From c325e9163bcbe60c8adf073c4088f0f5e9325fce Mon Sep 17 00:00:00 2001 From: zhangkai366 Date: Tue, 20 May 2025 16:17:13 +0800 Subject: [PATCH 001/145] Fix the bug that performance is not defined Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICDBY8 Test: grammar&ut Signed-off-by: zhangkai366 Change-Id: Iededcfe9a85127b15e12fe2ccd3b2e3ed46f1efb --- 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 3d5b31c78f..b8b714f8f8 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 f73cd5731c9cd25af261287ed14a5a3f2a0446fe Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Mon, 2 Jun 2025 00:13:57 +0800 Subject: [PATCH 002/145] Fix log decl bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICBVWC?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/scripts/arkui.properties | 2 +- .../compiler/ets/external_local_interface.ets | 18 +++++++++++++++ .../ets/external_local_interface_decl.ets | 22 +++++++++++++++++++ .../srcdumper/srcdumper-ets-ignored.txt | 1 + ets2panda/varbinder/varbinder.cpp | 13 +++++++++++ 5 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/external_local_interface.ets create mode 100644 ets2panda/test/ast/compiler/ets/external_local_interface_decl.ets diff --git a/ets2panda/scripts/arkui.properties b/ets2panda/scripts/arkui.properties index 0cbcc38439..54df76e008 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_8 +ARKUI_DEV_BRANCH=panda_rev_8-remove-primitives ARKUI_DEST=koala-sig diff --git a/ets2panda/test/ast/compiler/ets/external_local_interface.ets b/ets2panda/test/ast/compiler/ets/external_local_interface.ets new file mode 100644 index 0000000000..b17d69c20e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/external_local_interface.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 {foo} from "./external_local_interface_decl" + + diff --git a/ets2panda/test/ast/compiler/ets/external_local_interface_decl.ets b/ets2panda/test/ast/compiler/ets/external_local_interface_decl.ets new file mode 100644 index 0000000000..891e84f1a8 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/external_local_interface_decl.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 function foo() { + interface A{ + s:string + } + + let a:A = {s:""} +} \ 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 42b02135c1..cff206ab65 100644 --- a/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt +++ b/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt @@ -159,6 +159,7 @@ runtime/ets/import_declare_type_alias.ets ast/compiler/ets/import_type_without_export.ets ast/compiler/ets/type_binding_01.ets ast/compiler/ets/type_binding_02.ets +ast/compiler/ets/external_local_interface.ets # FailKind.ES2PANDA_FAIL runtime/ets/StringFasta.ets diff --git a/ets2panda/varbinder/varbinder.cpp b/ets2panda/varbinder/varbinder.cpp index 0504029b7b..d08635be49 100644 --- a/ets2panda/varbinder/varbinder.cpp +++ b/ets2panda/varbinder/varbinder.cpp @@ -470,6 +470,19 @@ void VarBinder::VisitScriptFunction(ir::ScriptFunction *func) } if (!BuildInternalName(func)) { + if (func->Body() == nullptr) { + return; + } + auto stmt = func->Body()->AsBlockStatement()->Statements(); + auto scopeCtx = LexicalScope::Enter(this, funcScope); + std::function doNode = [&](ir::AstNode *node) { + if (node->IsTSInterfaceDeclaration() || node->IsClassDeclaration() || node->IsTSEnumDeclaration() || + node->IsAnnotationDeclaration() || node->IsTSTypeAliasDeclaration()) { + ResolveReference(node); + } + node->Iterate([&](ir::AstNode *child) { doNode(child); }); + }; + doNode(func->Body()); return; } -- Gitee From 80d27622bfb01191d33d17231f7ccf93a7bc7fe0 Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Tue, 10 Jun 2025 14:36:32 +0800 Subject: [PATCH 003/145] Fix several bugs in fuzzing case Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICEB8F?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 | 28 +++++++++---------- 9 files changed, 120 insertions(+), 17 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 b0b3e32efd..7f9007daec 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 16c74fbdf2..1afba2af6d 100644 --- a/ets2panda/lexer/lexer.h +++ b/ets2panda/lexer/lexer.h @@ -422,13 +422,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: @@ -441,7 +442,7 @@ void Lexer::ScanString() continue; } case LEX_CHAR_BACKSLASH: { - validEscape &= HandleBackslashHelper(&str, &escapeEnd); + isFinalizedStr &= HandleBackslashHelper(&str, &escapeEnd); continue; } case LEX_CHAR_BACK_TICK: @@ -464,7 +465,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 f826f53499..8e8d168f73 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -1249,6 +1249,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 ff4089f8bd..9039a1b441 100644 --- a/ets2panda/parser/statementParser.cpp +++ b/ets2panda/parser/statementParser.cpp @@ -851,12 +851,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..63fb0322b1 --- /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 'end of stream'. */ +/* @@? 26:1 Error SyntaxError: Expected '}', got 'end of stream'. */ 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 a5017ce1b8..68f8b04937 100644 --- a/ets2panda/test/ast/parser/ets/unexpected_token_56.ets +++ b/ets2panda/test/ast/parser/ets/unexpected_token_56.ets @@ -13,21 +13,21 @@ * 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 */) /* @@ label7 */{ + /* @@ label8 */result = result + /* @@ label9 */p[i]!.awaitResolution() * /* @@ label10 */a[i]; } -for (let i? : Number = 1;;) { break; } +for (let i?: Number = 1;;) { break; } /* @@@ label1 Error SyntaxError: Unexpected token ';'. */ /* @@@ label2 Error SyntaxError: Unexpected token ';'. */ -/* @@? 16:44 Error TypeError: Unresolved reference i */ -/* @@? 16:44 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ -/* @@? 16:48 Error TypeError: Function name 'count' used in the wrong context */ -/* @@@ label3 Error SyntaxError: Expected ')', got ';'. */ -/* @@@ label Error SyntaxError: Unexpected token ')'. */ -/* @@? 16:89 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. */ +/* @@@ 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 ')'. */ +/* @@@ label7 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 e6503f0d231af94f9625bcaa2eb7f878ba3a1cf0 Mon Sep 17 00:00:00 2001 From: gizembusraturan Date: Tue, 20 May 2025 08:55:05 +0300 Subject: [PATCH 004/145] support declare struct Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICF80Z Description: It merged into branch 0411, but not into branch 0328 Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran ## --- 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 6a1ca88c8b..8161f7438f 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -2024,7 +2024,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 5fa13c6a135e2244c4c894f0c251718fc65fb8de Mon Sep 17 00:00:00 2001 From: dongchao Date: Thu, 12 Jun 2025 19:55:19 +0800 Subject: [PATCH 005/145] Fix incremental bug of filename case Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICG6LP Signed-off-by: dongchao Change-Id: I2bbb7a9890e4f6a1ea37c93b2563135286a5c7c3 --- .../driver/build_system/src/build/base_mode.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 99fad43361..e25ef54615 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -402,10 +402,16 @@ export abstract class BaseMode { private loadHashCache(): Record { try { - if (fs.existsSync(this.hashCacheFile)) { - const cacheContent = fs.readFileSync(this.hashCacheFile, 'utf-8'); - return JSON.parse(cacheContent); + if (!fs.existsSync(this.hashCacheFile)) { + return {}; } + + const cacheContent: string = fs.readFileSync(this.hashCacheFile, 'utf-8'); + const cacheData: Record = JSON.parse(cacheContent); + const filteredCache: Record = Object.fromEntries( + Object.entries(cacheData).filter(([file]) => this.entryFiles.has(file)) + ); + return filteredCache; } catch (error) { if (error instanceof Error) { const logData: LogData = LogDataFactory.newInstance( @@ -415,8 +421,8 @@ export abstract class BaseMode { ); this.logger.printError(logData); } + return {}; } - return {}; } private saveHashCache(): void { -- Gitee From 1bdbfcf51fb371efbe65af6b6f5cfa88272a623d Mon Sep 17 00:00:00 2001 From: dongchao Date: Mon, 16 Jun 2025 22:29:22 +0800 Subject: [PATCH 006/145] Avoid collecting unexist files in mixed scene Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICG6N3 Signed-off-by: dongchao Change-Id: Ibff99cf45f80175e8ffba22a5575bd4ca1de822e --- ets2panda/driver/build_system/src/build/base_mode.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 99fad43361..16ace8bf34 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -491,6 +491,11 @@ export abstract class BaseMode { processed.add(currentFile); (this.dependencyFileMap?.dependants[currentFile] || []).forEach(dependant => { + // For the 1.1 declaration file referenced in dynamicPaths, if a path is detected as non-existent, it will be skipped. + const isFileExist = fs.existsSync(dependant); + if (!isFileExist) { + return; + } if (!compileFiles.has(dependant) && !processed.has(dependant)) { queue.push(dependant); } -- Gitee From 9f0912cdddfc2fe0fa52fb0f85fd7840b3f2de40 Mon Sep 17 00:00:00 2001 From: Denis Slynko Date: Thu, 29 May 2025 11:07:53 +0300 Subject: [PATCH 007/145] [ArkTS] Rework Class.ofCaller Remove implementation of `GlobalClassHandler::FormDependentInitTriggers`. Right now its not used in any scenarios, but could be reused in future for `import "path"` feature (see #26183) Issue: #ICGD3V Signed-off-by: Denis Slynko --- .../ets/topLevelStmts/globalClassHandler.cpp | 23 ++++--------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp index a914f8ad66..ff2f8abf1b 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp @@ -431,26 +431,11 @@ ArenaVector GlobalClassHandler::FormInitMethodStatements(parser return statements; } -void GlobalClassHandler::FormDependentInitTriggers(ArenaVector &statements, - const ModuleDependencies *moduleDependencies) +void GlobalClassHandler::FormDependentInitTriggers([[maybe_unused]] ArenaVector &statements, + [[maybe_unused]] const ModuleDependencies *moduleDependencies) { - auto const sequence = [&statements](ir::Statement *stmt) { statements.push_back(stmt); }; - - auto triggerInitOf = [this, sequence, initialized = false](parser::Program *prog) mutable { - if (!initialized) { - initialized = true; - sequence(parser_->CreateFormattedStatement("const __linker = Class.ofCaller().getLinker();")); - } - auto name = std::string(prog->ModulePrefix()).append(Signatures::ETS_GLOBAL); - sequence(parser_->CreateFormattedStatement("__linker.loadClass(\"" + name + "\", true);")); - }; - - for (auto depProg : *moduleDependencies) { - if (util::Helpers::IsStdLib(depProg)) { - continue; - } - triggerInitOf(depProg); - } + // NOTE(dslynko, #26183): leaving this function for later reuse in `import "path"` feature, + // which would initialize the dependency. } ir::ClassStaticBlock *GlobalClassHandler::CreateStaticBlock(ir::ClassDefinition *classDef) -- Gitee From 1386d7b25b1de279560c0b55fa8bee2457635878 Mon Sep 17 00:00:00 2001 From: fanglou Date: Thu, 19 Jun 2025 14:35:46 +0800 Subject: [PATCH 008/145] Merge changes from 0328/linter into 0603 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICG74B Signed-off-by: fanglou Change-Id: I29b1e69693986b6a155ada045b84a9d07a54e5d0 --- ets2panda/linter/arkanalyzer/OAT.xml | 1 + .../arkanalyzer/config/arkanalyzer.json | 8 +- ets2panda/linter/arkanalyzer/src/Config.ts | 2 + ets2panda/linter/arkanalyzer/src/Scene.ts | 64 +- .../callgraph/algorithm/AbstractAnalysis.ts | 19 +- .../algorithm/ClassHierarchyAnalysis.ts | 7 +- .../callgraph/algorithm/RapidTypeAnalysis.ts | 3 +- .../src/callgraph/common/Statistics.ts | 5 +- .../src/callgraph/model/CallGraph.ts | 66 +- .../src/callgraph/model/CallSite.ts | 64 + .../model/builder/CallGraphBuilder.ts | 21 +- .../src/callgraph/pointerAnalysis/PTAUtils.ts | 1 + .../callgraph/pointerAnalysis/PagBuilder.ts | 48 +- .../pointerAnalysis/PointerAnalysis.ts | 3 +- .../pointerAnalysis/PointerAnalysisConfig.ts | 9 + .../linter/arkanalyzer/src/core/base/Expr.ts | 52 +- .../linter/arkanalyzer/src/core/base/Local.ts | 14 +- .../src/core/common/ArkIRTransformer.ts | 49 +- .../src/core/common/ArkValueTransformer.ts | 86 +- .../arkanalyzer/src/core/common/Builtin.ts | 4 +- .../src/core/common/DummyMainCreater.ts | 2 +- .../src/core/common/IRInference.ts | 126 +- .../arkanalyzer/src/core/common/ModelUtils.ts | 24 +- .../arkanalyzer/src/core/common/SdkUtils.ts | 170 +- .../src/core/common/TypeInference.ts | 89 +- .../arkanalyzer/src/core/common/ValueUtil.ts | 8 + .../src/core/dataflow/DataflowSolver.ts | 3 +- .../linter/arkanalyzer/src/core/graph/Scc.ts | 2 +- .../src/core/graph/builder/CfgBuilder.ts | 27 +- .../src/core/graph/builder/TrapBuilder.ts | 47 +- .../arkanalyzer/src/core/model/ArkMethod.ts | 87 +- .../src/core/model/builder/ArkClassBuilder.ts | 19 +- .../src/core/model/builder/ArkFieldBuilder.ts | 4 +- .../src/core/model/builder/ArkFileBuilder.ts | 4 +- .../core/model/builder/ArkMethodBuilder.ts | 11 +- .../core/model/builder/ArkNamespaceBuilder.ts | 8 +- .../src/core/model/builder/BodyBuilder.ts | 2 + .../arkanalyzer/src/save/JsonPrinter.ts | 104 +- .../arkanalyzer/src/save/source/SourceBody.ts | 5 +- .../arkanalyzer/src/save/source/SourceStmt.ts | 33 +- .../src/save/source/SourceTransformer.ts | 31 +- .../StaticSingleAssignmentFormer.ts | 2 +- .../arkanalyzer/src/utils/SparseBitVector.ts | 1 - ets2panda/linter/arkanalyzer/typedoc.json | 1 + ets2panda/linter/build_linter.py | 16 +- ets2panda/linter/homecheck/ruleSet.json | 6 +- ets2panda/linter/homecheck/src/Index.ts | 2 +- .../checker/migration/AppStorageGetCheck.ts | 2 +- .../checker/migration/CustomBuilderCheck.ts | 19 +- .../checker/migration/InteropAssignCheck.ts | 6 +- .../migration/InteropBackwardDFACheck.ts | 13 +- .../migration/InteropBoxedTypeCheck.ts | 2 +- .../InteropDeprecatedBuiltInAPICheck.ts | 928 +++++++ .../migration/InteropJSModifyPropertyCheck.ts | 6 +- .../InteropS2DObjectLiteralsCheck.ts | 347 +++ .../checker/migration/ModifyStateVarCheck.ts | 2 +- .../src/checker/migration/NoTSLikeAsCheck.ts | 231 +- .../checker/migration/ObjectLiteralCheck.ts | 7 +- .../migration/ObservedDecoratorCheck.ts | 6 +- .../src/checker/migration/ThisBindCheck.ts | 16 +- .../homecheck/src/checker/migration/Utils.ts | 33 +- .../src/tools/migrationTool/MigrationTool.ts | 12 +- .../src/utils/common/CheckerIndex.ts | 4 + .../src/utils/common/CheckerStorage.ts | 5 + .../homecheck/src/utils/common/FileUtils.ts | 4 +- ets2panda/linter/package.json | 2 +- ets2panda/linter/src/cli/CommandLineParser.ts | 9 +- ets2panda/linter/src/cli/LinterCLI.ts | 23 +- .../linter/src/lib/BaseTypeScriptLinter.ts | 9 +- .../linter/src/lib/CommandLineOptions.ts | 1 + ets2panda/linter/src/lib/CookBookMsg.ts | 15 +- ets2panda/linter/src/lib/FaultAttrs.ts | 4 +- ets2panda/linter/src/lib/FaultDesc.ts | 2 +- ets2panda/linter/src/lib/HomeCheck.ts | 15 +- ets2panda/linter/src/lib/LinterOptions.ts | 1 + ets2panda/linter/src/lib/LinterRunner.ts | 41 +- ets2panda/linter/src/lib/Problems.ts | 2 +- ets2panda/linter/src/lib/TypeScriptLinter.ts | 2116 +++++++++++----- .../linter/src/lib/autofixes/AutofixTitles.ts | 5 +- .../linter/src/lib/autofixes/Autofixer.ts | 939 ++++++- .../linter/src/lib/autofixes/QuasiEditor.ts | 29 +- ets2panda/linter/src/lib/utils/TsUtils.ts | 46 +- .../src/lib/utils/consts/ArkTS2Rules.ts | 8 +- .../src/lib/utils/consts/ArkTSUtilsAPI.ts | 2 + .../src/lib/utils/consts/ArkuiConstants.ts | 8 +- .../src/lib/utils/consts/ArkuiImportList.ts | 5 + .../linter/src/lib/utils/consts/ArraysAPI.ts | 49 + .../src/lib/utils/consts/AssociatedInfo.ts | 22 + .../lib/utils/consts/ErrorProp.ts} | 8 +- .../linter/src/lib/utils/consts/InteropAPI.ts | 17 +- .../src/lib/utils/consts/RuntimeCheckAPI.ts | 2 +- .../builtin_symbol_iterator.ets.arkts2.json | 10 + .../builtin/builtin_symbol_iterator.ets.json | 13 +- .../linter/test/concurrent/@ohos.taskpool.ets | 25 + .../concurrent/@ohos.taskpool.ets.args.json | 18 + .../test/concurrent/@ohos.taskpool.ets.json | 17 + .../concurrent_sharedarraybuffer1_arkts2.ets | 29 + ...nt_sharedarraybuffer1_arkts2.ets.args.json | 21 + ..._sharedarraybuffer1_arkts2.ets.arkts2.json | 58 + ...sharedarraybuffer1_arkts2.ets.autofix.json | 102 + ...current_sharedarraybuffer1_arkts2.ets.json | 17 + ..._sharedarraybuffer1_arkts2.ets.migrate.ets | 29 + ...sharedarraybuffer1_arkts2.ets.migrate.json | 3 + .../concurrent_sharedarraybuffer_arkts2.ets | 8 +- ...t_sharedarraybuffer_arkts2.ets.arkts2.json | 22 +- ..._sharedarraybuffer_arkts2.ets.autofix.json | 54 +- ...t_sharedarraybuffer_arkts2.ets.migrate.ets | 8 +- .../no_support_isconcurrent.ets.arkts2.json | 24 +- .../concurrent/no_support_isconcurrent2.ets | 42 + .../no_support_isconcurrent2.ets.args.json | 19 + .../no_support_isconcurrent2.ets.arkts2.json | 58 + .../no_support_isconcurrent2.ets.json | 17 + .../oh_modules/sharedArrayBuffer.ts | 32 + .../test/interop/binary_operation_js_obj.ets | 25 +- .../binary_operation_js_obj.ets.args.json | 42 +- .../binary_operation_js_obj.ets.arkts2.json | 254 +- .../binary_operation_js_obj.ets.autofix.json | 683 +++++- .../interop/binary_operation_js_obj.ets.json | 12 +- .../binary_operation_js_obj.ets.migrate.ets | 29 +- .../binary_operation_js_obj.ets.migrate.json | 66 +- .../interop/binary_operation_js_obj_js.js | 2 + .../linter/test/interop/call_function.ets | 35 +- .../interop/call_function.ets.arkts2.json | 26 +- .../test/interop/call_function.ets.json | 13 +- .../test/interop/call_object_methods.ets | 1 - .../call_object_methods.ets.arkts2.json | 22 +- .../call_object_methods.ets.autofix.json | 62 +- .../test/interop/call_object_methods.ets.json | 13 +- .../call_object_methods.ets.migrate.ets | 1 - .../call_object_methods.ets.migrate.json | 10 +- .../interop/increases_decreases_js_obj.ets | 6 +- .../increases_decreases_js_obj.ets.args.json | 42 +- ...increases_decreases_js_obj.ets.arkts2.json | 138 +- ...ncreases_decreases_js_obj.ets.autofix.json | 338 ++- .../increases_decreases_js_obj.ets.json | 13 +- ...increases_decreases_js_obj.ets.migrate.ets | 38 +- ...ncreases_decreases_js_obj.ets.migrate.json | 48 +- .../test/interop/instantiated_js_obj.ets | 1 - .../instantiated_js_obj.ets.arkts2.json | 58 +- .../instantiated_js_obj.ets.autofix.json | 164 +- .../test/interop/instantiated_js_obj.ets.json | 13 +- .../instantiated_js_obj.ets.migrate.ets | 1 - .../instantiated_js_obj.ets.migrate.json | 14 +- .../test/interop/interop_convert_import.ets | 26 +- .../interop_convert_import.ets.arkts2.json | 494 ++-- .../interop_convert_import.ets.autofix.json | 300 +-- .../interop/interop_convert_import.ets.json | 54 +- .../interop_convert_import.ets.migrate.ets | 90 +- .../interop_convert_import.ets.migrate.json | 38 +- .../interop/interop_equality_judgment.ets | 1 - .../interop_equality_judgment.ets.arkts2.json | 26 +- ...interop_equality_judgment.ets.autofix.json | 90 +- .../interop_equality_judgment.ets.json | 13 +- .../interop_equality_judgment.ets.migrate.ets | 1 - ...interop_equality_judgment.ets.migrate.json | 14 +- .../test/interop/interop_export_js_rules.ets | 1 - .../interop_export_js_rules.ets.arkts2.json | 174 +- .../interop/interop_export_js_rules.ets.json | 43 +- .../linter/test/interop/interop_import_js.ets | 1 - .../interop/interop_import_js.ets.arkts2.json | 86 +- .../interop_import_js.ets.autofix.json | 238 +- .../test/interop/interop_import_js.ets.json | 73 +- .../interop/interop_import_js.ets.migrate.ets | 1 - .../interop_import_js.ets.migrate.json | 50 +- .../interop/interop_import_js_compare.ets | 1 - .../interop_import_js_compare.ets.args.json | 14 +- .../interop_import_js_compare.ets.arkts2.json | 150 +- ...interop_import_js_compare.ets.autofix.json | 624 +++++ .../interop_import_js_compare.ets.json | 14 +- .../interop_import_js_compare.ets.migrate.ets | 51 + ...interop_import_js_compare.ets.migrate.json | 78 + .../test/interop/interop_import_js_index.ets | 20 +- .../interop_import_js_index.ets.arkts2.json | 218 +- .../interop_import_js_index.ets.autofix.json | 448 +++- .../interop/interop_import_js_index.ets.json | 13 +- .../interop_import_js_index.ets.migrate.ets | 29 +- .../interop_import_js_index.ets.migrate.json | 58 +- .../test/interop/interop_import_js_rules.ets | 11 + .../interop_import_js_rules.ets.arkts2.json | 234 +- .../interop_import_js_rules.ets.autofix.json | 2168 ++++++++-------- .../interop/interop_import_js_rules.ets.json | 28 +- .../test/interop/interop_import_typeof_js.ets | 3 +- .../interop_import_typeof_js.ets.arkts2.json | 924 ++++--- .../interop_import_typeof_js.ets.autofix.json | 1792 +++++++------- .../interop/interop_import_typeof_js.ets.json | 33 +- .../interop_import_typeof_js.ets.migrate.ets | 9 +- .../interop_import_typeof_js.ets.migrate.json | 334 +-- .../interop_not_have_property_arkts2.ets | 46 +- ...p_not_have_property_arkts2.ets.arkts2.json | 428 +++- ..._not_have_property_arkts2.ets.autofix.json | 934 ++++++- .../interop_not_have_property_arkts2.ets.json | 12 +- ...p_not_have_property_arkts2.ets.migrate.ets | 49 +- ..._not_have_property_arkts2.ets.migrate.json | 212 +- .../interop/interop_not_have_property_js.js | 59 +- .../interop_not_have_property_num_arkts2.ets | 1 - ...t_have_property_num_arkts2.ets.arkts2.json | 132 +- ..._have_property_num_arkts2.ets.autofix.json | 338 +-- ...erop_not_have_property_num_arkts2.ets.json | 13 +- ...t_have_property_num_arkts2.ets.migrate.ets | 1 - ..._have_property_num_arkts2.ets.migrate.json | 34 +- .../test/interop/no_await_js_promise.ets | 127 +- .../interop/no_await_js_promise.ets.args.json | 4 +- .../no_await_js_promise.ets.arkts2.json | 136 +- .../no_await_js_promise.ets.autofix.json | 278 +++ .../test/interop/no_await_js_promise.ets.json | 18 +- .../no_await_js_promise.ets.migrate.ets | 70 + .../no_await_js_promise.ets.migrate.json | 188 ++ .../linter/test/interop/no_js_instanceof.ets | 1 - .../interop/no_js_instanceof.ets.args.json | 4 +- .../interop/no_js_instanceof.ets.arkts2.json | 92 +- .../interop/no_js_instanceof.ets.autofix.json | 394 +++ .../test/interop/no_js_instanceof.ets.json | 38 +- .../interop/no_js_instanceof.ets.migrate.ets | 83 + .../interop/no_js_instanceof.ets.migrate.json | 118 + .../linter/test/interop/object_built_in.ets | 2 +- .../interop/object_built_in.ets.arkts2.json | 22 +- .../test/interop/object_built_in.ets.json | 22 +- .../interop/object_literal_constructor.ets | 1 - ...object_literal_constructor.ets.arkts2.json | 82 +- .../object_literal_constructor.ets.json | 18 +- .../interop/object_literal_union_type.ets | 1 - .../object_literal_union_type.ets.arkts2.json | 38 +- .../object_literal_union_type.ets.json | 23 +- .../object_literal_union_type_arkts2.ets | 1 - .../interop/oh_modules/reflect_export.ets | 35 +- .../static_object_literals_export.ets | 1 - .../linter/test/interop/reflect_built_in.ets | 33 +- .../interop/reflect_built_in.ets.arkts2.json | 324 ++- .../test/interop/reflect_built_in.ets.json | 278 ++- .../test/interop/static_dynamic_import.ets | 24 + .../static_dynamic_import.ets.arkts2.json | 98 + .../static_dynamic_import.ets.json} | 40 +- .../interop/static_object_literals.ets.json | 63 +- .../unary_operation_js_obj.ets} | 15 +- .../unary_operation_js_obj.ets.args.json | 21 + .../unary_operation_js_obj.ets.arkts2.json | 94 + .../unary_operation_js_obj.ets.autofix.json | 216 ++ .../interop/unary_operation_js_obj.ets.json | 3 + .../unary_operation_js_obj.ets.migrate.ets | 22 + .../unary_operation_js_obj.ets.migrate.json | 68 + .../test/interop/unary_operation_js_obj_js.js | 16 + .../linter/test/interop/unique_types.ets | 1 - .../test/interop/unique_types.ets.arkts2.json | 46 +- .../interop/unique_types.ets.autofix.json | 62 +- .../linter/test/interop/unique_types.ets.json | 27 +- .../test/interop/unique_types.ets.migrate.ets | 1 - .../interop/unique_types.ets.migrate.json | 38 +- ets2panda/linter/test/main/@ohos.taskpool.ets | 36 + .../test/main/@ohos.taskpool.ets.args.json | 18 + .../linter/test/main/@ohos.taskpool.ets.json | 17 + ...matable_extend_decorator_1.ets.arkts2.json | 16 +- ...atable_extend_decorator_1.ets.autofix.json | 16 +- .../test/main/arkts-array-type-immutable.ets | 121 +- ...arkts-array-type-immutable.ets.arkts2.json | 580 +++++ .../main/arkts-array-type-immutable.ets.json | 63 +- .../linter/test/main/arktsutils_module.ets | 2 + .../main/arktsutils_module.ets.arkts2.json | 10 + .../main/arktsutils_module.ets.autofix.json | 54 + .../main/arktsutils_module.ets.migrate.ets | 10 +- .../main/arktsutils_module.ets.migrate.json | 50 +- .../test/main/array_index_expr_type.ets | 4 + .../array_index_expr_type.ets.arkts2.json | 330 ++- .../array_index_expr_type.ets.autofix.json | 387 ++- .../array_index_expr_type.ets.migrate.ets | 6 +- .../array_index_expr_type.ets.migrate.json | 70 + .../linter/test/main/class_as_object.ets | 11 +- .../test/main/class_as_object.ets.arkts2.json | 62 +- .../linter/test/main/class_as_object.ets.json | 40 - .../linter/test/main/class_no_constructor.ets | 10 + .../main/class_no_constructor.ets.arkts2.json | 32 +- .../main/class_no_constructor.ets.migrate.ets | 10 + .../class_no_constructor.ets.migrate.json | 32 +- .../main/class_static_init.ets.arkts2.json | 8 +- ets2panda/linter/test/main/comment_test.ets | 23 + .../test/main/comment_test.ets.args.json | 21 + .../test/main/comment_test.ets.arkts2.json | 68 + .../test/main/comment_test.ets.autofix.json | 123 + ...ets.migrate.json => comment_test.ets.json} | 0 .../test/main/comment_test.ets.migrate.ets | 23 + ...ets.json => comment_test.ets.migrate.json} | 0 ets2panda/linter/test/main/custom_layout.ets | 40 +- .../test/main/custom_layout.ets.arkts2.json | 474 +++- .../test/main/custom_layout.ets.autofix.json | 1192 ++++++--- .../linter/test/main/custom_layout.ets.json | 14 +- .../test/main/custom_layout.ets.migrate.ets | 47 +- .../test/main/custom_layout.ets.migrate.json | 24 +- .../main/debugger_statememt.ets.args.json | 4 +- .../main/debugger_statememt.ets.arkts2.json | 4 +- .../test/main/default_required_args.ets | 13 + .../default_required_args.ets.arkts2.json | 20 + .../main/dollar_binding_1.ets.arkts2.json | 16 +- .../main/dollar_binding_1.ets.autofix.json | 16 +- .../double_dollar_binding_1.ets.arkts2.json | 20 +- .../double_dollar_binding_1.ets.autofix.json | 20 +- .../double_excla_binding_1.ets.arkts2.json | 70 +- .../double_excla_binding_1.ets.autofix.json | 70 +- .../test/main/double_excla_binding_3.ets | 32 + .../main/double_excla_binding_3.ets.args.json | 21 + .../double_excla_binding_3.ets.arkts2.json | 88 + .../double_excla_binding_3.ets.autofix.json | 165 ++ .../test/main/double_excla_binding_3.ets.json | 17 + ...=> double_excla_binding_3.ets.migrate.ets} | 41 +- .../double_excla_binding_3.ets.migrate.json | 17 + .../main/dynamic_ctor_call.ets.arkts2.json | 10 + .../test/main/dynamic_import.ets.arkts2.json | 2 +- .../entry_annotation_test8_1.ets.autofix.json | 13 +- .../entry_annotation_test8_1.ets.migrate.ets | 4 +- .../entry_annotation_test8_1.ets.migrate.json | 8 +- .../entry_annotation_test8_2.ets.autofix.json | 7 - .../entry_annotation_test8_2.ets.migrate.ets | 2 +- .../entry_annotation_test8_2.ets.migrate.json | 8 +- .../entry_annotation_test9_1.ets.autofix.json | 13 +- .../entry_annotation_test9_1.ets.migrate.ets | 2 +- .../entry_annotation_test9_1.ets.migrate.json | 13 +- .../entry_annotation_test9_2.ets.autofix.json | 7 - .../entry_annotation_test9_2.ets.migrate.ets | 2 +- .../entry_annotation_test9_2.ets.migrate.json | 13 +- .../enum_not_support_float.ets.arkts2.json | 10 + .../explicit_function_type.ets.arkts2.json | 20 + .../explicit_function_type.ets.autofix.json | 45 +- .../explicit_function_type.ets.migrate.ets | 14 +- .../explicit_function_type.ets.migrate.json | 10 + .../test/main/exponent.ets.autofix.json | 4 +- .../main/extend_decorator_1.ets.arkts2.json | 8 +- .../main/extend_decorator_1.ets.autofix.json | 8 +- .../func_inferred_type_args.ets.arkts2.json | 10 + .../test/main/func_inferred_type_args_2.ets | 24 +- .../func_inferred_type_args_2.ets.arkts2.json | 350 ++- ...func_inferred_type_args_2.ets.autofix.json | 599 ++++- .../main/func_inferred_type_args_2.ets.json | 44 +- .../func_inferred_type_args_2.ets.migrate.ets | 25 + ...func_inferred_type_args_2.ets.migrate.json | 170 +- .../test/main/global_this.ets.args.json | 4 +- .../test/main/index_negative.ets.arkts2.json | 500 +++- .../main/interface_import_1.ets.arkts2.json | 30 +- .../main/interface_import_1.ets.autofix.json | 30 +- .../main/interface_import_3.ets.arkts2.json | 4 +- .../main/interface_import_3.ets.autofix.json | 4 +- .../linter/test/main/interface_import_4.ets | 44 + .../main/interface_import_4.ets.args.json | 21 + .../main/interface_import_4.ets.arkts2.json | 248 ++ .../main/interface_import_4.ets.autofix.json | 490 ++++ ...e.ets.json => interface_import_4.ets.json} | 0 .../main/interface_import_4.ets.migrate.ets | 46 + ...on => interface_import_4.ets.migrate.json} | 12 +- .../main/invalid_identifier.ets.arkts2.json | 46 +- .../linter/test/main/limit_void_type.ets | 138 +- .../test/main/limit_void_type.ets.args.json | 36 +- .../test/main/limit_void_type.ets.arkts2.json | 378 ++- .../main/limit_void_type.ets.autofix.json | 2182 +++++++++++++++++ .../linter/test/main/limit_void_type.ets.json | 36 +- .../test/main/limit_void_type.ets.migrate.ets | 273 +++ .../main/limit_void_type.ets.migrate.json | 468 ++++ .../main/limited_stdlib_api.ets.arkts2.json | 170 ++ .../test/main/limited_stdlib_api.ets.json | 170 ++ .../test/main/literals_as_prop_names.ets | 20 +- .../literals_as_prop_names.ets.arkts2.json | 294 ++- .../literals_as_prop_names.ets.autofix.json | 461 +++- .../test/main/literals_as_prop_names.ets.json | 30 + .../literals_as_prop_names.ets.migrate.ets | 34 +- .../literals_as_prop_names.ets.migrate.json | 110 + .../test/main/localBuilder_1.ets.arkts2.json | 12 +- .../test/main/localBuilder_1.ets.autofix.json | 54 +- .../test/main/make_observed_1.ets.arkts2.json | 14 +- .../test/main/make_observed_2.ets.arkts2.json | 14 +- .../test/main/make_observed_3.ets.arkts2.json | 16 +- .../linter/test/main/method_inheritance.ets | 129 +- .../main/method_inheritance.ets.arkts2.json | 160 ++ .../linter/test/main/no_sparse_array.ets | 3 +- .../test/main/no_sparse_array.ets.arkts2.json | 10 + .../test/main/no_ts_like_smart_type.ets | 58 +- .../no_ts_like_smart_type.ets.arkts2.json | 86 +- .../test/main/no_ts_like_smart_type.ets.json | 13 +- .../linter/test/main/no_tuples_arrays.ets | 42 +- .../main/no_tuples_arrays.ets.arkts2.json | 380 ++- .../linter/test/main/numeric_semantics.ets | 24 +- .../main/numeric_semantics.ets.arkts2.json | 168 +- .../main/numeric_semantics.ets.autofix.json | 334 ++- .../main/numeric_semantics.ets.migrate.ets | 28 +- .../main/numeric_semantics.ets.migrate.json | 10 + .../main/numeric_semantics2.ets.arkts2.json | 40 + .../main/numeric_semantics2.ets.autofix.json | 62 + .../main/numeric_semantics2.ets.migrate.ets | 4 +- .../main/numeric_semantics2.ets.migrate.json | 20 + .../test/main/object_literals_properties.ets | 35 +- ...object_literals_properties.ets.arkts2.json | 234 +- ...bject_literals_properties.ets.autofix.json | 483 +++- .../main/object_literals_properties.ets.json | 18 +- ...object_literals_properties.ets.migrate.ets | 74 +- ...bject_literals_properties.ets.migrate.json | 152 +- .../main/parameter_properties.ets.arkts2.json | 10 + .../parameter_properties.ets.autofix.json | 10 + .../parameter_properties.ets.migrate.json | 10 + ...s => prop_decorators_and_interfaces_1.ets} | 0 ..._decorators_and_interfaces_1.ets.args.json | 21 + ...corators_and_interfaces_1.ets.arkts2.json} | 40 +- ...corators_and_interfaces_1.ets.autofix.json | 207 ++ ...prop_decorators_and_interfaces_1.ets.json} | 4 +- ...ecorators_and_interfaces_1.ets.migrate.ets | 43 + ...orators_and_interfaces_1.ets.migrate.json} | 46 +- ...s => prop_decorators_and_interfaces_2.ets} | 0 ...decorators_and_interfaces_2.ets.args.json} | 0 ...corators_and_interfaces_2.ets.arkts2.json} | 38 +- ...prop_decorators_and_interfaces_2.ets.json} | 0 ...s => prop_decorators_and_interfaces_3.ets} | 0 ...decorators_and_interfaces_3.ets.args.json} | 0 ...corators_and_interfaces_3.ets.arkts2.json} | 8 +- ...prop_decorators_and_interfaces_3.ets.json} | 0 .../main/prop_decorators_and_interfaces_4.ets | 108 + ..._decorators_and_interfaces_4.ets.args.json | 21 + ...ecorators_and_interfaces_4.ets.arkts2.json | 428 ++++ ...corators_and_interfaces_4.ets.autofix.json | 846 +++++++ .../prop_decorators_and_interfaces_4.ets.json | 17 + ...ecorators_and_interfaces_4.ets.migrate.ets | 112 + ...corators_and_interfaces_4.ets.migrate.json | 78 + .../test/main/property_access_by_index.ets | 12 + .../property_access_by_index.ets.args.json | 4 +- .../property_access_by_index.ets.arkts2.json | 280 +++ .../property_access_by_index.ets.autofix.json | 1503 ++++++++++++ .../main/property_access_by_index.ets.json | 10 + .../property_access_by_index.ets.migrate.ets | 66 +- .../property_access_by_index.ets.migrate.json | 402 ++- ets2panda/linter/test/main/props_by_index.ets | 50 + ...args.json => props_by_index.ets.args.json} | 0 ...ix.json => props_by_index.ets.arkts2.json} | 235 +- .../linter/test/main/props_by_index.ets.json | 17 + .../main/provide_annotation_1.ets.arkts2.json | 20 +- .../provide_annotation_1.ets.autofix.json | 84 +- .../main/provide_annotation_2.ets.arkts2.json | 18 +- .../provide_annotation_2.ets.autofix.json | 72 +- .../linter/test/main/runtime_array_bound.ets | 77 + .../main/runtime_array_bound.ets.arkts2.json | 1190 ++++++++- .../main/runtime_array_bound.ets.migrate.ets | 77 + .../main/runtime_array_bound.ets.migrate.json | 134 +- .../test/main/stdlib_array.ets.arkts2.json | 20 + .../linter/test/main/structural_identity.ets | 13 +- .../main/structural_identity.ets.arkts2.json | 40 + ...ntity_extended_inheritance.ets.arkts2.json | 10 + .../styles_decorator_anon_1.ets.arkts2.json | 12 +- .../styles_decorator_anon_1.ets.autofix.json | 12 +- .../styles_decorator_global_1.ets.arkts2.json | 18 +- ...styles_decorator_global_1.ets.autofix.json | 18 +- .../styles_decorator_mix_1.ets.arkts2.json | 38 +- .../styles_decorator_mix_1.ets.autofix.json | 188 +- .../styles_decorator_struct_1.ets.arkts2.json | 46 +- ...styles_decorator_struct_1.ets.autofix.json | 46 +- ...styles_decorator_struct_1.ets.migrate.json | 10 + .../styles_decorator_struct_2.ets.arkts2.json | 10 + ...styles_decorator_struct_2.ets.autofix.json | 10 + ...styles_decorator_struct_2.ets.migrate.json | 10 + .../test/main/swicth_expr.ets.arkts2.json | 20 + .../test/main/taskpool_deprecated_usages.ets | 52 +- ...taskpool_deprecated_usages.ets.arkts2.json | 428 +++- .../main/taskpool_deprecated_usages.ets.json | 106 +- .../test/main/taskpool_deprecated_usages2.ets | 33 + .../taskpool_deprecated_usages2.ets.args.json | 19 + ...askpool_deprecated_usages2.ets.arkts2.json | 88 + .../main/taskpool_deprecated_usages2.ets.json | 28 + .../test/main/taskpool_deprecated_usages3.ets | 22 + .../taskpool_deprecated_usages3.ets.args.json | 19 + ...askpool_deprecated_usages3.ets.arkts2.json | 48 + .../main/taskpool_deprecated_usages3.ets.json | 28 + .../linter/test/main/ts-like-catch-type.ets | 20 +- .../main/ts-like-catch-type.ets.arkts2.json | 58 +- .../test/main/ts-like-catch-type.ets.json | 23 +- .../test/main/ts_overload.ets.arkts2.json | 24 +- ets2panda/linter/test/rules/rule144.ets.json | 170 ++ .../linter/test/rules/rule37.ets.migrate.json | 13 +- ...cl_with_duplicate_name_sdk.ets.arkts2.json | 16 +- .../limit_void_type_sdk.ets.arkts2.json | 30 + .../limit_void_type_sdk2.ets.arkts2.json | 34 +- .../test/sdkwhite/limit_void_type_sdk3.ets | 14 +- .../limit_void_type_sdk3.ets.arkts2.json | 70 +- ...phen_props_deprecated_sdk2.ets.arkts2.json | 20 + .../test/sdkwhite/sdk_constructor_funcs.ets | 28 +- .../sdk_constructor_funcs.ets.arkts2.json | 196 +- .../sdkwhite/sdk_constructor_funcs.ets.json | 43 +- .../sdkwhite/sdk_type_query.ets.arkts2.json | 10 + ets2panda/package-lock.json | 6 + 479 files changed, 37670 insertions(+), 9667 deletions(-) create mode 100644 ets2panda/linter/arkanalyzer/src/callgraph/model/CallSite.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/InteropDeprecatedBuiltInAPICheck.ts create mode 100644 ets2panda/linter/homecheck/src/checker/migration/InteropS2DObjectLiteralsCheck.ts create mode 100755 ets2panda/linter/src/lib/utils/consts/ArraysAPI.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/AssociatedInfo.ts rename ets2panda/linter/{test/main/debugger_statememt.ets.migrate.ets => src/lib/utils/consts/ErrorProp.ts} (85%) create mode 100755 ets2panda/linter/test/concurrent/@ohos.taskpool.ets create mode 100755 ets2panda/linter/test/concurrent/@ohos.taskpool.ets.args.json create mode 100755 ets2panda/linter/test/concurrent/@ohos.taskpool.ets.json create mode 100755 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets create mode 100755 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.args.json create mode 100755 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.arkts2.json create mode 100755 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.autofix.json create mode 100755 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.json create mode 100755 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.migrate.ets create mode 100755 ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.migrate.json create mode 100755 ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets create mode 100755 ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.args.json create mode 100755 ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.arkts2.json create mode 100755 ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.json create mode 100755 ets2panda/linter/test/concurrent/oh_modules/sharedArrayBuffer.ts mode change 100755 => 100644 ets2panda/linter/test/interop/binary_operation_js_obj.ets mode change 100755 => 100644 ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json mode change 100755 => 100644 ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json mode change 100755 => 100644 ets2panda/linter/test/interop/increases_decreases_js_obj.ets mode change 100755 => 100644 ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json mode change 100755 => 100644 ets2panda/linter/test/interop/increases_decreases_js_obj.ets.autofix.json mode change 100755 => 100644 ets2panda/linter/test/interop/interop_convert_import.ets mode change 100755 => 100644 ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json mode change 100755 => 100644 ets2panda/linter/test/interop/interop_import_js.ets create mode 100644 ets2panda/linter/test/interop/interop_import_js_compare.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.json mode change 100755 => 100644 ets2panda/linter/test/interop/interop_import_typeof_js.ets mode change 100755 => 100644 ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json mode change 100755 => 100644 ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json mode change 100755 => 100644 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets mode change 100755 => 100644 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.arkts2.json mode change 100755 => 100644 ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.autofix.json mode change 100755 => 100644 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets mode change 100755 => 100644 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.arkts2.json mode change 100755 => 100644 ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets.autofix.json mode change 100755 => 100644 ets2panda/linter/test/interop/no_await_js_promise.ets mode change 100755 => 100644 ets2panda/linter/test/interop/no_await_js_promise.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/no_await_js_promise.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.json mode change 100755 => 100644 ets2panda/linter/test/interop/no_js_instanceof.ets mode change 100755 => 100644 ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/no_js_instanceof.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/static_dynamic_import.ets create mode 100644 ets2panda/linter/test/interop/static_dynamic_import.ets.arkts2.json rename ets2panda/linter/test/{main/global_this.ets.migrate.json => interop/static_dynamic_import.ets.json} (67%) rename ets2panda/linter/test/{main/prop_name_from_value.ets => interop/unary_operation_js_obj.ets} (80%) create mode 100644 ets2panda/linter/test/interop/unary_operation_js_obj.ets.args.json create mode 100644 ets2panda/linter/test/interop/unary_operation_js_obj.ets.arkts2.json create mode 100644 ets2panda/linter/test/interop/unary_operation_js_obj.ets.autofix.json create mode 100644 ets2panda/linter/test/interop/unary_operation_js_obj.ets.json create mode 100644 ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.ets create mode 100644 ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.json create mode 100644 ets2panda/linter/test/interop/unary_operation_js_obj_js.js create mode 100755 ets2panda/linter/test/main/@ohos.taskpool.ets create mode 100755 ets2panda/linter/test/main/@ohos.taskpool.ets.args.json create mode 100755 ets2panda/linter/test/main/@ohos.taskpool.ets.json mode change 100755 => 100644 ets2panda/linter/test/main/class_static_init.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/comment_test.ets create mode 100644 ets2panda/linter/test/main/comment_test.ets.args.json create mode 100644 ets2panda/linter/test/main/comment_test.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/comment_test.ets.autofix.json rename ets2panda/linter/test/main/{debugger_statememt.ets.migrate.json => comment_test.ets.json} (100%) create mode 100644 ets2panda/linter/test/main/comment_test.ets.migrate.ets rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_1.ets.json => comment_test.ets.migrate.json} (100%) create mode 100644 ets2panda/linter/test/main/double_excla_binding_3.ets create mode 100644 ets2panda/linter/test/main/double_excla_binding_3.ets.args.json create mode 100644 ets2panda/linter/test/main/double_excla_binding_3.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/double_excla_binding_3.ets.autofix.json create mode 100644 ets2panda/linter/test/main/double_excla_binding_3.ets.json rename ets2panda/linter/test/main/{global_this.ets.migrate.ets => double_excla_binding_3.ets.migrate.ets} (50%) create mode 100644 ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.json create mode 100644 ets2panda/linter/test/main/interface_import_4.ets create mode 100644 ets2panda/linter/test/main/interface_import_4.ets.args.json create mode 100644 ets2panda/linter/test/main/interface_import_4.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/interface_import_4.ets.autofix.json rename ets2panda/linter/test/main/{prop_name_from_value.ets.json => interface_import_4.ets.json} (100%) create mode 100644 ets2panda/linter/test/main/interface_import_4.ets.migrate.ets rename ets2panda/linter/test/main/{prop_name_from_value.ets.arkts2.json => interface_import_4.ets.migrate.json} (75%) create mode 100644 ets2panda/linter/test/main/limit_void_type.ets.autofix.json create mode 100644 ets2panda/linter/test/main/limit_void_type.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/limit_void_type.ets.migrate.json mode change 100755 => 100644 ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json mode change 100755 => 100644 ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_1.ets => prop_decorators_and_interfaces_1.ets} (100%) create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.args.json rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_1.ets.arkts2.json => prop_decorators_and_interfaces_1.ets.arkts2.json} (68%) create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.autofix.json rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_3.ets.args.json => prop_decorators_and_interfaces_1.ets.json} (94%) create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.ets rename ets2panda/linter/test/main/{debugger_statememt.ets.autofix.json => prop_decorators_and_interfaces_1.ets.migrate.json} (52%) rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_2.ets => prop_decorators_and_interfaces_2.ets} (100%) rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_1.ets.args.json => prop_decorators_and_interfaces_2.ets.args.json} (100%) rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_2.ets.arkts2.json => prop_decorators_and_interfaces_2.ets.arkts2.json} (84%) rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_2.ets.json => prop_decorators_and_interfaces_2.ets.json} (100%) rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_3.ets => prop_decorators_and_interfaces_3.ets} (100%) rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_2.ets.args.json => prop_decorators_and_interfaces_3.ets.args.json} (100%) rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_3.ets.arkts2.json => prop_decorators_and_interfaces_3.ets.arkts2.json} (96%) rename ets2panda/linter/test/main/{prop_decorator_and_interfaces_3.ets.json => prop_decorators_and_interfaces_3.ets.json} (100%) create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.args.json create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.autofix.json create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.json create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.json create mode 100644 ets2panda/linter/test/main/props_by_index.ets rename ets2panda/linter/test/main/{prop_name_from_value.ets.args.json => props_by_index.ets.args.json} (100%) rename ets2panda/linter/test/main/{global_this.ets.autofix.json => props_by_index.ets.arkts2.json} (36%) mode change 100755 => 100644 create mode 100644 ets2panda/linter/test/main/props_by_index.ets.json create mode 100755 ets2panda/linter/test/main/taskpool_deprecated_usages2.ets create mode 100755 ets2panda/linter/test/main/taskpool_deprecated_usages2.ets.args.json create mode 100755 ets2panda/linter/test/main/taskpool_deprecated_usages2.ets.arkts2.json create mode 100755 ets2panda/linter/test/main/taskpool_deprecated_usages2.ets.json create mode 100755 ets2panda/linter/test/main/taskpool_deprecated_usages3.ets create mode 100755 ets2panda/linter/test/main/taskpool_deprecated_usages3.ets.args.json create mode 100755 ets2panda/linter/test/main/taskpool_deprecated_usages3.ets.arkts2.json create mode 100755 ets2panda/linter/test/main/taskpool_deprecated_usages3.ets.json create mode 100644 ets2panda/package-lock.json diff --git a/ets2panda/linter/arkanalyzer/OAT.xml b/ets2panda/linter/arkanalyzer/OAT.xml index 6420939360..a33eba98c9 100644 --- a/ets2panda/linter/arkanalyzer/OAT.xml +++ b/ets2panda/linter/arkanalyzer/OAT.xml @@ -19,6 +19,7 @@ + diff --git a/ets2panda/linter/arkanalyzer/config/arkanalyzer.json b/ets2panda/linter/arkanalyzer/config/arkanalyzer.json index fe0c60bdc4..17df9e7480 100644 --- a/ets2panda/linter/arkanalyzer/config/arkanalyzer.json +++ b/ets2panda/linter/arkanalyzer/config/arkanalyzer.json @@ -7,15 +7,19 @@ ".d.ts" ], "enableLeadingComments": false, + "enableBuiltIn": true, "ignoreFileNames": [ "oh_modules", "node_modules", "build-tools", - "hvigorfile.ts" + "hvigorfile.ts", + "hvigorfile.js", + "hvigor-wrapper.js" ], "sdkGlobalFolders": [ "component", - "@internal" + "@internal", + "ohos-typescript" ], "tsconfig": "tsconfig.json" } \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/Config.ts b/ets2panda/linter/arkanalyzer/src/Config.ts index bff8ddf474..45645d8783 100644 --- a/ets2panda/linter/arkanalyzer/src/Config.ts +++ b/ets2panda/linter/arkanalyzer/src/Config.ts @@ -43,6 +43,7 @@ export interface SceneOptions { ignoreFileNames?: string[]; enableLeadingComments?: boolean; enableTrailingComments?: boolean; + enableBuiltIn?: boolean; tsconfig?: string; isScanAbc?: boolean; sdkGlobalFolders?: string[]; @@ -86,6 +87,7 @@ export class SceneConfig { public buildConfig(targetProjectName: string, targetProjectDirectory: string, sdks: Sdk[], fullFilePath?: string[]): void { this.targetProjectName = targetProjectName; this.targetProjectDirectory = targetProjectDirectory; + this.projectFiles = getAllFiles(targetProjectDirectory, this.options.supportFileExts!, this.options.ignoreFileNames); this.sdksObj = sdks; if (fullFilePath) { this.projectFiles.push(...fullFilePath); diff --git a/ets2panda/linter/arkanalyzer/src/Scene.ts b/ets2panda/linter/arkanalyzer/src/Scene.ts index 72c7828226..cc41afcc09 100644 --- a/ets2panda/linter/arkanalyzer/src/Scene.ts +++ b/ets2panda/linter/arkanalyzer/src/Scene.ts @@ -41,16 +41,18 @@ 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'; +import { PointerAnalysisConfig } from './callgraph/pointerAnalysis/PointerAnalysisConfig'; +import { ValueUtil } from './core/common/ValueUtil'; const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'Scene'); enum SceneBuildStage { BUILD_INIT, + SDK_INFERRED, CLASS_DONE, METHOD_DONE, CLASS_COLLECTED, METHOD_COLLECTED, - SDK_INFERRED, TYPE_INFERRED, } @@ -99,6 +101,17 @@ export class Scene { constructor() {} + /* + * Set all static field to be null, then all related objects could be freed by GC. + * This method could be called before drop Scene. + */ + public dispose(): void { + PointerAnalysisConfig.dispose(); + SdkUtils.dispose(); + ValueUtil.dispose(); + ModelUtils.dispose(); + } + public getOptions(): SceneOptions { return this.options; } @@ -194,6 +207,9 @@ export class Scene { } // handle sdks + if (this.options.enableBuiltIn && !sceneConfig.getSdksObj().find(sdk => sdk.name === SdkUtils.BUILT_IN_NAME)) { + sceneConfig.getSdksObj().unshift(SdkUtils.BUILT_IN_SDK); + } sceneConfig.getSdksObj()?.forEach(sdk => { if (!sdk.moduleName) { this.buildSdk(sdk.name, sdk.path); @@ -207,7 +223,16 @@ export class Scene { } } }); - + if (this.buildStage < SceneBuildStage.SDK_INFERRED) { + this.sdkArkFilesMap.forEach(file => { + IRInference.inferFile(file); + SdkUtils.mergeGlobalAPI(file, this.sdkGlobalMap); + }); + this.sdkArkFilesMap.forEach(file => { + SdkUtils.postInferredSdk(file, this.sdkGlobalMap); + }); + this.buildStage = SceneBuildStage.SDK_INFERRED; + } this.fileLanguages = sceneConfig.getFileLanguages(); } @@ -222,6 +247,7 @@ export class Scene { return; } const buildProfileJson = parseJsonText(configurationsText); + SdkUtils.setEsVersion(buildProfileJson); const modules = buildProfileJson.modules; if (modules instanceof Array) { modules.forEach(module => { @@ -322,12 +348,13 @@ export class Scene { } } + ModelUtils.dispose(); this.buildStage = SceneBuildStage.METHOD_DONE; } private genArkFiles(): void { this.projectFiles.forEach(file => { - logger.info('=== parse file:', file); + logger.trace('=== parse file:', file); try { const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.fileLanguages)); arkFile.setScene(this); @@ -469,9 +496,11 @@ export class Scene { } private findDependenciesByRule(originPath: string, arkFile: ArkFile): void { - 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!'); + if ( + !this.findFilesByPathArray(originPath, this.indexPathArray, arkFile) && + !this.findFilesByExtNameArray(originPath, this.options.supportFileExts!, arkFile) + ) { + logger.trace(originPath + 'module mapperInfo is not found!'); } } @@ -542,7 +571,7 @@ export class Scene { this.addFileNode2DependencyGrap(originPath, arkFile); } if (!this.findFilesByPathArray(originPath, this.indexPathArray, arkFile)) { - logger.info(originPath + 'module mapperInfo is not found!'); + logger.trace(originPath + 'module mapperInfo is not found!'); } } } @@ -572,9 +601,10 @@ export class Scene { } private buildSdk(sdkName: string, sdkPath: string): void { - const allFiles = getAllFiles(sdkPath, this.options.supportFileExts!, this.options.ignoreFileNames); + const allFiles = sdkName === SdkUtils.BUILT_IN_NAME ? SdkUtils.fetchBuiltInFiles() : + getAllFiles(sdkPath, this.options.supportFileExts!, this.options.ignoreFileNames); allFiles.forEach(file => { - logger.info('=== parse sdk file:', file); + logger.trace('=== parse sdk file:', file); try { const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.fileLanguages)); arkFile.setScene(this); @@ -586,7 +616,7 @@ export class Scene { const fileSig = arkFile.getFileSignature().toMapKey(); this.sdkArkFilesMap.set(fileSig, arkFile); SdkUtils.buildSdkImportMap(arkFile); - SdkUtils.buildGlobalMap(arkFile, this.sdkGlobalMap); + SdkUtils.loadGlobalAPI(arkFile, this.sdkGlobalMap); } catch (error) { logger.error('Error parsing file:', file, error); this.unhandledSdkFilePaths.push(file); @@ -1023,16 +1053,7 @@ export class Scene { ``` */ public inferTypes(): void { - if (this.buildStage < SceneBuildStage.SDK_INFERRED) { - 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 => { try { IRInference.inferFile(file); @@ -1044,6 +1065,7 @@ export class Scene { this.getMethodsMap(true); this.buildStage = SceneBuildStage.TYPE_INFERRED; } + SdkUtils.dispose(); } /** @@ -1458,7 +1480,7 @@ export class ModuleScene { private genArkFiles(supportFileExts: string[]): void { getAllFiles(this.modulePath, supportFileExts, this.projectScene.getOptions().ignoreFileNames).forEach(file => { - logger.info('=== parse file:', file); + logger.trace('=== parse file:', file); try { const arkFile: ArkFile = new ArkFile(FileUtils.getFileLanguage(file, this.projectScene.getFileLanguages())); arkFile.setScene(this.projectScene); diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts index 4fb8a6f7b7..9a3e7fa8e1 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/AbstractAnalysis.ts @@ -30,13 +30,14 @@ const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'CG'); export abstract class AbstractAnalysis { protected scene: Scene; - protected cg!: CallGraph; + protected cg: CallGraph; protected cgBuilder!: CallGraphBuilder; protected workList: FuncID[] = []; protected processedMethod!: IPtsCollection; - constructor(s: Scene) { + constructor(s: Scene, cg: CallGraph) { this.scene = s; + this.cg = cg; } public getScene(): Scene { @@ -96,11 +97,13 @@ export abstract class AbstractAnalysis { } public projectStart(displayGeneratedMethod: boolean): void { - this.scene.getMethods().forEach((method) => { - let cgNode = this.cg.getCallGraphNodeByMethod(method.getSignature()) as CallGraphNode; + this.cgBuilder.buildCGNodes(this.scene.getMethods()); + + for (let n of this.cg.getNodesIter()) { + let cgNode = n as CallGraphNode; if (cgNode.isSdkMethod()) { - return; + continue; } this.preProcessMethod(cgNode.getID()); @@ -108,7 +111,9 @@ export abstract class AbstractAnalysis { this.processMethod(cgNode.getID()).forEach((cs: CallSite) => { this.processCallSite(cgNode.getID(), cs, displayGeneratedMethod, true); }); - }); + } + + this.cgBuilder.setEntries(); } private processCallSite(method: FuncID, cs: CallSite, displayGeneratedMethod: boolean, isProject: boolean = false): void { @@ -128,7 +133,7 @@ export abstract class AbstractAnalysis { if (displayGeneratedMethod || !me?.isGenerated()) { this.workList.push(cs.calleeFuncID); - logger.info(`New workList item ${cs.calleeFuncID}: ${this.cg.getArkMethodByFuncID(cs.calleeFuncID)?.getSignature().toString()}`); + logger.trace(`New workList item ${cs.calleeFuncID}: ${this.cg.getArkMethodByFuncID(cs.calleeFuncID)?.getSignature().toString()}`); } } diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts index 029d85541e..df58f9e571 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/ClassHierarchyAnalysis.ts @@ -20,11 +20,12 @@ import { ArkClass } from '../../core/model/ArkClass'; import { NodeID } from '../../core/graph/BaseExplicitGraph'; import { CallGraph, CallSite } from '../model/CallGraph'; import { AbstractAnalysis } from './AbstractAnalysis'; +import { CallGraphBuilder } from '../model/builder/CallGraphBuilder'; export class ClassHierarchyAnalysis extends AbstractAnalysis { - constructor(scene: Scene, cg: CallGraph) { - super(scene); - this.cg = cg; + constructor(scene: Scene, cg: CallGraph, cb: CallGraphBuilder) { + super(scene, cg); + this.cgBuilder = cb; } public resolveCall(callerMethod: NodeID, invokeStmt: Stmt): CallSite[] { diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts index b4ecc267ac..b14816d26b 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/algorithm/RapidTypeAnalysis.ts @@ -33,8 +33,7 @@ export class RapidTypeAnalysis extends AbstractAnalysis { private ignoredCalls: Map> = new Map(); constructor(scene: Scene, cg: CallGraph) { - super(scene); - this.cg = cg; + super(scene, cg); } public resolveCall(callerMethod: NodeID, invokeStmt: Stmt): CallSite[] { diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts b/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts index 61246908ad..112539b168 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/common/Statistics.ts @@ -196,6 +196,7 @@ export class CGStat extends StatTraits { numVirtual: number = 0; numIntrinsic: number = 0; numConstructor: number = 0; + numBlank: number = 0; public startStat(): void { this.startTime = new Date().getTime(); @@ -221,6 +222,7 @@ export class CGStat extends StatTraits { this.numIntrinsic++; break; default: + this.numBlank++; } this.numTotalNode++; } @@ -232,7 +234,8 @@ export class CGStat extends StatTraits { 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 + `Virtual function\t\t${this.numVirtual}\n`; + output = output + `Blank function\t\t${this.numBlank}\n`; output = output + `Total\t\t\t${this.numTotalNode}\n`; return output; } diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts b/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts index 954f47804a..0ddeb63007 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/model/CallGraph.ts @@ -15,63 +15,27 @@ 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'; +import { CallSite, CallSiteID, DynCallSite, ICallSite } from './CallSite'; export type Method = MethodSignature; -export type CallSiteID = number; export type FuncID = number; type StmtSet = Set; +export { CallSite, DynCallSite, ICallSite }; + export enum CallGraphNodeKind { - real, + real, // method from project and has body 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; - } + intrinsic, // method created by AA, which arkMethod.isGenrated is true + constructor, // constructor + blank, // method without body } export class CallGraphEdge extends BaseEdge { @@ -119,7 +83,6 @@ export class CallGraphEdge extends BaseEdge { 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); @@ -139,11 +102,7 @@ export class CallGraphNode extends BaseNode { } public get isBlankMethod(): boolean { - return this.isBlank; - } - - public set isBlankMethod(is: boolean) { - this.isBlank = is; + return this.kind === CallGraphNodeKind.blank; } public getDotAttr(): string { @@ -195,11 +154,6 @@ export class CallGraph extends BaseExplicitGraph { // 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); @@ -285,7 +239,7 @@ export class CallGraph extends BaseExplicitGraph { } let args = callStmt.getInvokeExpr()?.getArgs(); - let cs = new DynCallSite(callerNode.getID(), callStmt, args, calleeNode?.getID()); + let cs = new DynCallSite(callStmt, args, calleeNode?.getID(), callerNode.getID()); this.stmtToDynCallSitemap.set(callStmt, cs); } @@ -467,4 +421,4 @@ export class CallGraph extends BaseExplicitGraph { public getGraphName(): string { return 'CG'; } -} +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/model/CallSite.ts b/ets2panda/linter/arkanalyzer/src/callgraph/model/CallSite.ts new file mode 100644 index 0000000000..40dbb3b492 --- /dev/null +++ b/ets2panda/linter/arkanalyzer/src/callgraph/model/CallSite.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 { Stmt } from '../../core/base/Stmt'; +import { Value } from '../../core/base/Value'; +import { ContextID } from '../pointerAnalysis/Context'; +import { FuncID } from './CallGraph'; + +export type CallSiteID = number; + +export interface ICallSite { + callStmt: Stmt; + args: Value[] | undefined; + callerFuncID: FuncID; +} + +export class CallSite implements ICallSite { + 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 implements ICallSite { + public callStmt: Stmt; + public args: Value[] | undefined; + public protentialCalleeFuncID: FuncID | undefined; + public callerFuncID: FuncID; + + constructor(s: Stmt, a: Value[] | undefined, ptcCallee: FuncID | undefined, caller: FuncID) { + 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; + } +} \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts b/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts index c631c4333f..5947b9c66e 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/model/builder/CallGraphBuilder.ts @@ -38,19 +38,27 @@ export class CallGraphBuilder { this.setEntries(); } - public buildDirectCallGraph(methods: ArkMethod[]): void { + /* + * Create CG Node for ArkMethods + */ + public buildCGNodes(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') { + } else if (method.getBody() === undefined || method.getCfg() === undefined) { + kind = CallGraphNodeKind.blank; + } else if (method.getName() === 'constructor') { kind = CallGraphNodeKind.constructor; } this.cg.addCallGraphNode(m, kind); } + } + + public buildDirectCallGraph(methods: ArkMethod[]): void { + this.buildCGNodes(methods); for (const method of methods) { let cfg = method.getCfg(); @@ -70,8 +78,7 @@ export class CallGraphBuilder { if (callee && invokeExpr instanceof ArkStaticInvokeExpr) { this.cg.addDirectOrSpecialCallEdge(method.getSignature(), callee, stmt); } else if ( - callee && - invokeExpr instanceof ArkInstanceInvokeExpr && + callee && invokeExpr instanceof ArkInstanceInvokeExpr && (this.isConstructor(callee) || this.scene.getMethod(callee)?.isGenerated()) ) { this.cg.addDirectOrSpecialCallEdge(method.getSignature(), callee, stmt, false); @@ -89,12 +96,12 @@ export class CallGraphBuilder { }); this.cg.setEntries(cgEntries); - let classHierarchyAnalysis: ClassHierarchyAnalysis = new ClassHierarchyAnalysis(this.scene, this.cg); + let classHierarchyAnalysis: ClassHierarchyAnalysis = new ClassHierarchyAnalysis(this.scene, this.cg, this); classHierarchyAnalysis.start(displayGeneratedMethod); } public buildCHA4WholeProject(displayGeneratedMethod: boolean = false): void { - let classHierarchyAnalysis: ClassHierarchyAnalysis = new ClassHierarchyAnalysis(this.scene, this.cg); + let classHierarchyAnalysis: ClassHierarchyAnalysis = new ClassHierarchyAnalysis(this.scene, this.cg, this); classHierarchyAnalysis.projectStart(displayGeneratedMethod); } diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts index a8940d5d3c..0c120d6000 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PTAUtils.ts @@ -51,6 +51,7 @@ export function getBuiltInApiType(method: MethodSignature): BuiltApiType { return BuiltApiType.FunctionApply; case 'bind': return BuiltApiType.FunctionBind; + default: } } } diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts index bd3917b090..815eae1afb 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PagBuilder.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CallGraph, CallGraphNode, CallGraphNodeKind, CallSite, DynCallSite, FuncID } from '../model/CallGraph'; +import { CallGraph, CallGraphNode, CallGraphNodeKind, CallSite, DynCallSite, FuncID, ICallSite } from '../model/CallGraph'; import { Scene } from '../../Scene'; import { ArkAssignStmt, ArkInvokeStmt, ArkReturnStmt, Stmt } from '../../core/base/Stmt'; import { @@ -527,7 +527,7 @@ export class PagBuilder { }); } - public addDynamicCallEdge(cs: DynCallSite | CallSite, baseClassPTNode: NodeID, cid: ContextID): NodeID[] { + public addDynamicCallEdge(cs: ICallSite, baseClassPTNode: NodeID, cid: ContextID): NodeID[] { let srcNodes: NodeID[] = []; let ivkExpr = cs.callStmt.getInvokeExpr(); @@ -577,7 +577,7 @@ export class PagBuilder { * 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[] { + private getDynamicCallee(ptNode: PagNode, value: Value, ivkExpr: AbstractInvokeExpr, cs: ICallSite): ArkMethod[] { let callee: ArkMethod[] = []; if (ptNode instanceof PagFuncNode) { @@ -646,7 +646,10 @@ export class PagBuilder { // 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); + + if (srcBaseNode !== -1) { + srcNodes.push(srcBaseNode); + } } else if (!dstCGNode.isSdkMethod() && ivkExpr instanceof ArkPtrInvokeExpr) { let originCS = (ptNode as PagFuncNode).getCS(); if (!originCS) { @@ -712,6 +715,7 @@ export class PagBuilder { */ this.handleFunctionBind(staticCS, cid, baseClassPTNode, srcNodes); break; + default: } return srcNodes; @@ -799,7 +803,11 @@ export class PagBuilder { 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)); + let srcNodeID = this.addThisRefCallEdge(baseClassPTNode, cid, staticCS.args![0] as Local, realCallee, calleeCid, staticCS.callerFuncID); + + if (srcNodeID !== -1) { + srcNodes.push(srcNodeID); + } } } @@ -915,6 +923,10 @@ export class PagBuilder { callerFunID: FuncID ): NodeID { let thisRefNodeID = this.recordThisRefNode(baseClassPTNode, callee, calleeCid); + if (thisRefNodeID === -1) { + return -1; + } + let thisRefNode = this.pag.getNode(thisRefNodeID) as PagThisRefNode; let srcBaseLocal = baseLocal; srcBaseLocal = this.getRealThisLocal(srcBaseLocal, callerFunID); @@ -945,7 +957,7 @@ export class PagBuilder { .getCfg() ?.getStmts() .filter(s => s instanceof ArkAssignStmt && s.getRightOp() instanceof ArkThisRef); - let thisPtr = (thisAssignStmt?.at(0) as ArkAssignStmt).getRightOp() as ArkThisRef; + let thisPtr = (thisAssignStmt?.[0] as ArkAssignStmt).getRightOp() as ArkThisRef; if (!thisPtr) { throw new Error('Can not get this ptr'); } @@ -1031,8 +1043,8 @@ export class PagBuilder { // add args to parameters edges for (let i = offset; i <= args.length; i++) { - let arg = args.at(i); - let param = params.at(i - offset); + let arg = args[i]; + let param = params[i - offset]; if (!arg || !param) { return srcNodes; } @@ -1063,7 +1075,7 @@ export class PagBuilder { // 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); + let param = params[0]; if (!containerValue || !param) { return srcNodes; } @@ -1200,7 +1212,7 @@ export class PagBuilder { // add args to parameters edges for (let i = 0; i < argNum; i++) { - let arg = cs.args?.at(i); + let arg = cs.args?.[i]; let paramValue; if (arg instanceof Local && arg.getType() instanceof FunctionType) { @@ -1233,7 +1245,7 @@ export class PagBuilder { 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); + let sdkParamCallSite = new DynCallSite(sdkParamInvokeStmt, undefined, undefined, funcID); dstPagNode.addRelatedDynCallSite(sdkParamCallSite); } @@ -1542,7 +1554,7 @@ export class PagBuilder { * 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 { + private processStorage(cs: ICallSite, calleeCGNode: CallGraphNode, cid: ContextID): boolean { let storageName = calleeCGNode.getMethod().getDeclaringClassSignature().getClassName(); let storageType: StorageType = this.getStorageType(storageName, cs, cid); @@ -1570,7 +1582,7 @@ export class PagBuilder { return false; } - private processStorageSetOrCreate(cs: CallSite | DynCallSite, cid: ContextID): void { + private processStorageSetOrCreate(cs: ICallSite, cid: ContextID): void { let propertyStr = this.getPropertyName(cs.args![0]); if (!propertyStr) { return; @@ -1583,7 +1595,7 @@ export class PagBuilder { this.addPropertyLinkEdge(propertyNode, storageObj, cid, cs.callStmt, StorageLinkEdgeType.Local2Property); } - private processStorageLink(cs: CallSite | DynCallSite, cid: ContextID): void { + private processStorageLink(cs: ICallSite, cid: ContextID): void { let propertyStr = this.getPropertyName(cs.args![0]); if (!propertyStr) { return; @@ -1601,7 +1613,7 @@ export class PagBuilder { this.pag.addPagEdge(linkedOpNode, propertyNode, PagEdgeKind.Copy); } - private processStorageProp(cs: CallSite | DynCallSite, cid: ContextID): void { + private processStorageProp(cs: ICallSite, cid: ContextID): void { let propertyStr = this.getPropertyName(cs.args![0]); if (!propertyStr) { return; @@ -1618,7 +1630,7 @@ export class PagBuilder { this.pag.addPagEdge(propertyNode, linkedOpNode, PagEdgeKind.Copy); } - private processStorageSet(cs: CallSite | DynCallSite, cid: ContextID): void { + private processStorageSet(cs: ICallSite, cid: ContextID): void { let ivkExpr: AbstractInvokeExpr = cs.callStmt.getInvokeExpr()!; if (ivkExpr instanceof ArkInstanceInvokeExpr) { let base = ivkExpr.getBase(); @@ -1634,7 +1646,7 @@ export class PagBuilder { } } - private processStorageGet(cs: CallSite | DynCallSite, cid: ContextID): void { + private processStorageGet(cs: ICallSite, cid: ContextID): void { if (!(cs.callStmt instanceof ArkAssignStmt)) { return; } @@ -1686,7 +1698,7 @@ export class PagBuilder { * @param cid: for search PAG node in SubscribedAbstractProperty * @returns StorageType enum */ - private getStorageType(storageName: string, cs: CallSite | DynCallSite, cid: ContextID): StorageType { + private getStorageType(storageName: string, cs: ICallSite, cid: ContextID): StorageType { switch (storageName) { case 'AppStorage': return StorageType.APP_STORAGE; diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts index 902a05b902..4fc4a16471 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysis.ts @@ -47,9 +47,8 @@ export class PointerAnalysis extends AbstractAnalysis { private config: PointerAnalysisConfig; constructor(p: Pag, cg: CallGraph, s: Scene, config: PointerAnalysisConfig) { - super(s); + super(s, cg); 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); diff --git a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts index 1e68c981db..c42428087e 100644 --- a/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts +++ b/ets2panda/linter/arkanalyzer/src/callgraph/pointerAnalysis/PointerAnalysisConfig.ts @@ -64,6 +64,15 @@ export class PointerAnalysisConfig { } } + /* + * Set static field to be null, then all related objects could be freed by GC. + * Class PointerAnalysisConfig has been exported by ArkAnalyzer, the dispose method should be called by users themselves before free this class. + */ + public static dispose(): void { + // @ts-expect-error: only be used to free the memory + this.instance = null; + } + /* * Create Singleton instance * The instance can be created multi-times and be overwrited diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts b/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts index dcf4695331..521e967079 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Expr.ts @@ -19,11 +19,13 @@ import { MethodSignature } from '../model/ArkSignature'; import { Local } from './Local'; import { AliasType, + AnyType, ArrayType, BigIntType, BooleanType, ClassType, FunctionType, + GenericType, NullType, NumberType, StringType, @@ -40,8 +42,9 @@ 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 { ArkClass, ClassCategory } from '../model/ArkClass'; import { ArkField } from '../model/ArkField'; +import { ModelUtils } from '../common/ModelUtils'; /** * @category core/base/expr @@ -133,7 +136,8 @@ export abstract class AbstractInvokeExpr extends AbstractExpr { public getType(): Type { const type = this.methodSignature.getType(); - if (this.realGenericTypes) { + if (TypeInference.checkType(type, t => t instanceof GenericType || t instanceof AnyType) && + this.realGenericTypes) { return TypeInference.replaceTypeWithReal(type, this.realGenericTypes); } return type; @@ -342,14 +346,38 @@ export class ArkNewExpr extends AbstractExpr { const classSignature = this.classType.getClassSignature(); if (classSignature.getDeclaringFileSignature().getFileName() === UNKNOWN_FILE_NAME) { const className = classSignature.getClassName(); - let type = TypeInference.inferUnclearRefName(className, arkMethod.getDeclaringArkClass()); + let type: Type | null | undefined = ModelUtils.findDeclaredLocal(new Local(className), arkMethod, 1)?.getType(); + if (TypeInference.isUnclearType(type)) { + type = TypeInference.inferUnclearRefName(className, arkMethod.getDeclaringArkClass()); + } + if (type instanceof AliasType) { + const originalType = TypeInference.replaceAliasType(type); + if (originalType instanceof FunctionType) { + type = originalType.getMethodSignature().getMethodSubSignature().getReturnType(); + } else { + type = originalType; + } + } if (type && type instanceof ClassType) { - let realGenericTypes = this.classType.getRealGenericTypes(); - this.classType = realGenericTypes ? new ClassType(type.getClassSignature(), realGenericTypes) : type; + const instanceType = this.constructorSignature(type, arkMethod) ?? type; + this.classType.setClassSignature(instanceType.getClassSignature()); + TypeInference.inferRealGenericTypes(this.classType.getRealGenericTypes(), arkMethod.getDeclaringArkClass()); } } return this; } + + private constructorSignature(type: ClassType, arkMethod: ArkMethod): ClassType | undefined { + const classConstructor = arkMethod.getDeclaringArkFile().getScene().getClass(type.getClassSignature()); + if (classConstructor?.getCategory() === ClassCategory.INTERFACE) { + const type = classConstructor.getMethodWithName('construct-signature')?.getReturnType(); + if (type) { + const returnType = TypeInference.replaceAliasType(type); + return returnType instanceof ClassType ? returnType : undefined; + } + } + return undefined; + } } export class ArkNewArrayExpr extends AbstractExpr { @@ -695,9 +723,13 @@ export abstract class AbstractBinopExpr extends AbstractExpr { 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 '>>>': if (op1Type === NumberType.getInstance() && op2Type === NumberType.getInstance()) { type = NumberType.getInstance(); @@ -1042,10 +1074,14 @@ export class AliasTypeExpr extends AbstractExpr { public getType(): Type { function getTypeOfImportInfo(importInfo: ImportInfo): Type { const arkExport = importInfo.getLazyExportInfo()?.getArkExport(); - if (arkExport) { - return TypeInference.parseArkExport2Type(arkExport) ?? UnknownType.getInstance(); + const importClauseName = importInfo.getImportClauseName(); + let type; + if (importClauseName.includes('.') && arkExport instanceof ArkClass) { + type = TypeInference.inferUnclearRefName(importClauseName, arkExport); + } else if (arkExport) { + type = TypeInference.parseArkExport2Type(arkExport); } - return UnknownType.getInstance(); + return type ?? UnknownType.getInstance(); } const operator = this.getOriginalObject(); diff --git a/ets2panda/linter/arkanalyzer/src/core/base/Local.ts b/ets2panda/linter/arkanalyzer/src/core/base/Local.ts index aa4fbebdf0..18e6391330 100644 --- a/ets2panda/linter/arkanalyzer/src/core/base/Local.ts +++ b/ets2panda/linter/arkanalyzer/src/core/base/Local.ts @@ -14,13 +14,13 @@ */ import { Stmt } from './Stmt'; -import { ClassType, Type, UnknownType } from './Type'; +import { ClassType, FunctionType, 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 { NAME_PREFIX, UNKNOWN_METHOD_NAME } from '../common/Const'; import { ModifierType } from '../model/ArkBaseModel'; import { ArkMethod } from '../model/ArkMethod'; import { ModelUtils } from '../common/ModelUtils'; @@ -53,12 +53,18 @@ export class Local implements Value, ArkExport { 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(); + } else if (!this.name.startsWith(NAME_PREFIX) && TypeInference.isUnclearType(this.type)) { + const type = TypeInference.inferBaseType(this.name, arkMethod.getDeclaringArkClass()) ?? + ModelUtils.findDeclaredLocal(this, arkMethod)?.getType(); if (type) { this.type = type; } } + if (this.type instanceof FunctionType) { + this.type.getMethodSignature().getMethodSubSignature().getParameters() + .forEach(p => TypeInference.inferParameterType(p, arkMethod)); + TypeInference.inferSignatureReturnType(this.type.getMethodSignature(), arkMethod); + } return this; } diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts b/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts index 31f9ecf635..5ed77fbe20 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ArkIRTransformer.ts @@ -46,7 +46,6 @@ 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'; @@ -156,6 +155,8 @@ export class ArkIRTransformer { stmts = this.expressionInExportToStmts(node.expression); } else if (ts.isClassDeclaration(node)) { stmts = this.classDeclarationToStmts(node); + } else if (ts.isParameter(node)) { + stmts = this.parameterPropertyToStmts(node); } this.mapStmtsToTsStmt(stmts, node); @@ -190,6 +191,44 @@ export class ArkIRTransformer { return []; } + // This is only used to add class property assign stmts into constructor when it is with parameter property. + private parameterPropertyToStmts(paramNode: ts.ParameterDeclaration): Stmt[] { + if (paramNode.modifiers === undefined || !ts.isIdentifier(paramNode.name)) { + return []; + } + const fieldName = paramNode.name.text; + const arkClass = this.declaringMethod.getDeclaringArkClass(); + const fieldSignature = arkClass.getFieldWithName(fieldName)?.getSignature(); + const paramLocal = Array.from(this.getLocals()).find(local => local.getName() === fieldName); + if (fieldSignature === undefined || paramLocal === undefined) { + return []; + } + const leftOp = new ArkInstanceFieldRef(this.getThisLocal(), fieldSignature); + const fieldAssignStmt = new ArkAssignStmt(leftOp, paramLocal); + fieldAssignStmt.setOperandOriginalPositions([FullPosition.DEFAULT, FullPosition.DEFAULT, FullPosition.DEFAULT]); + + // If the parameter has initializer, the related stmts should be added into class instance init method. + const instInitMethodCfg = arkClass.getInstanceInitMethod().getBody()?.getCfg(); + const instInitStmts = instInitMethodCfg?.getStartingBlock()?.getStmts(); + if (paramNode.initializer && instInitStmts && instInitMethodCfg) { + const { + value: instanceInitValue, + valueOriginalPositions: instanceInitPositions, + stmts: instanceInitStmts, + } = this.tsNodeToValueAndStmts(paramNode.initializer); + const instanceAssignStmt = new ArkAssignStmt(leftOp, instanceInitValue); + instanceAssignStmt.setOperandOriginalPositions([FullPosition.DEFAULT, FullPosition.DEFAULT, ...instanceInitPositions]); + const newInstanceInitStmts = [...instanceInitStmts, instanceAssignStmt]; + + // All these stmts will be added into instance init method, while that method has completed the building. So all new stmts should set cfg here. + newInstanceInitStmts.forEach(stmt => stmt.setCfg(instInitMethodCfg)); + + // The last stmt of instance init method is return stmt, so all the initializer stmts should be added before return stmt. + instInitStmts.splice(instInitStmts.length - 1, 0, ...newInstanceInitStmts); + } + return [fieldAssignStmt]; + } + private returnStatementToStmts(returnStatement: ts.ReturnStatement): Stmt[] { const stmts: Stmt[] = []; if (returnStatement.expression) { @@ -339,12 +378,6 @@ export class ArkIRTransformer { 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); @@ -402,8 +435,6 @@ export class ArkIRTransformer { 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); } diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts b/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts index 75d8689428..a26b46ee66 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ArkValueTransformer.ts @@ -299,6 +299,7 @@ export class ArkValueTransformer { const constructorInvokeStmt = new ArkInvokeStmt(constructorInvokeExpr); constructorInvokeStmt.setOperandOriginalPositions(constructorInvokeExprPositions); stmts.push(constructorInvokeStmt); + return { value: newExprLocal, valueOriginalPositions: newExprLocalPositions, @@ -832,6 +833,11 @@ export class ArkValueTransformer { } else { invokeValue = new ArkStaticInvokeExpr(methodSignature, args, realGenericTypes); } + } else if (callerValue instanceof ArkArrayRef && ts.isElementAccessExpression(functionNameNode)) { + const methodSignature = ArkSignatureBuilder.buildMethodSignatureFromMethodName(functionNameNode.argumentExpression.getText()); + invokeValue = new ArkInstanceInvokeExpr(callerValue.getBase(), methodSignature, args, realGenericTypes); + invokeValuePositions.push(...callerPositions.slice(1)); + stmts.pop(); } else { ({ value: callerValue, @@ -1107,15 +1113,24 @@ export class ArkValueTransformer { private prefixUnaryExpressionToValueAndStmts(prefixUnaryExpression: ts.PrefixUnaryExpression): ValueAndStmts { const stmts: Stmt[] = []; - let { value: operandValue, valueOriginalPositions: operandPositions, stmts: operandStmts } = this.tsNodeToValueAndStmts(prefixUnaryExpression.operand); + let { + value: originOperandValue, + valueOriginalPositions: originOperandPositions, + stmts: operandStmts, + } = this.tsNodeToValueAndStmts(prefixUnaryExpression.operand); operandStmts.forEach(stmt => stmts.push(stmt)); - if (IRUtils.moreThanOneAddress(operandValue)) { + let operandValue: Value; + let operandPositions: FullPosition[]; + if (IRUtils.moreThanOneAddress(originOperandValue)) { ({ value: operandValue, valueOriginalPositions: operandPositions, stmts: operandStmts, - } = this.arkIRTransformer.generateAssignStmtForValue(operandValue, operandPositions)); + } = this.arkIRTransformer.generateAssignStmtForValue(originOperandValue, originOperandPositions)); operandStmts.forEach(stmt => stmts.push(stmt)); + } else { + operandValue = originOperandValue; + operandPositions = originOperandPositions; } const operatorToken = prefixUnaryExpression.operator; @@ -1127,17 +1142,14 @@ export class ArkValueTransformer { const assignStmt = new ArkAssignStmt(operandValue, binopExpr); assignStmt.setOperandOriginalPositions([...operandPositions, ...exprPositions]); stmts.push(assignStmt); - return { - value: operandValue, - valueOriginalPositions: operandPositions, - stmts: stmts, - }; + if (operandValue !== originOperandValue) { + const lastAssignStmt = new ArkAssignStmt(originOperandValue, operandValue); + lastAssignStmt.setOperandOriginalPositions([...originOperandPositions, ...operandPositions]); + stmts.push(lastAssignStmt); + } + return { value: originOperandValue, valueOriginalPositions: originOperandPositions, 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); @@ -1148,28 +1160,32 @@ 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: originOperandValue, + valueOriginalPositions: originOperandPositions, + stmts: exprStmts, + } = this.tsNodeToValueAndStmts(postfixUnaryExpression.operand); exprStmts.forEach(stmt => stmts.push(stmt)); - if (IRUtils.moreThanOneAddress(operandValue)) { + let operandValue: Value; + let operandPositions: FullPosition[]; + if (IRUtils.moreThanOneAddress(originOperandValue)) { ({ value: operandValue, valueOriginalPositions: operandPositions, stmts: exprStmts, - } = this.arkIRTransformer.generateAssignStmtForValue(operandValue, operandPositions)); + } = this.arkIRTransformer.generateAssignStmtForValue(originOperandValue, originOperandPositions)); exprStmts.forEach(stmt => stmts.push(stmt)); + } else { + operandValue = originOperandValue; + operandPositions = originOperandPositions; } - let value: Value; let exprPositions = [FullPosition.buildFromNode(postfixUnaryExpression, this.sourceFile)]; const operatorToken = postfixUnaryExpression.operator; if (operatorToken === ts.SyntaxKind.PlusPlusToken || operatorToken === ts.SyntaxKind.MinusMinusToken) { @@ -1179,15 +1195,21 @@ export class ArkValueTransformer { const assignStmt = new ArkAssignStmt(operandValue, binopExpr); assignStmt.setOperandOriginalPositions([...operandPositions, ...exprPositions]); stmts.push(assignStmt); - value = operandValue; - } else { - value = ValueUtil.getUndefinedConst(); - exprPositions = [FullPosition.DEFAULT]; + if (operandValue !== originOperandValue) { + const lastAssignStmt = new ArkAssignStmt(originOperandValue, operandValue); + lastAssignStmt.setOperandOriginalPositions([...originOperandPositions, ...operandPositions]); + stmts.push(lastAssignStmt); + } + return { + value: originOperandValue, + valueOriginalPositions: originOperandPositions, + stmts: stmts, + }; } return { - value: value, - valueOriginalPositions: exprPositions, + value: ValueUtil.getUndefinedConst(), + valueOriginalPositions: [FullPosition.DEFAULT], stmts: stmts, }; } @@ -1921,7 +1943,8 @@ export class ArkValueTransformer { } private resolveTypeReferenceNode(typeReferenceNode: ts.TypeReferenceNode): Type { - const typeReferenceFullName = typeReferenceNode.typeName.getText(this.sourceFile); + const typeReferenceFullName = ts.isIdentifier(typeReferenceNode.typeName) ? typeReferenceNode.typeName.text : + typeReferenceNode.typeName.getText(this.sourceFile); if (typeReferenceFullName === Builtin.OBJECT) { return Builtin.OBJECT_CLASS_TYPE; } @@ -1935,12 +1958,11 @@ export class ArkValueTransformer { } if (!aliasTypeAndStmt) { - const typeName = typeReferenceNode.typeName.getText(this.sourceFile); - const local = this.locals.get(typeName); + const local = this.locals.get(typeReferenceFullName); if (local !== undefined) { return local.getType(); } - return new UnclearReferenceType(typeName, genericTypes); + return new UnclearReferenceType(typeReferenceFullName, genericTypes); } else { if (genericTypes.length > 0) { const oldAlias = aliasTypeAndStmt[0]; diff --git a/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts b/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts index 5c74ecf4d2..faf7eb2152 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/Builtin.ts @@ -42,8 +42,8 @@ export class Builtin { public static BUILT_IN_CLASS_SIGNATURE_MAP = this.buildBuiltInClassSignatureMap(); // constants for iterator - public static ITERATOR_FUNCTION = 'iterator'; - public static ITERATOR = 'Iterator'; + public static ITERATOR_FUNCTION = 'Symbol.iterator'; + public static ITERATOR = 'IterableIterator'; public static ITERATOR_NEXT = 'next'; public static ITERATOR_RESULT = 'IteratorResult'; public static ITERATOR_RESULT_DONE = 'done'; diff --git a/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts b/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts index 3818ac8051..4dc9c68041 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/DummyMainCreater.ts @@ -175,7 +175,7 @@ export class DummyMainCreater { let superCls = method.getDeclaringArkClass().getSuperClass(); let methodInSuperCls = superCls?.getMethodWithName(method.getName()); if (methodInSuperCls) { - paramType = methodInSuperCls.getParameters().at(paramIdx)?.getType(); + paramType = methodInSuperCls.getParameters()[paramIdx]?.getType(); method = methodInSuperCls; } } diff --git a/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts b/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts index 0808347490..c670ead482 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/IRInference.ts @@ -49,7 +49,7 @@ import { AliasClassSignature, BaseSignature, ClassSignature, - FieldSignature, + FieldSignature, FileSignature, MethodSignature, MethodSubSignature } from '../model/ArkSignature'; @@ -63,15 +63,14 @@ import { ArkArrayRef, ArkInstanceFieldRef, ArkParameterRef, - ArkStaticFieldRef, - GlobalRef + 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, + DEFAULT_ARK_CLASS_NAME, LEXICAL_ENV_NAME_PREFIX, NAME_DELIMITER, NAME_PREFIX, UNKNOWN_CLASS_NAME @@ -130,12 +129,17 @@ export class IRInference { } return 0; }); + arkClass.getAllHeritageClasses(); methods.forEach(arkMethod => TypeInference.inferTypeInMethod(arkMethod)); }); this.inferExportInfos(file); } public static inferStaticInvokeExpr(expr: ArkStaticInvokeExpr, arkMethod: ArkMethod): AbstractInvokeExpr { + const fileSignature = expr.getMethodSignature().getDeclaringClassSignature().getDeclaringFileSignature(); + if (fileSignature !== FileSignature.DEFAULT && fileSignature !== Builtin.BUILT_IN_CLASSES_FILE_SIGNATURE) { + return expr; + } const arkClass = arkMethod.getDeclaringArkClass(); const methodName = expr.getMethodSignature().getMethodSubSignature().getMethodName(); expr.getArgs().forEach(arg => TypeInference.inferValueType(arg, arkMethod)); @@ -252,10 +256,12 @@ export class IRInference { 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()); + const stmts = arkMethod.getDeclaringArkFile().getScene().getMethod(methodSignature)?.getCfg()?.getStmts(); + if (stmts) { + const endStmt = stmts[stmts.length - 2]; + if (endStmt instanceof ArkInvokeStmt) { + methodSignature.getMethodSubSignature().setReturnType(endStmt.getInvokeExpr().getType()); + } } expr.setMethodSignature(methodSignature); return expr; @@ -283,6 +289,11 @@ export class IRInference { private static inferBase(instance: ArkInstanceFieldRef | ArkInstanceInvokeExpr, arkMethod: ArkMethod): void { const base = instance.getBase(); if (base.getName() === THIS_NAME) { + const name = instance instanceof ArkInstanceFieldRef ? instance.getFieldName() : + instance.getMethodSignature().getMethodSubSignature().getMethodName(); + if (name.includes('.')) { + return; + } const declaringArkClass = arkMethod.getDeclaringArkClass(); if (declaringArkClass.isAnonymousClass()) { let newBase = this.inferThisLocal(arkMethod); @@ -293,14 +304,6 @@ export class IRInference { 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); } } @@ -445,17 +448,13 @@ 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) { - 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); - } + const arrayInterface = scene.getSdkGlobal(Builtin.ARRAY); + if (arrayInterface instanceof ArkClass) { + return this.inferInvokeExpr(expr, new ClassType(arrayInterface.getSignature(), [baseType.getBaseType()]), methodName, scene); + } else if (methodName === Builtin.ITERATOR_FUNCTION) { + expr.getMethodSignature().getMethodSubSignature().setReturnType(Builtin.ITERATOR_CLASS_TYPE); + expr.setRealGenericTypes([baseType.getBaseType()]); + return expr; } return null; } @@ -498,7 +497,7 @@ export class IRInference { const methodSignature = method.matchMethodSignature(expr.getArgs()); TypeInference.inferSignatureReturnType(methodSignature, method); expr.setMethodSignature(this.replaceMethodSignature(expr.getMethodSignature(), methodSignature)); - expr.setRealGenericTypes(IRInference.getRealTypes(method, declaredClass, baseType)); + expr.setRealGenericTypes(IRInference.getRealTypes(expr, declaredClass, baseType, method)); if (method.isStatic() && expr instanceof ArkInstanceInvokeExpr) { return new ArkStaticInvokeExpr(methodSignature, expr.getArgs(), expr.getRealGenericTypes()); } @@ -527,25 +526,33 @@ export class IRInference { 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; - } + } else if (methodName === Builtin.ITERATOR_NEXT && + baseType.getClassSignature().getDeclaringFileSignature().getProjectName() === Builtin.DUMMY_PROJECT_NAME) { + expr.getMethodSignature().getMethodSubSignature().setReturnType(Builtin.ITERATOR_RESULT_CLASS_TYPE); + expr.setRealGenericTypes(baseType.getRealGenericTypes()); + return expr; } return null; } - private static getRealTypes(method: ArkMethod, declaredClass: ArkClass | null, baseType: ClassType): Type[] | undefined { + private static getRealTypes(expr: AbstractInvokeExpr, declaredClass: ArkClass | null, baseType: ClassType, method: ArkMethod): Type[] | undefined { let realTypes; - if (method.getDeclaringArkClass() === declaredClass) { - realTypes = baseType.getRealGenericTypes(); - } else if (declaredClass?.getRealTypes()) { - realTypes = declaredClass?.getRealTypes(); + const tmp: Type[] = []; + if (method.getGenericTypes()) { + expr.getMethodSignature().getMethodSubSignature().getParameters() + .filter(p => !p.getName().startsWith(LEXICAL_ENV_NAME_PREFIX)) + .forEach((p, i) => { + if (TypeInference.checkType(p.getType(), t => t instanceof GenericType)) { + tmp.push(expr.getArg(i).getType()); + } + }); + } + if (tmp.length > 0) { + realTypes = tmp; } else if (declaredClass?.hasComponentDecorator()) { realTypes = [new ClassType(declaredClass?.getSignature())]; + } else { + realTypes = baseType.getRealGenericTypes() ?? declaredClass?.getRealTypes(); } return realTypes; } @@ -618,23 +625,13 @@ export class IRInference { } const fieldName = ref.getFieldName().replace(/[\"|\']/g, ''); const propertyAndType = TypeInference.inferFieldType(baseType, fieldName, arkClass); - let propertyType = propertyAndType?.[1]; - if (!propertyType || propertyType instanceof UnknownType) { - const newType = TypeInference.inferBaseType(fieldName, arkClass); - if (newType) { - propertyType = newType; - } - } else if (TypeInference.isUnclearType(propertyType)) { - const newType = TypeInference.inferUnclearedType(propertyType, arkClass); - if (newType) { - propertyType = newType; - } - } + let propertyType = IRInference.repairType(propertyAndType?.[1], fieldName, arkClass); let staticFlag: boolean; let signature: BaseSignature; if (baseType instanceof ClassType) { const property = propertyAndType?.[0]; - if (property instanceof ArkField && property.getCategory() !== FieldCategory.ENUM_MEMBER) { + if (property instanceof ArkField && property.getCategory() !== FieldCategory.ENUM_MEMBER && + !(property.getType() instanceof GenericType)) { return property.getSignature(); } staticFlag = @@ -650,6 +647,21 @@ export class IRInference { return new FieldSignature(fieldName, signature, propertyType ?? ref.getType(), staticFlag); } + private static repairType(propertyType: Type | undefined, fieldName: string, arkClass: ArkClass): Type | undefined { + if (!propertyType || propertyType instanceof UnknownType) { + const newType = TypeInference.inferBaseType(fieldName, arkClass); + if (newType) { + propertyType = newType; + } + } else if (TypeInference.isUnclearType(propertyType)) { + const newType = TypeInference.inferUnclearedType(propertyType, arkClass); + if (newType) { + propertyType = newType; + } + } + return propertyType; + } + public static inferAnonymousClass(anon: ArkClass | null, declaredSignature: ClassSignature, set: Set = new Set()): void { if (!anon) { return; @@ -686,7 +698,7 @@ export class IRInference { private static assignAnonMethod(anonMethod: ArkMethod | null, declaredMethod: ArkMethod | null): void { if (declaredMethod && anonMethod) { - anonMethod.setImplementationSignature(declaredMethod.matchMethodSignature(anonMethod.getSubSignature().getParameters())); + anonMethod.setDeclareSignatures(declaredMethod.matchMethodSignature(anonMethod.getSubSignature().getParameters())); } } @@ -698,7 +710,8 @@ export class IRInference { } const type = property.getSignature().getType(); - const lastStmt = anonField.getInitializer().at(-1); + const fieldInitializer = anonField.getInitializer(); + const lastStmt = fieldInitializer[fieldInitializer.length - 1]; if (lastStmt instanceof ArkAssignStmt) { const rightType = lastStmt.getRightOp().getType(); if (type instanceof ClassType) { @@ -815,7 +828,8 @@ export class IRInference { 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(); + const signature = arkMethod.getDeclareSignatures()?.[0] ?? arkMethod.getSignature(); + const type1 = signature.getMethodSubSignature().getParameters()[ref.getIndex()]?.getType(); if (!TypeInference.isUnclearType(type1)) { ref.setType(type1); return ref; diff --git a/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts b/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts index 7b90129608..ae079bea04 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ModelUtils.ts @@ -37,14 +37,7 @@ 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 { 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'; @@ -56,6 +49,14 @@ import { SdkUtils } from './SdkUtils'; export class ModelUtils { public static implicitArkUIBuilderMethods: Set = new Set(); + /* + * Set static field to be null, then all related objects could be freed by GC. + * Static field implicitArkUIBuilderMethods is only used during method body building, the dispose method should be called after build all body. + */ + public static dispose(): void { + this.implicitArkUIBuilderMethods.clear(); + } + public static getMethodSignatureFromArkClass(arkClass: ArkClass, methodName: string): MethodSignature | null { for (const arkMethod of arkClass.getMethods()) { if (arkMethod.getName() === methodName) { @@ -570,8 +571,7 @@ export function getArkFile(im: FromInfo): ArkFile | null | undefined { 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()}`); + logger.warn(`${fromInfo.getOriginName()} ${fromInfo.getFrom()} file not found: ${fromInfo.getDeclaringArkFile()?.getFileSignature()?.toString()}`); return null; } if (fileSignatureCompare(file.getFileSignature(), fromInfo.getDeclaringArkFile().getFileSignature())) { @@ -623,8 +623,8 @@ export function findArkExport(exportInfo: ExportInfo | undefined): ArkExport | n if (arkExport) { exportInfo.setArkExport(arkExport); } else { - logger.warn(`${exportInfo.getExportClauseName()} get arkExport fail from ${exportInfo.getFrom()} at - ${exportInfo.getDeclaringArkFile().getFileSignature().toString()}`); + const file = exportInfo.getDeclaringArkFile().getFileSignature().toString(); + logger.warn(`${exportInfo.getExportClauseName()} get arkExport fail from ${exportInfo.getFrom()} at ${file}`); } return arkExport || null; } diff --git a/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts b/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts index 84f1859878..aa3b7fd421 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts @@ -20,18 +20,80 @@ 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 } from './ModelUtils'; import { Local } from '../base/Local'; import { ArkMethod } from '../model/ArkMethod'; import path from 'path'; import { ClassType } from '../base/Type'; import { AbstractFieldRef } from '../base/Ref'; import { ArkNamespace } from '../model/ArkNamespace'; -import { TypeInference } from './TypeInference'; +import Logger, { LOG_MODULE_TYPE } from '../../utils/logger'; +import { Sdk } from '../../Config'; +import ts from 'ohos-typescript'; +import fs from 'fs'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.ARKANALYZER, 'SdkUtils'); export class SdkUtils { + private static esVersion: string = 'ES2017'; + private static esVersionMap: Map = new Map([ + ['ES2017', 'lib.es2020.d.ts'], + ['ES2021', 'lib.es2021.d.ts'] + ]); private static sdkImportMap: Map = new Map(); + public static BUILT_IN_NAME = 'built-in'; + private static BUILT_IN_PATH = 'node_modules/ohos-typescript/lib'; + public static BUILT_IN_SDK: Sdk = { + moduleName: '', + name: `${SdkUtils.BUILT_IN_NAME}`, + path: '' + }; + + public static setEsVersion(buildProfile: any): void { + const accessChain = 'buildOption.arkOptions.tscConfig.targetESVersion'; + const version = accessChain.split('.').reduce((acc, key) => acc?.[key], buildProfile); + if (version && this.esVersionMap.has(version)) { + this.esVersion = version; + } + } + + public static fetchBuiltInFiles(): string[] { + let builtInPath = this.BUILT_IN_PATH; + try { + // If arkanalyzer is used as dependency by other project, the base directory should be the module path. + const moduleRoot = path.dirname(path.dirname(require.resolve('ohos-typescript'))); + builtInPath = path.join(moduleRoot, 'lib'); + logger.debug(`arkanalyzer is used as dependency, so using builtin sdk file in ${builtInPath}.`); + } catch { + logger.debug(`use builtin sdk file in ${builtInPath}.`); + } + const filePath = path.resolve(builtInPath, this.esVersionMap.get(this.esVersion) ?? ''); + this.BUILT_IN_SDK.path = path.resolve(builtInPath); + if (!fs.existsSync(filePath)) { + logger.error(`built in directory ${filePath} is not exist, please check!`); + return []; + } + const result = new Set(); + this.dfsFiles(filePath, result); + return Array.from(result); + } + + private static dfsFiles(filePath: string, files: Set): void { + const sourceFile = ts.createSourceFile(filePath, fs.readFileSync(filePath, 'utf8'), ts.ScriptTarget.Latest); + const references = sourceFile.libReferenceDirectives; + references.forEach(ref => { + this.dfsFiles(path.join(path.dirname(filePath), `lib.${ref.fileName}.d.ts`), files); + }); + files.add(filePath); + } + + /* + * Set static field to be null, then all related objects could be freed by GC. + * Class SdkUtils is only internally used by ArkAnalyzer type inference, the dispose method should be called at the end of type inference. + */ + public static dispose(): void { + this.sdkImportMap.clear(); + } public static buildSdkImportMap(file: ArkFile): void { const fileName = path.basename(file.getName()); @@ -44,7 +106,7 @@ export class SdkUtils { return this.sdkImportMap.get(from); } - public static buildGlobalMap(file: ArkFile, globalMap: Map): void { + public static loadGlobalAPI(file: ArkFile, globalMap: Map): void { const isGlobalPath = file .getScene() .getOptions() @@ -52,20 +114,59 @@ export class SdkUtils { if (!isGlobalPath) { return; } - ModelUtils.getAllClassesInFile(file).forEach(cls => { + file.getClasses().forEach(cls => { if (!cls.isAnonymousClass() && !cls.isDefaultArkClass()) { - SdkUtils.loadClass(globalMap, cls); + this.loadAPI(cls, globalMap); } if (cls.isDefaultArkClass()) { cls.getMethods() .filter(mtd => !mtd.isDefaultArkMethod() && !mtd.isAnonymousMethod()) - .forEach(mtd => globalMap.set(mtd.getName(), mtd)); + .forEach(mtd => this.loadAPI(mtd, globalMap)); } }); - const defaultArkMethod = file.getDefaultClass().getDefaultArkMethod(); - if (defaultArkMethod) { - TypeInference.inferTypeInMethod(defaultArkMethod); + file.getDefaultClass().getDefaultArkMethod() + ?.getBody() + ?.getAliasTypeMap() + ?.forEach(a => this.loadAPI(a[0], globalMap, true)); + file.getNamespaces().forEach(ns => this.loadAPI(ns, globalMap)); + } + + public static mergeGlobalAPI(file: ArkFile, globalMap: Map): void { + const isGlobalPath = file + .getScene() + .getOptions() + .sdkGlobalFolders?.find(x => file.getFilePath().includes(path.sep + x + path.sep)); + if (!isGlobalPath) { + return; } + file.getClasses().forEach(cls => { + if (!cls.isAnonymousClass() && !cls.isDefaultArkClass()) { + this.loadClass(globalMap, cls); + } + }); + } + + public static loadAPI(api: ArkExport, globalMap: Map, override: boolean = false): void { + const old = globalMap.get(api.getName()); + if (!old) { + globalMap.set(api.getName(), api); + } else if (override) { + logger.trace(`${old.getSignature()} is override`); + globalMap.set(api.getName(), api); + } else { + logger.trace(`duplicated api: ${api.getSignature()}`); + } + } + + public static postInferredSdk(file: ArkFile, globalMap: Map): void { + const isGlobalPath = file + .getScene() + .getOptions() + .sdkGlobalFolders?.find(x => file.getFilePath().includes(path.sep + x + path.sep)); + if (!isGlobalPath) { + return; + } + const defaultArkMethod = file.getDefaultClass().getDefaultArkMethod(); defaultArkMethod ?.getBody() ?.getLocals() @@ -75,25 +176,22 @@ export class SdkUtils { 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); + if (cls === old) { + return; + } else if (old instanceof ArkClass && old.getDeclaringArkFile().getProjectName() === cls.getDeclaringArkFile().getProjectName()) { + if (old.getCategory() === ClassCategory.CLASS || old.getCategory() === ClassCategory.INTERFACE) { + this.copyMembers(cls, old); } else { - this.copyMethod(old, cls); + this.copyMembers(old, cls); globalMap.delete(cls.getName()); - globalMap.set(cls.getName(), cls); + this.loadAPI(cls, globalMap, true); } - } else if (!old) { - globalMap.set(cls.getName(), cls); + } else { + this.loadAPI(cls, globalMap, true); } } @@ -105,29 +203,25 @@ 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)); + this.copyMembers(instance, attr); 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)); + if (old instanceof ArkClass && local.getType() instanceof ClassType) { + const localConstructor = globalMap.get((local.getType() as ClassType).getClassSignature().getClassName()); + if (localConstructor instanceof ArkClass) { + this.copyMembers(localConstructor, old); + } else { + this.loadAPI(local, globalMap, true); } + } else { + this.loadAPI(local, globalMap, true); } } - private static copyMethod(from: ArkClass, to: ArkClass): void { + private static copyMembers(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(); @@ -137,6 +231,12 @@ export class SdkUtils { to.addMethod(method); } }); + from.getFields().forEach(field => { + const dist = field.isStatic() ? to.getStaticFieldWithName(field.getName()) : to.getFieldWithName(field.getName()); + if (!dist) { + to.addField(field); + } + }); } public static computeGlobalThis(leftOp: AbstractFieldRef, arkMethod: ArkMethod): void { diff --git a/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts b/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts index e754272cbf..a2a2b25067 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/TypeInference.ts @@ -16,7 +16,14 @@ 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, GlobalRef +} from '../base/Ref'; import { ArkAliasTypeDefineStmt, ArkAssignStmt, ArkReturnStmt, Stmt } from '../base/Stmt'; import { AliasType, @@ -54,7 +61,7 @@ import { ANY_KEYWORD, BIGINT_KEYWORD, BOOLEAN_KEYWORD, - CONSTRUCTOR_NAME, + CONSTRUCTOR_NAME, DEFAULT, GLOBAL_THIS_NAME, NEVER_KEYWORD, NULL_KEYWORD, @@ -157,7 +164,7 @@ export class TypeInference { type = leftOpType; } } else if (leftOpType instanceof AnnotationNamespaceType) { - type = this.inferUnclearRefName(leftOpType.getOriginType(), declaringArkClass); + type = this.inferBaseType(leftOpType.getOriginType(), declaringArkClass); } else if (leftOpType instanceof UnclearReferenceType) { type = this.inferUnclearRefType(leftOpType, declaringArkClass); } @@ -185,6 +192,15 @@ export class TypeInference { signatures.forEach(s => this.inferSignatureReturnType(s, arkMethod)); return; } + body.getUsedGlobals()?.forEach((value, key) => { + if (value instanceof GlobalRef && !value.getRef()) { + const arkExport = ModelUtils.findGlobalRef(key, arkMethod); + if (arkExport instanceof Local) { + arkExport.getUsedStmts().push(...value.getUsedStmts()); + value.setRef(arkExport); + } + } + }); const cfg = body.getCfg(); for (const block of cfg.getBlocks()) { for (const stmt of block.getStmts()) { @@ -387,7 +403,8 @@ 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 || type instanceof GenericType) { return true; } else if ( type instanceof ClassType && @@ -398,10 +415,10 @@ export class TypeInference { ) { return true; } else if (type instanceof UnionType || type instanceof IntersectionType || type instanceof TupleType) { - return !!type.getTypes().find(t => this.hasUnclearReferenceType(t)); + return !!type.getTypes().find(t => this.checkType(t, e => e instanceof UnclearReferenceType)); } else if (type instanceof ArrayType) { const baseType = type.getBaseType(); - return this.hasUnclearReferenceType(baseType) || baseType instanceof GenericType; + return this.checkType(baseType, t => t instanceof UnclearReferenceType) || baseType instanceof GenericType; } else if (type instanceof AliasType) { return this.isUnclearType(type.getOriginalType()); } else if (type instanceof KeyofTypeExpr) { @@ -412,25 +429,29 @@ export class TypeInference { 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 { + // This is the temporal function to check Type recursively and can be removed after typeInfer supports multiple candidate types. + public static checkType(type: Type, + check: (t: Type) => boolean, + visited: Set = new Set()): boolean { if (visited.has(type)) { return false; } else { visited.add(type); } - if (type instanceof UnclearReferenceType) { + if (check(type)) { return true; + } else if (type instanceof ClassType) { + return !!type.getRealGenericTypes()?.find(t => this.checkType(t, check, visited)); } else if (type instanceof UnionType || type instanceof IntersectionType || type instanceof TupleType) { - return !!type.getTypes().find(t => this.hasUnclearReferenceType(t, visited)); + return !!type.getTypes().find(t => this.checkType(t, check, visited)); } else if (type instanceof ArrayType) { - return this.hasUnclearReferenceType(type.getBaseType(), visited); + return this.checkType(type.getBaseType(), check, visited); } else if (type instanceof AliasType) { - return this.hasUnclearReferenceType(type.getOriginalType(), visited); + return this.checkType(type.getOriginalType(), check, visited); } else if (type instanceof KeyofTypeExpr) { - return this.hasUnclearReferenceType(type.getOpType(), visited); + return this.checkType(type.getOpType(), check, visited); } else if (type instanceof TypeQueryExpr) { - return this.hasUnclearReferenceType(type.getType(), visited); + return this.checkType(type.getType(), check, visited); } return false; } @@ -488,7 +509,7 @@ export class TypeInference { return value.getType(); } - private static inferParameterType(param: MethodParameter, arkMethod: ArkMethod): void { + public static inferParameterType(param: MethodParameter, arkMethod: ArkMethod): void { let pType = param.getType(); const arkClass = arkMethod.getDeclaringArkClass(); let type; @@ -697,13 +718,14 @@ export class TypeInference { if (property instanceof ArkField) { if (arkClass.getCategory() === ClassCategory.ENUM) { let constant; - const lastStmt = property.getInitializer().at(-1); + const propertyInitializer = property.getInitializer(); + const lastStmt = propertyInitializer[propertyInitializer.length - 1]; if (lastStmt instanceof ArkAssignStmt && lastStmt.getRightOp() instanceof Constant) { constant = lastStmt.getRightOp() as Constant; } propertyType = new EnumValueType(property.getSignature(), constant); } else { - propertyType = property.getType(); + propertyType = this.replaceTypeWithReal(property.getType(), baseType.getRealGenericTypes()); } } else if (property) { propertyType = this.parseArkExport2Type(property); @@ -728,6 +750,8 @@ export class TypeInference { public static inferBaseType(baseName: string, arkClass: ArkClass): Type | null { if (SUPER_NAME === baseName) { return this.parseArkExport2Type(arkClass.getSuperClass()); + } else if (DEFAULT === baseName) { + return this.parseArkExport2Type(arkClass.getDeclaringArkFile().getExportInfoBy(DEFAULT)?.getArkExport()); } const field = ModelUtils.getDefaultClass(arkClass)?.getDefaultArkMethod()?.getBody()?.getLocals()?.get(baseName); if (field && !this.isUnclearType(field.getType())) { @@ -750,18 +774,21 @@ export class TypeInference { 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)) { + if (!arkExport && !arkClass.getDeclaringArkFile().getImportInfoBy(typeName)) { arkExport = arkClass.getDeclaringArkFile().getScene().getSdkGlobal(typeName); } - if (arkExport instanceof ArkClass || arkExport instanceof AliasType) { - return this.parseArkExport2Type(arkExport); + const type = this.parseArkExport2Type(arkExport); + if (type instanceof ClassType || type instanceof AliasType) { + return type; } return null; } + public static getTypeByGlobalName(globalName: string, arkMethod: ArkMethod): Type | null { + const arkExport: ArkExport | null = arkMethod.getDeclaringArkFile().getScene().getSdkGlobal(globalName); + return this.parseArkExport2Type(arkExport); + } + public static inferRealGenericTypes(realTypes: Type[] | undefined, arkClass: ArkClass): void { if (!realTypes) { return; @@ -860,12 +887,14 @@ export class TypeInference { .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); + if (this.isUnclearType(p.getType())) { + let type = params?.[i]?.getType(); + if (type instanceof GenericType && realTypes) { + type = realTypes?.[type.getIndex()]; + } + if (type) { + p.setType(type); + } } }); } @@ -876,7 +905,7 @@ export class TypeInference { } let returnType: Type | undefined = arkMethod.getSignature().getType(); if (returnType instanceof ClassType && returnType.getClassSignature().getClassName() === PROMISE) { - returnType = returnType.getRealGenericTypes()?.at(0); + returnType = returnType.getRealGenericTypes()?.[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 index 1731b701b0..8a29e565b8 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/ValueUtil.ts @@ -21,6 +21,14 @@ export class ValueUtil { private static readonly NumberConstantCache: Map = new Map(); public static readonly EMPTY_STRING_CONSTANT = new StringConstant(EMPTY_STRING); + /* + * Set static field to be null, then all related objects could be freed by GC. + * Class SdkUtils is only internally used by ArkAnalyzer, the dispose method should be called by users themselves before drop Scene. + */ + public static dispose(): void { + this.NumberConstantCache.clear(); + } + public static getOrCreateNumberConst(n: number): Constant { let constant = this.NumberConstantCache.get(n); if (constant === undefined) { diff --git a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts index 523dd9a41b..325fa23634 100644 --- a/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts +++ b/ets2panda/linter/arkanalyzer/src/core/dataflow/DataflowSolver.ts @@ -24,6 +24,7 @@ import { CallGraph } from '../../callgraph/model/CallGraph'; import { ClassHierarchyAnalysis } from '../../callgraph/algorithm/ClassHierarchyAnalysis'; import { addCfg2Stmt } from '../../utils/entryMethodUtils'; import { getRecallMethodInParam } from './Util'; +import { CallGraphBuilder } from '../../callgraph/model/builder/CallGraphBuilder'; /* this program is roughly an implementation of the paper: Practical Extensions to the IFDS Algorithm. @@ -88,7 +89,7 @@ export abstract class DataflowSolver { // build CHA let cg = new CallGraph(this.scene); - this.CHA = new ClassHierarchyAnalysis(this.scene, cg); + this.CHA = new ClassHierarchyAnalysis(this.scene, cg, new CallGraphBuilder(cg, this.scene)); this.buildStmtMapInClass(); this.setCfg4AllStmt(); return; diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts b/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts index aeb568012d..ccafdd7067 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/Scc.ts @@ -173,7 +173,7 @@ export class SCCDetection> { if (this.getRep(v) === v) { this.setInSCC(v); while (this._S.length > 0) { - let w = this._S.at(this._S.length - 1)!; + let w = this._S[this._S.length - 1]!; if (this._D.get(w)! <= this._D.get(v)!) { break; } else { diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts index 5cd44402ec..478d0a7121 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/CfgBuilder.ts @@ -32,6 +32,7 @@ import { ConditionBuilder } from './ConditionBuilder'; import { TrapBuilder } from './TrapBuilder'; import { CONSTRUCTOR_NAME, PROMISE } from '../../common/TSConst'; import { ModifierType } from '../../model/ArkBaseModel'; +import { ParameterDeclaration } from 'ohos-typescript'; class StatementBuilder { type: string; @@ -524,7 +525,7 @@ export class CfgBuilder { 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)) { + if (ts.isVariableStatement(c) || ts.isExpressionStatement(c) || ts.isThrowStatement(c) || ts.isTypeAliasDeclaration(c) || ts.isParameter(c)) { let s = new StatementBuilder('statement', c.getText(this.sourceFile), c, scope.id); this.judgeLastType(s, lastStatement); lastStatement = s; @@ -677,6 +678,9 @@ export class CfgBuilder { for (let i = stmt.nexts.length - 1; i >= 0; i--) { stmtQueue.push(stmt.nexts[i]); } + if (stmt.afterSwitch && stmt.afterSwitch.lasts.size === 0) { + stmtQueue.push(stmt.afterSwitch); + } } else if (stmt instanceof TryStatementBuilder) { if (stmt.finallyStatement) { stmtQueue.push(stmt.finallyStatement); @@ -956,6 +960,16 @@ export class CfgBuilder { this.exit.lasts = new Set([s]); } + private getParamPropertyNodes(constructorParams: ts.NodeArray): ts.Node[] { + let stmts: ts.Node[] = []; + constructorParams.forEach(parameter => { + if (parameter.modifiers !== undefined) { + stmts.push(parameter); + } + }); + return stmts; + } + buildCfgBuilder(): void { let stmts: ts.Node[] = []; if (ts.isSourceFile(this.astRoot)) { @@ -969,11 +983,7 @@ export class CfgBuilder { ts.isFunctionExpression(this.astRoot) || ts.isClassStaticBlockDeclaration(this.astRoot) ) { - if (this.astRoot.body) { - stmts = [...this.astRoot.body.statements]; - } else { - this.emptyBody = true; - } + this.astRoot.body ? stmts = [...this.astRoot.body.statements] : this.emptyBody = true; } else if (ts.isArrowFunction(this.astRoot)) { if (ts.isBlock(this.astRoot.body)) { stmts = [...this.astRoot.body.statements]; @@ -988,6 +998,10 @@ export class CfgBuilder { } else if (ts.isModuleDeclaration(this.astRoot) && ts.isModuleBlock(this.astRoot.body!)) { stmts = [...this.astRoot.body.statements]; } + // For constructor, add parameter property node to stmts which can be used when build body + if (ts.isConstructorDeclaration(this.astRoot)) { + stmts = [...this.getParamPropertyNodes(this.astRoot.parameters), ...stmts]; + } if (!ModelUtils.isArkUIBuilderMethod(this.declaringMethod)) { this.walkAST(this.entry, this.exit, stmts); } else { @@ -996,6 +1010,7 @@ export class CfgBuilder { if (ts.isArrowFunction(this.astRoot) && !ts.isBlock(this.astRoot.body)) { this.buildStatementBuilder4ArrowFunction(this.astRoot.body); } + this.addReturnInEmptyMethod(); this.deleteExit(); this.CfgBuilder2Array(this.entry); diff --git a/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts index 160df9fdc0..9094994dc5 100644 --- a/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/graph/builder/TrapBuilder.ts @@ -19,7 +19,15 @@ 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'; @@ -217,16 +225,17 @@ export class TrapBuilder { 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); + // A tail block's successor may be within the traversal range + if (child === endBlockBuilder) { + tailBlocks.push(currBlock); + } else { + queue.push(child); + } } + } else { + tailBlocks.push(currBlock); } } return { bfsBlocks, tailBlocks }; @@ -247,19 +256,16 @@ export class TrapBuilder { 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); }); + copyFinallyBfsBlocks.push(...copyFinallyTailBlocks); copyFinallyTailBlocks = [newCopyFinallyTailBlock]; } - copyFinallyTailBlocks[0]?.addStmt(throwStmt); + copyFinallyTailBlocks[0].addStmt(throwStmt); copyFinallyBfsBlocks.push(...copyFinallyTailBlocks); copyFinallyBfsBlocks.forEach((copyFinallyBfsBlock: BasicBlock) => { basicBlockSet.add(copyFinallyBfsBlock); @@ -281,12 +287,19 @@ export class TrapBuilder { for (const sourceBlock of sourceBlocks) { const targetBlock = sourceToTarget.get(sourceBlock)!; for (const predecessor of sourceBlock.getPredecessors()) { - const targetPredecessor = sourceToTarget.get(predecessor)!; - targetBlock.addPredecessorBlock(targetPredecessor); + const targetPredecessor = sourceToTarget.get(predecessor); + // Only include blocks within the copy range, so that predecessor and successor relationships to + // external blocks can be trimmed + if (targetPredecessor) { + targetBlock.addPredecessorBlock(targetPredecessor); + } + } for (const successor of sourceBlock.getSuccessors()) { - const targetSuccessor = sourceToTarget.get(successor)!; - targetBlock.addSuccessorBlock(targetSuccessor); + const targetSuccessor = sourceToTarget.get(successor); + if (targetSuccessor) { + targetBlock.addSuccessorBlock(targetSuccessor); + } } } return targetBlocks; diff --git a/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts b/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts index f3476d3567..789e940e89 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/ArkMethod.ts @@ -15,7 +15,16 @@ import { ArkParameterRef, ArkThisRef } from '../base/Ref'; import { ArkAssignStmt, ArkReturnStmt, Stmt } from '../base/Stmt'; -import { ClassType, EnumValueType, FunctionType, GenericType, LiteralType, Type, UnionType } from '../base/Type'; +import { + AliasType, + 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'; @@ -24,17 +33,17 @@ import { ArkClass, ClassCategory } from './ArkClass'; 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'; +import { ANONYMOUS_METHOD_PREFIX, DEFAULT_ARK_METHOD_NAME, LEXICAL_ENV_NAME_PREFIX } 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 { ArkFile, Language } from './ArkFile'; import { CONSTRUCTOR_NAME } from '../common/TSConst'; import { MethodParameter } from './builder/ArkMethodBuilder'; +import { TypeInference } from '../common/TypeInference'; export const arkMethodNodeKind = [ 'MethodDeclaration', @@ -623,45 +632,46 @@ 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 true; - }) ?? + signatures?.find(p => this.isMatched(p.getMethodSubSignature().getParameters(), args)) ?? 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(); + private isMatched(parameters: MethodParameter[], args: Value[], isArrowFunc: boolean = false): boolean { + for (let i = 0; i < parameters.length; i++) { + if (!args[i]) { + return isArrowFunc ? true : parameters[i].isOptional(); } + const paramType = parameters[i].getType(); + const isMatched = this.matchParam(paramType, args[i]); + if (!isMatched) { + return false; + } else if (paramType instanceof EnumValueType || paramType instanceof LiteralType) { + return true; + } + } + return true; + } + + private matchParam(paramType: Type, arg: Value): boolean { + if (paramType instanceof EnumValueType || paramType instanceof LiteralType) { + arg = ArkMethod.parseArg(arg); + } + const argType = arg.getType(); + if (paramType instanceof AliasType && !(argType instanceof AliasType)) { + paramType = TypeInference.replaceAliasType(paramType); } if (paramType instanceof UnionType) { - let matched = false; - for (const e of paramType.getTypes()) { - if (argType.constructor === e.constructor) { - matched = true; - break; - } - } - return matched; + return !!paramType.getTypes().find(p => this.matchParam(p, arg)); } else if (argType instanceof FunctionType && paramType instanceof FunctionType) { - return argType.getMethodSignature().getParamLength() === paramType.getMethodSignature().getParamLength(); + if (argType.getMethodSignature().getParamLength() > paramType.getMethodSignature().getParamLength()) { + return false; + } + const parameters = paramType.getMethodSignature().getMethodSubSignature().getParameters(); + const args = argType.getMethodSignature().getMethodSubSignature().getParameters().filter(p => !p.getName().startsWith(LEXICAL_ENV_NAME_PREFIX)); + return this.isMatched(parameters, args, true); } else if (paramType instanceof ClassType && paramType.getClassSignature().getClassName().includes(CALL_BACK)) { return argType instanceof FunctionType; } else if (paramType instanceof LiteralType && arg instanceof Constant) { @@ -684,6 +694,19 @@ export class ArkMethod extends ArkBaseModel implements ArkExport { return argType.constructor === paramType.constructor; } + private static parseArg(arg: Value): Value { + if (arg instanceof Local) { + const stmt = arg.getDeclaringStmt(); + const argType = arg.getType(); + if (argType instanceof EnumValueType && argType.getConstant()) { + arg = argType.getConstant()!; + } else if (stmt instanceof ArkAssignStmt && stmt.getRightOp() instanceof Constant) { + arg = stmt.getRightOp(); + } + } + return arg; + } + public getOuterMethod(): ArkMethod | undefined { return this.outerMethod; } diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts index 7c3f169384..dcef17ac8d 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/ArkClassBuilder.ts @@ -370,7 +370,17 @@ function buildArkClassMembers(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: const instanceInitStmts: Stmt[] = []; let staticBlockId = 0; clsNode.members.forEach(member => { - if (ts.isPropertyDeclaration(member) || ts.isPropertySignature(member)) { + if ( + ts.isMethodDeclaration(member) || + ts.isConstructorDeclaration(member) || + ts.isMethodSignature(member) || + ts.isConstructSignatureDeclaration(member) || + ts.isAccessor(member) || + ts.isCallSignatureDeclaration(member) + ) { + // these node types have been handled at the beginning of this function by calling buildMethodsForClass + return; + } else 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()) { @@ -395,9 +405,9 @@ function buildArkClassMembers(clsNode: ClassLikeNode, cls: ArkClass, sourceFile: const staticBlockInvokeExpr = new ArkStaticInvokeExpr(currStaticBlockMethodSig, []); staticInitStmts.push(new ArkInvokeStmt(staticBlockInvokeExpr)); } else if (ts.isSemicolonClassElement(member)) { - logger.debug('Skip these members.'); + logger.trace('Skip these members.'); } else { - logger.warn('Please contact developers to support new member type!'); + logger.warn(`Please contact developers to support new member in class: ${cls.getSignature().toString()}, member: ${member.getText()}!`); } }); if (ts.isClassDeclaration(clsNode) || ts.isClassExpression(clsNode) || ts.isStructDeclaration(clsNode)) { @@ -456,6 +466,9 @@ function buildParameterProperty2ArkField(params: ts.NodeArray namespace.addExportInfo(item)); } else { - logger.info('Child joined default method of arkFile: ', ts.SyntaxKind[child.kind]); + logger.trace('Child joined default method of arkFile: ', ts.SyntaxKind[child.kind]); // join default method } }); diff --git a/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts b/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts index 77b28a411f..8a6286bd30 100644 --- a/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts +++ b/ets2panda/linter/arkanalyzer/src/core/model/builder/BodyBuilder.ts @@ -571,6 +571,7 @@ export class BodyBuilder { const closuresLocal = new Local(closuresParam.getName(), lexicalEnv); body.addLocal(closuresLocal.getName(), closuresLocal); let assignStmt = new ArkAssignStmt(closuresLocal, parameterRef); + assignStmt.setCfg(body.getCfg()); stmts.splice(index, 0, assignStmt); closuresLocal.setDeclaringStmt(assignStmt); @@ -590,6 +591,7 @@ export class BodyBuilder { index++; const closureFieldRef = new ClosureFieldRef(closuresParam, closure.getName(), closure.getType()); let assignStmt = new ArkAssignStmt(local, closureFieldRef); + assignStmt.setCfg(body.getCfg()); stmts.splice(index, 0, assignStmt); local.setDeclaringStmt(assignStmt); closuresLocal.addUsedStmt(assignStmt); diff --git a/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts b/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts index 283de26011..e9c2696bf8 100644 --- a/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts +++ b/ets2panda/linter/arkanalyzer/src/save/JsonPrinter.ts @@ -22,20 +22,20 @@ import { ArkField } from '../core/model/ArkField'; import { AliasType, AnnotationNamespaceType, - AnnotationType, AnnotationTypeQueryType, AnyType, ArrayType, BigIntType, BooleanType, ClassType, + EnumValueType, FunctionType, GenericType, + IntersectionType, LiteralType, NeverType, NullType, NumberType, - PrimitiveType, StringType, TupleType, Type, @@ -46,11 +46,16 @@ 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 { - AbstractBinopExpr, - AbstractExpr, - AbstractInvokeExpr, + ArkAssignStmt, + ArkIfStmt, + ArkInvokeStmt, + ArkReturnStmt, + ArkReturnVoidStmt, + ArkThrowStmt, + Stmt, +} from '../core/base/Stmt'; +import { ArkAwaitExpr, ArkCastExpr, ArkConditionExpr, @@ -73,13 +78,12 @@ 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 { ArkArrayRef, ArkCaughtExceptionRef, ArkInstanceFieldRef, ArkParameterRef, ArkStaticFieldRef, ArkThisRef, ClosureFieldRef, GlobalRef } 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) { @@ -113,8 +117,9 @@ 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)), + category: clazz.getCategory(), superClassName: clazz.getSuperClassName(), implementedInterfaceNames: clazz.getImplementedInterfaceNames(), fields: clazz.getFields().map(field => this.serializeField(field)), @@ -155,6 +160,7 @@ export class JsonPrinter extends Printer { name: parameter.getName(), type: this.serializeType(parameter.getType()), isOptional: parameter.isOptional(), + isRest: parameter.hasDotDotDotToken(), }; } @@ -220,6 +226,11 @@ export class JsonPrinter extends Printer { _: 'UnionType', types: type.getTypes().map(type => this.serializeType(type)), }; + } else if (type instanceof IntersectionType) { + return { + _: 'IntersectionType', + types: type.getTypes().map((type) => this.serializeType(type)), + }; } else if (type instanceof TupleType) { return { _: 'TupleType', @@ -254,8 +265,6 @@ export class JsonPrinter extends Printer { _: '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', @@ -281,13 +290,13 @@ export class JsonPrinter extends Printer { typeParameters: type.getGenericTypes().map(type => this.serializeType(type)), }; } else if (type instanceof GenericType) { - let defaultType = type.getDefaultType(); let constraint = type.getConstraint(); + let defaultType = type.getDefaultType(); return { _: 'GenericType', name: type.getName(), - defaultType: defaultType && this.serializeType(defaultType), constraint: constraint && this.serializeType(constraint), + defaultType: defaultType && this.serializeType(defaultType), }; } else if (type instanceof AliasType) { return { @@ -307,10 +316,19 @@ export class JsonPrinter extends Printer { _: 'AnnotationTypeQueryType', originType: type.getOriginType(), }; - } else if (type instanceof AnnotationType) { - throw new Error('Unhandled AnnotationType: ' + util.inspect(type, { showHidden: true, depth: null })); + } else if (type instanceof EnumValueType) { + const c = type.getConstant(); + return { + _: 'EnumValueType', + signature: this.serializeFieldSignature(type.getFieldSignature()), + constant: c && this.serializeValue(c), + }; } else { - throw new Error('Unhandled Type: ' + util.inspect(type, { showHidden: true, depth: null })); + console.warn(`Unhandled Type: ${type.constructor.name} (${type.toString()})`); + return { + _: type.constructor.name, + text: type.toString(), + }; } } @@ -415,6 +433,13 @@ export class JsonPrinter extends Printer { }; } + private serializeConstant(constant: Constant): object { + return { + value: constant.getValue(), + type: this.serializeType(constant.getType()), + }; + } + private serializeValue(value: Value): object { if (value === undefined) { throw new Error('Value is undefined'); @@ -428,8 +453,7 @@ export class JsonPrinter extends Printer { } else if (value instanceof Constant) { return { _: 'Constant', - value: value.getValue(), - type: this.serializeType(value.getType()), + ...this.serializeConstant(value), }; } else if (value instanceof ArkNewExpr) { return { @@ -498,8 +522,6 @@ export class JsonPrinter extends Printer { 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', @@ -526,8 +548,6 @@ export class JsonPrinter extends Printer { 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', @@ -546,6 +566,25 @@ export class JsonPrinter extends Printer { index: this.serializeValue(value.getIndex()), type: this.serializeType(value.getType()), }; + } else if (value instanceof ArkCaughtExceptionRef) { + return { + _: 'CaughtExceptionRef', + type: this.serializeType(value.getType()), + }; + } else if (value instanceof GlobalRef) { + let ref = value.getRef(); + return { + _: 'GlobalRef', + name: value.getName(), + ref: ref ? this.serializeValue(ref) : null, + }; + } else if (value instanceof ClosureFieldRef) { + return { + _: 'ClosureFieldRef', + base: this.serializeLocal(value.getBase()), + fieldName: value.getFieldName(), + type: this.serializeType(value.getType()), + }; } else if (value instanceof ArkInstanceFieldRef) { return { _: 'InstanceFieldRef', @@ -557,14 +596,13 @@ export class JsonPrinter extends Printer { _: '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 })); + console.warn(`Unhandled Value: ${value.constructor.name} (${value.toString()})`); + return { + _: value.constructor.name, + text: value.toString(), + type: this.serializeType(value.getType()), + }; } } @@ -600,7 +638,11 @@ export class JsonPrinter extends Printer { arg: this.serializeValue(stmt.getOp()), }; } else { - throw new Error('Unhandled Stmt: ' + util.inspect(stmt, { showHidden: true, depth: null })); + console.warn(`Unhandled Stmt: ${stmt.constructor.name} (${stmt.toString()})`); + return { + _: stmt.constructor.name, + text: stmt.toString(), + }; } } } diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts index b33546dce3..d1437e94dc 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceBody.ts @@ -126,8 +126,9 @@ export class SourceBody implements StmtPrinterContext { this.tempCodeMap.set(temp, code); } - public transTemp2Code(temp: Local): string { - if (this.tempCodeMap.has(temp.getName()) && PrinterUtils.isTemp(temp.getName())) { + public transTemp2Code(temp: Local, isLeftOp: boolean = false): string { + // if the temp local is not the left op of ArkAssignStmt, it should get the actual text from tempCodeMap + if (!isLeftOp && this.tempCodeMap.has(temp.getName()) && PrinterUtils.isTemp(temp.getName())) { this.tempVisitor.add(temp.getName()); return this.tempCodeMap.get(temp.getName())!; } diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts index 6f73ec3dc8..78452b5658 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceStmt.ts @@ -14,10 +14,31 @@ */ 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 { + 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'; @@ -166,7 +187,7 @@ export class SourceAssignStmt extends SourceStmt { return; } - this.leftCode = this.transformer.valueToString(this.leftOp); + this.leftCode = this.transformer.valueToString(this.leftOp, true); if (this.leftOp instanceof Local && this.rightOp instanceof ArkNewExpr) { this.transferRightNewExpr(); @@ -380,8 +401,8 @@ export class SourceInvokeStmt extends SourceStmt { isAttr = PrinterUtils.isComponentIfElseInvoke(invokeExpr); } } else if (invokeExpr instanceof ArkInstanceInvokeExpr) { - code = this.transformer.instanceInvokeExprToString(invokeExpr); isAttr = PrinterUtils.isComponentAttributeInvoke(invokeExpr); + code = this.transformer.instanceInvokeExprToString(invokeExpr, isAttr); } if (code.length > 0 && !isAttr) { @@ -511,7 +532,7 @@ export class SourceWhileStmt extends SourceStmt { return false; } - if (iterator.getMethodSignature().getMethodSubSignature().getMethodName() !== 'iterator') { + if (iterator.getMethodSignature().getMethodSubSignature().getMethodName() !== 'Symbol.iterator') { return false; } diff --git a/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts b/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts index 58c999d85b..d199e7fc17 100644 --- a/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts +++ b/ets2panda/linter/arkanalyzer/src/save/source/SourceTransformer.ts @@ -60,7 +60,12 @@ 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'; @@ -84,7 +89,7 @@ export interface TransformerContext { getPrinter(): ArkCodeBuffer; - transTemp2Code(temp: Local): string; + transTemp2Code(temp: Local, isLeftOp: boolean): string; isInBuilderMethod(): boolean; } @@ -107,7 +112,7 @@ export class SourceTransformer { return clsPrinter.dump().trimStart(); } - public instanceInvokeExprToString(invokeExpr: ArkInstanceInvokeExpr): string { + public instanceInvokeExprToString(invokeExpr: ArkInstanceInvokeExpr, isAttr: boolean): string { let methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName(); if (methodName === INSTANCE_INIT_METHOD_NAME) { return ''; @@ -116,9 +121,8 @@ export class SourceTransformer { invokeExpr.getArgs().forEach(v => { args.push(this.valueToString(v)); }); - let genericCode = this.genericTypesToString(invokeExpr.getRealGenericTypes()); - - if (PrinterUtils.isComponentAttributeInvoke(invokeExpr) && this.context.isInBuilderMethod()) { + let genericCode = isAttr ? '' : this.genericTypesToString(invokeExpr.getRealGenericTypes()); + if (isAttr && this.context.isInBuilderMethod()) { return `.${methodName}${genericCode}(${args.join(', ')})`; } @@ -227,7 +231,8 @@ export class SourceTransformer { private exprToString(expr: AbstractExpr): string { if (expr instanceof ArkInstanceInvokeExpr) { - return `${this.instanceInvokeExprToString(expr)}`; + const isAttr = PrinterUtils.isComponentAttributeInvoke(expr); + return `${this.instanceInvokeExprToString(expr, isAttr)}`; } if (expr instanceof ArkStaticInvokeExpr) { @@ -251,7 +256,7 @@ export class SourceTransformer { let op2: Value = expr.getOp2(); let operator: string = expr.getOperator(); - return `${this.valueToString(op1, operator)} ${operator} ${this.valueToString(op2, operator)}`; + return `${this.valueToString(op1, false, operator)} ${operator} ${this.valueToString(op2, false, operator)}`; } if (expr instanceof ArkTypeOfExpr) { @@ -310,7 +315,7 @@ export class SourceTransformer { return `${value}`; } - public valueToString(value: Value, operator?: string): string { + public valueToString(value: Value, isLeftOp: boolean = false, operator?: string): string { if (value instanceof AbstractExpr) { return this.exprToString(value); } @@ -324,14 +329,14 @@ export class SourceTransformer { } if (value instanceof Local) { - return this.localToString(value, operator); + return this.localToString(value, isLeftOp, operator); } logger.info(`valueToString ${value.constructor} not support.`); return `${value}`; } - private localToString(value: Local, operator?: string): string { + private localToString(value: Local, isLeftOp: boolean = false, operator?: string): string { if (PrinterUtils.isAnonymousMethod(value.getName())) { let methodSignature = (value.getType() as FunctionType).getMethodSignature(); let anonymousMethod = this.context.getMethod(methodSignature); @@ -351,12 +356,12 @@ export class SourceTransformer { 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, isLeftOp)})`; } } } - return this.context.transTemp2Code(value); + return this.context.transTemp2Code(value, isLeftOp); } public literalObjectToString(type: ClassType): string { diff --git a/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts b/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts index 2c7e78deec..1f1383c18c 100644 --- a/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts +++ b/ets2panda/linter/arkanalyzer/src/transformer/StaticSingleAssignmentFormer.ts @@ -73,7 +73,7 @@ export class StaticSingleAssignmentFormer { 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 block = blocks.splice(0, 1)[0] as BasicBlock; let dfs = dominanceFinder.getDominanceFrontiers(block); for (const df of dfs) { this.handleDf(blockToPhiStmts, blockToPhiLocals, phiBlocks, df, local, blockToDefs, blocks); diff --git a/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts b/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts index fcb5c816ac..313fb88f35 100644 --- a/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts +++ b/ets2panda/linter/arkanalyzer/src/utils/SparseBitVector.ts @@ -538,7 +538,6 @@ export class SparseBitVector { return changed; } - // Dump as string toString(): string { let ar = [...this]; return ar.toString(); diff --git a/ets2panda/linter/arkanalyzer/typedoc.json b/ets2panda/linter/arkanalyzer/typedoc.json index 1b08d68d69..e582cf129b 100644 --- a/ets2panda/linter/arkanalyzer/typedoc.json +++ b/ets2panda/linter/arkanalyzer/typedoc.json @@ -16,6 +16,7 @@ ], "excludeInternal": true, "useTsLinkResolution": true, + "plugin": "typedoc-plugin-markdown", "out": "docs/api_docs", "readme": "./README.en.md" } \ No newline at end of file diff --git a/ets2panda/linter/build_linter.py b/ets2panda/linter/build_linter.py index cfc970134c..3634b84a25 100755 --- a/ets2panda/linter/build_linter.py +++ b/ets2panda/linter/build_linter.py @@ -36,6 +36,9 @@ def copy_files(source_path, dest_path, is_file=False): def run_cmd(cmd, execution_path=None): + if (cmd and cmd[0].strip().endswith('npm')): + cmd.append('--registry') + cmd.append('https://repo.huaweicloud.com/repository/npm/') proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, @@ -48,15 +51,24 @@ def run_cmd(cmd, execution_path=None): def run_cmd_with_retry(max_retries, wait_time, cmd, execution_path=None): retry_count = 0 + last_exception = None while retry_count < max_retries: try: run_cmd(cmd, execution_path) break - except Exception: + except Exception as e: + last_exception = e retry_count += 1 time.sleep(wait_time) if retry_count >= max_retries: - raise Exception("Failed to run cmd: " + cmd) + raise Exception( + "Command failed after {r} attempts. Cmd: {c}. Error: {e}" + .format( + r=max_retries, + c=" ".join(cmd), + e=last_exception + ) + ) def is_npm_newer_than_6(options): diff --git a/ets2panda/linter/homecheck/ruleSet.json b/ets2panda/linter/homecheck/ruleSet.json index adfc2898b5..1dcacfee1b 100644 --- a/ets2panda/linter/homecheck/ruleSet.json +++ b/ets2panda/linter/homecheck/ruleSet.json @@ -208,6 +208,8 @@ "@migration/interop-dynamic-object-literals": 1, "@migration/interop-assign": 1, "@migration/interop-boxed-type-check": 1, - "@migration/interop-js-modify-property": 1 + "@migration/interop-js-modify-property": 1, + "@migration/arkts-interop-s2d-object-literal": 1, + "@migration/arkts-interop-s2d-dynamic-call-builtin-api-not-in-static": 1 } -} +} \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/Index.ts b/ets2panda/linter/homecheck/src/Index.ts index 6ad78b6bfe..b3228e9bd5 100644 --- a/ets2panda/linter/homecheck/src/Index.ts +++ b/ets2panda/linter/homecheck/src/Index.ts @@ -42,4 +42,4 @@ export { Utils } from './utils/common/Utils'; // tools export { runTool, Tools } from './tools/toolEntry'; -export { MigrationTool } from './tools/migrationTool/MigrationTool'; +export { MigrationTool } from './tools/migrationTool/MigrationTool'; \ No newline at end of file diff --git a/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts index 693f891412..8e1ef29f16 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/AppStorageGetCheck.ts @@ -139,7 +139,7 @@ export class AppStorageGetCheck implements BaseChecker { } private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { - const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { const originPath = arkFile.getFilePath(); diff --git a/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts index b8dcb06db7..5243a14f39 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts @@ -149,15 +149,18 @@ export class CustomBuilderCheck implements BaseChecker { } private isPassToCustomBuilder(stmt: Stmt, locals: Set): Local | undefined { + let res: Local | undefined = undefined; if (stmt instanceof ArkAssignStmt) { - if (!this.isCustomBuilderTy(stmt.getLeftOp().getType())) { - return undefined; - } - const rightOp = stmt.getRightOp(); - if (rightOp instanceof Local && locals.has(rightOp)) { - return rightOp; + if (this.isCustomBuilderTy(stmt.getLeftOp().getType())) { + const rightOp = stmt.getRightOp(); + if (rightOp instanceof Local && locals.has(rightOp)) { + res = rightOp; + } } } + if (res !== undefined) { + return res; + } const invokeExpr = stmt.getInvokeExpr(); if (invokeExpr) { const paramTys = invokeExpr.getMethodSignature().getMethodSubSignature().getParameterTypes(); @@ -208,7 +211,7 @@ export class CustomBuilderCheck implements BaseChecker { } private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { - const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { const originPath = arkFile.getFilePath(); @@ -229,7 +232,7 @@ export class CustomBuilderCheck implements BaseChecker { fixPosition.endLine = endPosition.line; fixPosition.endCol = endPosition.col; } - const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const sourceFile = AstTreeUtils.getASTNode(arkFile.getName(), arkFile.getCode()); const range = FixUtils.getRangeWithAst(sourceFile, fixPosition); ruleFix.range = range; diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts index d956fe529c..a17b9064ba 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts @@ -98,7 +98,7 @@ export class InteropAssignCheck implements BaseChecker { callsites.forEach(cs => { let hasTargetArg = false; const invoke = cs.getInvokeExpr()!; - const csMethod = cs.getCfg()?.getDeclaringMethod(); + const csMethod = cs.getCfg().getDeclaringMethod(); invoke.getArgs().forEach(arg => { const argTy = arg.getType(); if (argTy instanceof PrimitiveType || this.isBoxedType(argTy)) { @@ -149,7 +149,7 @@ export class InteropAssignCheck implements BaseChecker { 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 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)); }); @@ -265,8 +265,6 @@ export class InteropAssignCheck implements BaseChecker { } 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 index 9651894a32..7f231f51fa 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/InteropBackwardDFACheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropBackwardDFACheck.ts @@ -176,11 +176,14 @@ export class InteropBackwardDFACheck implements BaseChecker { const invoke = stmt.getInvokeExpr(); let isReflect = false; let paramIdx = -1; - if (invoke && invoke instanceof ArkInstanceInvokeExpr) { - if (invoke.getBase().getName() === 'Reflect') { + if (invoke && invoke instanceof ArkStaticInvokeExpr) { + const classSig = invoke.getMethodSignature().getDeclaringClassSignature(); + if ( + classSig.getDeclaringFileSignature().getProjectName() === 'built-in' && + classSig.getDeclaringNamespaceSignature()?.getNamespaceName() === 'Reflect' + ) { isReflect = true; - paramIdx = - REFLECT_API.get(invoke.getMethodSignature().getMethodSubSignature().getMethodName()) ?? -1; + paramIdx = REFLECT_API.get(invoke.getMethodSignature().getMethodSubSignature().getMethodName()) ?? -1; } } if (invoke && invoke instanceof ArkStaticInvokeExpr) { @@ -214,7 +217,7 @@ export class InteropBackwardDFACheck implements BaseChecker { private reportIssue(objDefInfo: ObjDefInfo, apiLang: Language, isReflect: boolean) { const problemStmt = objDefInfo.problemStmt; - const problemStmtMtd = problemStmt.getCfg()?.getDeclaringMethod(); + const problemStmtMtd = problemStmt.getCfg().getDeclaringMethod(); const problemStmtLang = problemStmtMtd?.getLanguage(); const objLanguage = objDefInfo.objLanguage; if (objLanguage === Language.UNKNOWN || problemStmtLang === Language.UNKNOWN) { diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropBoxedTypeCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropBoxedTypeCheck.ts index 42b4dc0973..d0a1c9b10f 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/InteropBoxedTypeCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropBoxedTypeCheck.ts @@ -40,7 +40,7 @@ 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 logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'InteropBoxedTypeCheck'); const gMetaData: BaseMetaData = { severity: 1, ruleDocPath: '', diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropDeprecatedBuiltInAPICheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropDeprecatedBuiltInAPICheck.ts new file mode 100644 index 0000000000..b8af6a32c8 --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropDeprecatedBuiltInAPICheck.ts @@ -0,0 +1,928 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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, + CallGraph, + ArkParameterRef, + ArkInstanceFieldRef, + ArkNamespace, + Local, + ClassType, + ArkField, + ClassSignature, + Type, + BooleanType, + FunctionType, + AnyType, + MethodSignature, + UnknownType, + GenericType, + NumberType, + ArrayType, + MethodSubSignature, + ArkInvokeStmt, + AbstractInvokeExpr, + ArkInstanceInvokeExpr, + ArkPtrInvokeExpr, + ImportInfo, + UnionType, + FileSignature, + ArkStaticInvokeExpr, + UndefinedType, + VoidType, +} 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 { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass'; +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; +import { MethodParameter } from 'arkanalyzer/lib/core/model/builder/ArkMethodBuilder'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'DeprecatedBuiltInAPICheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: '', +}; + +enum APIBaseCategory { + Array = 'Array', + Set = 'Set', + Map = 'Map', +} + +class DeprecatedAPIInfo { + constructor( + public base: APIBaseCategory, + public name: string, + public isStatic: boolean, + public returnType?: Type, // return Type为undefined时表示不关心API的返回值 + public params?: Type[], // return Type为undefined时表示不关心API的形参,应该是整个API都被废弃,而非某一重载形态 + public targetParamIndex?: number // 若isStatic为tue,说明是静态接口,需要提供查找接口的第几个param是否来源arkts1.2,编号从0开始,不提供则查找base的来源 + ) {} +} + +class APIBasicType { + static readonly genericTypeT = new GenericType('T'); + static readonly genericTypeU = new GenericType('U'); + static readonly genericTypeV = new GenericType('V'); + static readonly genericTypeK = new GenericType('K'); + static readonly genericTypeS = new GenericType('S'); + static readonly arrayT = new ArrayType(this.genericTypeT, 1); + static readonly arrayU = new ArrayType(this.genericTypeU, 1); + static readonly unknownType = UnknownType.getInstance(); + static readonly numberType = NumberType.getInstance(); + static readonly booleanType = BooleanType.getInstance(); + static readonly anyType = AnyType.getInstance(); + static readonly undefinedType = UndefinedType.getInstance(); + static readonly voidType = VoidType.getInstance(); +} + +class APIComplicatedType { + static readonly anonyMethodName = 'anonymous'; + static readonly predicateFunctionType = this.createPredicateFunctionType(); + static readonly predicateFunction1Type = this.createPredicateFunction1Type(); + static readonly concatItemType = this.createConcatItemType(); + static readonly mapfnFunctionType = this.createMapfnFunctionType(); + static readonly ArrayLikeType = new ClassType(new ClassSignature('ArrayLike', FileSignature.DEFAULT)); + static readonly IterableType = new ClassType(new ClassSignature('Iterable', FileSignature.DEFAULT)); + static readonly SetType = new ClassType(new ClassSignature('Set', FileSignature.DEFAULT)); + static readonly MapType = new ClassType(new ClassSignature('Map', FileSignature.DEFAULT)); + static readonly setCallbackFnFunctionType = this.createSetCallbackFnFunctionType(); + static readonly mapCallbackFnFunctionType = this.createMapCallbackFnFunctionType(); + + // 对于参数类型一致,但是参数名称不同、返回值类型不同的FunctionType,视为同一个,不重新创建。因为FunctionType类型匹配的时候仅匹配参数类型 + // 不同的API,仅形参为lambda函数且该lambda函数的返回值不同,例如unknown和value is S类型谓词形式,视为同一个API + private static createPredicateFunctionType(): FunctionType { + const predicateValueParam = new MethodParameter(); + predicateValueParam.setName('value'); + predicateValueParam.setType(APIBasicType.genericTypeT); + const predicateIndexParam = new MethodParameter(); + predicateIndexParam.setName('index'); + predicateIndexParam.setType(APIBasicType.numberType); + const predicateArrayParam = new MethodParameter(); + predicateArrayParam.setName('array'); + predicateArrayParam.setType(APIBasicType.arrayT); + const predicateMethodSubSignature = new MethodSubSignature( + this.anonyMethodName, + [predicateValueParam, predicateIndexParam, predicateArrayParam], + APIBasicType.unknownType + ); + return new FunctionType(new MethodSignature(ClassSignature.DEFAULT, predicateMethodSubSignature)); + } + + private static createPredicateFunction1Type(): FunctionType { + const predicateThisParam = new MethodParameter(); + predicateThisParam.setName('this'); + predicateThisParam.setType(APIBasicType.voidType); + const predicateValueParam = new MethodParameter(); + predicateValueParam.setName('value'); + predicateValueParam.setType(APIBasicType.genericTypeT); + const predicateIndexParam = new MethodParameter(); + predicateIndexParam.setName('index'); + predicateIndexParam.setType(APIBasicType.numberType); + const predicateObjParam = new MethodParameter(); + predicateObjParam.setName('obj'); + predicateObjParam.setType(APIBasicType.arrayT); + const predicateMethodSubSignature = new MethodSubSignature( + this.anonyMethodName, + [predicateThisParam, predicateValueParam, predicateIndexParam, predicateObjParam], + APIBasicType.booleanType + ); + return new FunctionType(new MethodSignature(ClassSignature.DEFAULT, predicateMethodSubSignature)); + } + + private static createConcatItemType(): UnionType { + return new UnionType([APIBasicType.genericTypeT, new ClassType(new ClassSignature('ConcatArray', FileSignature.DEFAULT))]); + } + + private static createMapfnFunctionType(): FunctionType { + const mapfnParamV = new MethodParameter(); + mapfnParamV.setName('v'); + mapfnParamV.setType(APIBasicType.genericTypeT); + const mapfnParamK = new MethodParameter(); + mapfnParamK.setName('k'); + mapfnParamK.setType(APIBasicType.numberType); + const mapfnMethodSubSignature = new MethodSubSignature(this.anonyMethodName, [mapfnParamV, mapfnParamK], APIBasicType.genericTypeU); + return new FunctionType(new MethodSignature(ClassSignature.DEFAULT, mapfnMethodSubSignature)); + } + + private static createSetCallbackFnFunctionType(): FunctionType { + const callbackFnValueParam = new MethodParameter(); + callbackFnValueParam.setName('value'); + callbackFnValueParam.setType(APIBasicType.genericTypeT); + const callbackFnValue2Param = new MethodParameter(); + callbackFnValue2Param.setName('value2'); + callbackFnValue2Param.setType(APIBasicType.genericTypeT); + const callbackFnSetParam = new MethodParameter(); + callbackFnSetParam.setName('set'); + callbackFnSetParam.setType(this.SetType); + const predicateMethodSubSignature = new MethodSubSignature( + this.anonyMethodName, + [callbackFnValueParam, callbackFnValue2Param, callbackFnSetParam], + APIBasicType.voidType + ); + return new FunctionType(new MethodSignature(ClassSignature.DEFAULT, predicateMethodSubSignature)); + } + + private static createMapCallbackFnFunctionType(): FunctionType { + const callbackFnValueParam = new MethodParameter(); + callbackFnValueParam.setName('value'); + callbackFnValueParam.setType(APIBasicType.genericTypeV); + const callbackFnKeyParam = new MethodParameter(); + callbackFnKeyParam.setName('key'); + callbackFnKeyParam.setType(APIBasicType.genericTypeK); + const callbackFnMapParam = new MethodParameter(); + callbackFnMapParam.setName('map'); + callbackFnMapParam.setType(this.MapType); + const predicateMethodSubSignature = new MethodSubSignature( + this.anonyMethodName, + [callbackFnValueParam, callbackFnKeyParam, callbackFnMapParam], + APIBasicType.voidType + ); + return new FunctionType(new MethodSignature(ClassSignature.DEFAULT, predicateMethodSubSignature)); + } +} + +class DeprecatedAPIList { + static readonly DeprecatedAPIs: DeprecatedAPIInfo[] = [ + this.createArrayEveryAPI1(), + this.createArrayFilterAPI1(), + this.createArrayFindAPI1(), + this.createArrayFindAPI2(), + this.createArrayFindIndexAPI(), + this.createArrayForEachAPI(), + this.createArrayMapAPI(), + this.createArraySomeAPI(), + this.createArrayConcatAPI(), + this.createArrayFlatAPI(), + this.createArrayFlatMapAPI(), + this.createArrayFromArrayLikeAPI(), + this.createArrayFromIterableAndArrayLikeAPI(), + this.createSetForEachAPI(), + this.createMapForEachAPI(), + this.createArraySymbolIteratorAPI(), + this.createSetSymbolIteratorAPI(), + this.createMapSymbolIteratorAPI() + ]; + + private static createArrayEveryAPI1(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'every', false, APIBasicType.booleanType, [ + APIComplicatedType.predicateFunctionType, + APIBasicType.anyType, + ]); + } + + private static createArrayFilterAPI1(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'filter', false, APIBasicType.arrayT, [ + APIComplicatedType.predicateFunctionType, + APIBasicType.anyType, + ]); + } + + private static createArrayFindAPI1(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'find', false, new UnionType([APIBasicType.genericTypeT, APIBasicType.undefinedType]), [ + APIComplicatedType.predicateFunctionType, + APIBasicType.anyType, + ]); + } + + private static createArrayFindAPI2(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'find', false, new UnionType([APIBasicType.genericTypeS, APIBasicType.undefinedType]), [ + APIComplicatedType.predicateFunction1Type, + APIBasicType.anyType, + ]); + } + + private static createArrayFindIndexAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'findIndex', false, APIBasicType.numberType, [ + APIComplicatedType.predicateFunctionType, + APIBasicType.anyType, + ]); + } + + private static createArrayForEachAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'forEach', false, APIBasicType.voidType, [ + APIComplicatedType.predicateFunctionType, + APIBasicType.anyType, + ]); + } + + private static createArrayMapAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'map', false, APIBasicType.arrayU, [ + APIComplicatedType.predicateFunctionType, + APIBasicType.anyType, + ]); + } + + private static createArraySomeAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'some', false, APIBasicType.booleanType, [ + APIComplicatedType.predicateFunctionType, + APIBasicType.anyType, + ]); + } + + private static createArrayConcatAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'concat', false, APIBasicType.arrayT, [new ArrayType(APIComplicatedType.concatItemType, 1)]); + } + + private static createArrayFlatAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'flat', false); + } + + private static createArrayFlatMapAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'flatMap', false); + } + + private static createArrayFromArrayLikeAPI(): DeprecatedAPIInfo { + const fromParams = [APIComplicatedType.ArrayLikeType, APIComplicatedType.mapfnFunctionType, APIBasicType.anyType]; + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'from', true, APIBasicType.arrayU, fromParams, 0); + } + + private static createArrayFromIterableAndArrayLikeAPI(): DeprecatedAPIInfo { + const fromParams = [ + new UnionType([APIComplicatedType.ArrayLikeType, APIComplicatedType.IterableType]), + APIComplicatedType.mapfnFunctionType, + APIBasicType.anyType, + ]; + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'from', true, APIBasicType.arrayU, fromParams, 0); + } + + private static createSetForEachAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Set, 'forEach', false, APIBasicType.voidType, [ + APIComplicatedType.setCallbackFnFunctionType, + APIBasicType.anyType, + ]); + } + + private static createMapForEachAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Map, 'forEach', false, APIBasicType.voidType, [ + APIComplicatedType.mapCallbackFnFunctionType, + APIBasicType.anyType, + ]); + } + + private static createArraySymbolIteratorAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Array, 'Symbol.iterator', false); + } + + private static createSetSymbolIteratorAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Set, 'Symbol.iterator', false); + } + + private static createMapSymbolIteratorAPI(): DeprecatedAPIInfo { + return new DeprecatedAPIInfo(APIBaseCategory.Map, 'Symbol.iterator', false); + } +} + +export class InteropDeprecatedBuiltInAPICheck 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 scene: Scene; + private visited: Set = new Set(); + + public registerMatchers(): MatcherCallback[] { + const matchBuildCb: MatcherCallback = { + matcher: undefined, + callback: this.check, + }; + return [matchBuildCb]; + } + + public check = (scene: Scene): void => { + this.scene = scene; + 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进行检查 + if (!(arkFile.getLanguage() === Language.ARKTS1_1)) { + continue; + } + const defaultMethod = arkFile.getDefaultClass().getDefaultArkMethod(); + let globalVarMap: Map = new Map(); + if (defaultMethod) { + this.dvfgBuilder.buildForSingleMethod(defaultMethod); + globalVarMap = getGlobalsDefineInDefaultMethod(defaultMethod); + } + for (let arkClass of arkFile.getClasses()) { + this.processArkClass(arkClass, globalVarMap); + } + for (let namespace of arkFile.getAllNamespacesUnderThisFile()) { + this.processNameSpace(namespace, globalVarMap); + } + } + }; + + public processArkClass(arkClass: ArkClass, globalVarMap: Map): void { + for (let field of arkClass.getFields()) { + this.processClassField(field, globalVarMap); + } + for (let mtd of arkClass.getMethods()) { + this.processArkMethod(mtd, globalVarMap); + } + } + + public processNameSpace(namespace: ArkNamespace, globalVarMap: Map): void { + for (let ns of namespace.getNamespaces()) { + this.processNameSpace(ns, globalVarMap); + } + for (let arkClass of namespace.getClasses()) { + this.processArkClass(arkClass, globalVarMap); + } + } + + public processClassField(field: ArkField, globalVarMap: Map): void { + const stmts = field.getInitializer(); + for (const stmt of stmts) { + const invokeExpr = this.getInvokeExpr(stmt); + if (invokeExpr === null) { + continue; + } + } + } + + public processArkMethod(target: ArkMethod, globalVarMap: Map): void { + const stmts = target.getBody()?.getCfg().getStmts() ?? []; + for (const stmt of stmts) { + // 查找到DeprecatedAPIs中的builtIn的API调用语句为sink点,从该点开始进行逆向数据流分析,分析base是否为arkts1.2中声明的对象实例或其引用 + const targetLocal = this.getTargetLocalOfDeprecatedAPICall(stmt); + if (targetLocal === null) { + continue; + } + + // 从base的最近一次赋值语句开始,使用逆向数据流进行查找 + let checkStmt = this.getLastAssignStmt(targetLocal, stmt); + if (checkStmt === null) { + checkStmt = this.checkTargetLocalAsGlobal(target, stmt, targetLocal, globalVarMap); + } + if (checkStmt === null) { + continue; + } + + if (!this.visited.has(target)) { + this.dvfgBuilder.buildForSingleMethod(target); + this.visited.add(target); + } + + let checkAll = { value: true }; + let visited: Set = new Set(); + if (this.checkFromStmt(checkStmt, globalVarMap, checkAll, visited)) { + this.addIssueReport(stmt, targetLocal); + } + } + } + + private checkTargetLocalAsGlobal(targetMethod: ArkMethod, stmt: Stmt, targetLocal: Local, globalVarMap: Map): Stmt | null { + const globalDefs = globalVarMap.get(targetLocal.getName()); + if (globalDefs === undefined) { + const importInfos = targetMethod.getDeclaringArkClass().getDeclaringArkFile().getImportInfos(); + const importValue = this.isLocalFromImport(targetLocal, importInfos); + if (importValue && importValue.getDeclaringStmt() !== null) { + return importValue.getDeclaringStmt()!; + } + return null; + } + let lastLegalStmtLine = -1; + let lastIllegalStmtLine = -1; + for (const defStmt of globalDefs) { + if (!this.visited.has(targetMethod)) { + this.dvfgBuilder.buildForSingleMethod(targetMethod); + this.visited.add(targetMethod); + } + + let checkAll = { value: true }; + let visited: Set = new Set(); + + const currStmtLine = defStmt.getOriginPositionInfo().getLineNo(); + if (this.checkFromStmt(defStmt, globalVarMap, checkAll, visited)) { + if (currStmtLine > lastIllegalStmtLine) { + lastIllegalStmtLine = currStmtLine; + } + } else { + if (currStmtLine > lastLegalStmtLine) { + lastLegalStmtLine = currStmtLine; + } + } + } + if (lastIllegalStmtLine > lastLegalStmtLine) { + this.addIssueReport(stmt, targetLocal); + } + return null; + } + + private getLastAssignStmt(local: Local, currStmt: Stmt): Stmt | null { + // 获取local变量在currStmt使用语句之前的最近一次赋值/声明语句,未找到表示直接来自于全局变量或import信息,则返回null + const usedStmts = local.getUsedStmts(); + let currLine = currStmt.getOriginPositionInfo().getLineNo(); + let lastAssignStmt = local.getDeclaringStmt(); + for (const stmt of usedStmts) { + if (stmt === currStmt || !(stmt instanceof ArkAssignStmt) || stmt.getLeftOp() !== local) { + continue; + } + const line = stmt.getOriginPositionInfo().getLineNo(); + if (line < currLine) { + lastAssignStmt = stmt; + currLine = line; + } + } + return lastAssignStmt; + } + + private isLocalDefinedInStaticArkTS(local: Local): boolean { + return local.getDeclaringStmt()?.getCfg().getDeclaringMethod().getLanguage() === Language.ARKTS1_2; + } + + // 判断语句是否为废弃API接口的调用语句,若废弃接口仅为一系列重载中的某一种,需要判断这一具体重载形态,若是返回对应需要查找的Local对象,否则返回null + private getTargetLocalOfDeprecatedAPICall(stmt: Stmt): Local | null { + const invokeExpr = this.getInvokeExpr(stmt); + if (invokeExpr === null) { + return null; + } + if (invokeExpr instanceof ArkInstanceInvokeExpr) { + const base = invokeExpr.getBase(); + if (this.isInstanceCallMethodInDeprecatedAPIs(base, stmt, invokeExpr.getMethodSignature(), invokeExpr.getArgs())) { + return base; + } + // instance invoke未匹配到,继续匹配静态调用。Array.from的API调用ArkAnalyzer也表示为ArkInstanceInvokeExpr,因为API定义里没有明确的static标识。 + return this.getTargetValueInStaticInvokeWithDeprecatedAPIs(invokeExpr); + } else if (invokeExpr instanceof ArkPtrInvokeExpr) { + // TODO:可能存在ptr invoke的场景吗? + return null; + } else if (invokeExpr instanceof ArkStaticInvokeExpr) { + return null; + } + return null; + } + + private getInvokeExpr(stmt: Stmt): AbstractInvokeExpr | null { + if (!(stmt instanceof ArkAssignStmt) && !(stmt instanceof ArkInvokeStmt)) { + return null; + } + + if (stmt instanceof ArkInvokeStmt) { + return stmt.getInvokeExpr(); + } + + const rightOp = stmt.getRightOp(); + if (rightOp instanceof AbstractInvokeExpr) { + return rightOp; + } + return null; + } + + private compareParamTypes(apiParams: Type[], callApiParams: MethodParameter[]): boolean { + if (apiParams.length !== callApiParams.length) { + return false; + } + for (let i = 0; i < apiParams.length; i++) { + if (!this.isTypeMatch(apiParams[i], callApiParams[i].getType())) { + return false; + } + } + return true; + } + + private getTargetValueInStaticInvokeWithDeprecatedAPIs(staticInvokeExpr: ArkStaticInvokeExpr): Local | null { + const callApiMethod = staticInvokeExpr.getMethodSignature(); + const callApiClass = callApiMethod.getDeclaringClassSignature(); + for (const api of DeprecatedAPIList.DeprecatedAPIs) { + if (!api.isStatic) { + continue; + } + if (api.name !== callApiMethod.getMethodSubSignature().getMethodName()) { + continue; + } + // Array.from 形式的调用,from方法实际的class为ArrayConstructor + if (api.base !== callApiClass.getClassName() && `${api.base}Constructor` !== callApiClass.getClassName()) { + continue; + } + // 在本条规则检查范围内的static API的调用一定是带参数的,并且其中某个参数即为需要进行进一步查找的value + if (api.params === undefined) { + continue; + } + if (this.compareParamTypes(api.params, callApiMethod.getMethodSubSignature().getParameters())) { + const args = staticInvokeExpr.getArgs(); + // 形参匹配的情况下,进一步比较传入的实参,因为当前废弃接口大多数为去掉any类型的第二个可选参数 + // TODO:这里需要考虑如何做的更通用 + if (args.length !== api.params.length) { + continue; + } + const index = api.targetParamIndex; + // 成功匹配到指定的API后,如果未提供下一步需要查找的目标param的index,则返回null。理论上不应该走到这个分支。 + if (index === undefined) { + logger.error(`Missing targetParamIndex, api: ${api.name}, category ${api.base}`); + return null; + } + + if (args.length <= index) { + logger.error(`Invalid targetParamIndex ${index}, totally invoke args size ${args.length}, api: ${api.name}, category ${api.base}`); + return null; + } + const target = args[index]; + if (target instanceof Local) { + return target; + } + logger.error(`Need to handle non-local target ${target.getType().getTypeString()}`); + return null; + } + } + return null; + } + + private isMatchSymbolIterator(apiName: string, callApiName: string, stmt: Stmt): boolean { + // 对于map[Symbol.iterator]这样的API,这里会存在%0 = Symbol.iterator的操作 + if (apiName !== 'Symbol.iterator' || !callApiName.startsWith('%')) { + return false; + } + const tempLocalDeclaring = stmt.getCfg().getDeclaringMethod().getBody()?.getLocals().get(callApiName)?.getDeclaringStmt(); + if (tempLocalDeclaring && tempLocalDeclaring instanceof ArkAssignStmt) { + const rightOp = tempLocalDeclaring.getRightOp(); + if (!(rightOp instanceof ArkInstanceFieldRef)) { + return false; + } + if (rightOp.getFieldName() === 'iterator' && rightOp.getBase().getName() === 'Symbol') { + return true; + } + } + return false; + } + + private isInstanceCallMethodInDeprecatedAPIs(callBase: Local, stmt: Stmt, callMethod: MethodSignature, args: Value[]): boolean { + const callApiName = callMethod.getMethodSubSignature().getMethodName(); + const callApiParams = callMethod.getMethodSubSignature().getParameters(); + for (const api of DeprecatedAPIList.DeprecatedAPIs) { + // 对于map[Symbol.iterator]这样的API调用,callApiName是临时变量,需要进一步匹配 + if (api.name !== callApiName) { + continue; + } + if (api.isStatic) { + continue; + } + if (!this.isBaseTypeMatchAPIBase(api.base, callBase)) { + continue; + } + + // Array concat API ArkAnalyzer当前无法很好处理...items形式的入参,此处作为特例处理 + if (api.name === 'concat') { + return this.isMatchArrayConcatAPI(args); + } + + const apiParams = api.params; + if (apiParams === undefined) { + return true; + } + let allParamTypeMatch = true; + if (apiParams.length !== callApiParams.length) { + allParamTypeMatch = false; + } else { + for (let i = 0; i < apiParams.length; i++) { + if (!this.isTypeMatch(apiParams[i], callApiParams[i].getType())) { + allParamTypeMatch = false; + break; + } + } + } + + if (allParamTypeMatch) { + // 形参匹配的情况下,进一步比较传入的实参,因为当前废弃接口大多数为去掉any类型的第二个可选参数 + // TODO:这里需要考虑如何做的更通用 + if (args.length !== apiParams.length) { + continue; + } + return true; + } + // 形参类型不匹配的情形,可能是由于ArkAnalyzer的类型推导未能找到正确的API,需要根据实参类型进行二次匹配 + if (apiParams.length !== args.length) { + continue; + } + allParamTypeMatch = true; + for (let i = 0; i < apiParams.length; i++) { + // 对于lambda函数作为参数类型,此处不严格校验lambda的参数类型,仅判断是否为FunctionType + if (apiParams[i] instanceof FunctionType && args[i].getType() instanceof FunctionType) { + continue; + } + if (!this.isTypeMatch(apiParams[i], args[i].getType())) { + allParamTypeMatch = false; + break; + } + } + if (allParamTypeMatch) { + return true; + } + } + return false; + } + + // 判断入参是否都为数组,不允许有单个元素 + private isMatchArrayConcatAPI(args: Value[]): boolean { + for (const arg of args) { + if (!(arg.getType() instanceof ArrayType)) { + return true; + } + } + return false; + } + + private isTypeMatch(apiType: Type, callApiType: Type): boolean { + const apiTypeStr = apiType.getTypeString(); + const callApiTypeStr = callApiType.getTypeString(); + if (callApiType instanceof FunctionType && apiType instanceof FunctionType) { + // 若类型为FunctionType,仅需匹配string中的形参部分 + const regex = /\(([^()]*)\)/; + const apiMatch = apiTypeStr.match(regex); + const callApiMatch = callApiTypeStr.match(regex); + if (apiMatch === null || callApiMatch === null) { + return false; + } + return apiMatch[0] === callApiMatch[0]; + } else if (callApiType instanceof ClassType && apiType instanceof ClassType) { + // 若类型为FunctionType,仅需匹配class name,因为apiTypeStr类型推导后有可能为@%unk/%unk: ArrayLike,而callApiTypeStr有明确的declaring file + return callApiType.getClassSignature().getClassName() === apiType.getClassSignature().getClassName(); + } else if (apiType instanceof AnyType) { + return true; + } else { + // 其他场景需严格判断字符串相等 + return apiTypeStr === callApiTypeStr; + } + } + + private isBaseTypeMatchAPIBase(apiBase: APIBaseCategory, callBase: Local): boolean { + if (apiBase === APIBaseCategory.Array && callBase.getType() instanceof ArrayType) { + return true; + } + if (apiBase === APIBaseCategory.Map) { + const callBaseType = callBase.getType(); + return callBaseType instanceof ClassType && callBaseType.getClassSignature().getClassName() === 'Map'; + } + if (apiBase === APIBaseCategory.Set) { + const callBaseType = callBase.getType(); + return callBaseType instanceof ClassType && callBaseType.getClassSignature().getClassName() === 'Set'; + } + return false; + } + + private checkFromStmt(stmt: Stmt, globalVarMap: Map, checkAll: { value: boolean }, visited: Set, depth: number = 0): boolean { + if (depth > CALL_DEPTH_LIMIT) { + checkAll.value = false; + return false; + } + 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.isLeftOpDefinedInStaticArkTS(currentStmt)) { + return true; + } + + const gv = this.isRightOpGlobalVar(currentStmt); + if (gv) { + const globalDefs = globalVarMap.get(gv.getName()); + if (globalDefs === undefined) { + const importInfos = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile().getImportInfos(); + const importValue = this.isLocalFromImport(gv, importInfos); + 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, globalVarMap, checkAll, visited, depth + 1); + if (res) { + return true; + } + } + } + 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, globalVarMap, checkAll, visited, depth + 1); + if (res) { + return true; + } + } + } + current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); + } + return false; + } + + private isRightOpGlobalVar(stmt: Stmt): Local | undefined { + if (stmt instanceof ArkAssignStmt) { + const rightOp = stmt.getRightOp(); + if (rightOp instanceof Local && !rightOp.getDeclaringStmt()) { + return rightOp; + } + } + return undefined; + } + + private isLocalFromImport(local: Local, importInfos: ImportInfo[]): Local | undefined { + for (const importInfo of importInfos) { + if (importInfo.getImportClauseName() === local.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); + } + }); + } + + // 判断语句是否为赋值语句,且左值的定义来自于ArkTS1.2 + private isLeftOpDefinedInStaticArkTS(stmt: Stmt): boolean { + if (!(stmt instanceof ArkAssignStmt)) { + return false; + } + const leftOp = stmt.getLeftOp(); + if (!(leftOp instanceof Local)) { + return false; + } + return this.isLocalDefinedInStaticArkTS(leftOp); + } + + 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)); + let refs = Array.from(this.dvfg.getOrNewDVFGNode(callsite).getIncomingEdge()) + .map(e => (e.getSrcNode() as DVFGNode).getStmt()) + .filter(s => { + return s instanceof ArkAssignStmt && target === getKey(s.getLeftOp()); + }); + // 以上步骤未找到defs语句,说明入参变量来源自import信息 + if (refs.length === 0 && target instanceof Local) { + const importInfos = callsite.getCfg().getDeclaringMethod().getDeclaringArkFile().getImportInfos(); + const importValue = this.isLocalFromImport(target, importInfos); + if (importValue && importValue.getDeclaringStmt() !== null) { + return importValue.getDeclaringStmt()!; + } + } + return refs; + }); + } + + private addIssueReport(stmt: Stmt, operand: Value): void { + const severity = this.rule.alert ?? this.metaData.severity; + const warnInfo = this.getLineAndColumn(stmt, operand); + const problem = 'builtin-api'; + const desc = `Builtin API is not support in ArkTS1.2 (${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): 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/InteropJSModifyPropertyCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropJSModifyPropertyCheck.ts index 3b912361f2..16ea7584bc 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/InteropJSModifyPropertyCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropJSModifyPropertyCheck.ts @@ -276,10 +276,8 @@ export class InteropJSModifyPropertyCheck implements BaseChecker { } if (file) { return file.getLanguage(); - } else { - logger.error(`fail to identify which file the type definition ${type.toString()} is in.`); - return Language.UNKNOWN; } + return Language.UNKNOWN; } private reportIssue(problemStmt: Stmt) { @@ -289,7 +287,7 @@ export class InteropJSModifyPropertyCheck implements BaseChecker { 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 filePath = problemStmt.getCfg().getDeclaringMethod().getDeclaringArkFile()?.getFilePath() ?? ''; const defeats = new Defects( line, column, diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropS2DObjectLiteralsCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropS2DObjectLiteralsCheck.ts new file mode 100644 index 0000000000..79c14788bd --- /dev/null +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropS2DObjectLiteralsCheck.ts @@ -0,0 +1,347 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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, + Stmt, + Scene, + Value, + ArkInstanceFieldRef, + ClassType, + ArkInvokeStmt, + AbstractInvokeExpr, + ArkField, + ArkReturnStmt, +} from 'arkanalyzer/lib'; +import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; +import { BaseChecker, BaseMetaData } from '../BaseChecker'; +import { Rule, Defects, MatcherCallback, MatcherTypes, MethodMatcher } from '../../Index'; +import { IssueReport } from '../../model/Defects'; +import { ArkClass, ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; +import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; +import { getLanguageStr, getLineAndColumn } from './Utils'; + +const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'InteropS2DObjectLiteralCheck'); +const gMetaData: BaseMetaData = { + severity: 1, + ruleDocPath: '', + description: '', +}; + +const s2dRuleId: string = 'arkts-interop-s2d-object-literal'; + +type IssueData = { + stmt: Stmt; + value: Value; +}; + +export class InteropS2DObjectLiteralCheck implements BaseChecker { + private scene: Scene; + readonly metaData: BaseMetaData = gMetaData; + public rule: Rule; + public defects: Defects[] = []; + public issues: IssueReport[] = []; + + private methodMatcher: MethodMatcher = { + matcherType: MatcherTypes.METHOD, + }; + + public registerMatchers(): MatcherCallback[] { + const methodMatcher: MatcherCallback = { + matcher: this.methodMatcher, + callback: this.check, + }; + return [methodMatcher]; + } + + public check = (arkMethod: ArkMethod): void => { + this.scene = arkMethod.getDeclaringArkFile().getScene(); + + if (arkMethod.getLanguage() !== Language.ARKTS1_1) { + return; + } + // 检测的sink点为赋值语句,且左值的类型注解明确为1.2的class或者包含1.2的class的更复杂数据结构 + const stmts = arkMethod.getBody()?.getCfg().getStmts() ?? []; + // 检查所有语句 + // 1. 对于赋值语句,检查左边是否为arkts1.2的class类型或某个field为arkts1.2的class类型,右边对象或对应属性是否用arkts1.1的object litral赋值 + // 2. 对于函数调用,可能为invoke语句或赋值语句的右值为invoke表达式,检查入参是否存在如上的情况 + for (const stmt of stmts) { + if (stmt instanceof ArkAssignStmt) { + this.checkAssignWithObjectLiteral(stmt, arkMethod); + if (stmt.getRightOp() instanceof AbstractInvokeExpr) { + this.checkInvokeWithObjectLiteral(stmt, arkMethod); + } + } else if (stmt instanceof ArkInvokeStmt) { + this.checkInvokeWithObjectLiteral(stmt, arkMethod); + } + } + // 检查函数的返回值,若函数签名中返回类型声明是否为arkts1.2的class类型或某个field为arkts1.2的class类型,且实际返回对象或对应属性是否为arkts1.1的object litral + this.checkReturnWithObjectLiteral(arkMethod); + }; + + private getClassWithType(checkType: ClassType): ArkClass | null { + return this.scene.getClass(checkType.getClassSignature()); + } + + private isClassFromEtsStatic(clazz: ArkClass): boolean { + return clazz.getLanguage() === Language.ARKTS1_2 && clazz.getCategory() !== ClassCategory.OBJECT; + } + + private isObjectLiteralFromEtsDynamic(clazz: ArkClass): boolean { + return clazz.getLanguage() === Language.ARKTS1_1 && clazz.getCategory() === ClassCategory.OBJECT; + } + + private checkAssignWithObjectLiteral(stmt: ArkAssignStmt, target: ArkMethod): void { + const leftOpType = stmt.getLeftOp().getType(); + if (!(leftOpType instanceof ClassType)) { + return; + } + const leftTypeClass = this.getClassWithType(leftOpType); + if (leftTypeClass === null) { + logger.debug(`Failed to find class of type ${leftOpType.toString()}`); + return; + } + if (this.isClassFromEtsStatic(leftTypeClass)) { + const rightOpType = stmt.getRightOp().getType(); + if (!(rightOpType instanceof ClassType)) { + return; + } + const rightTypeClass = this.getClassWithType(rightOpType); + if (rightTypeClass === null) { + logger.debug(`Failed to find class of type ${rightOpType.toString()}`); + return; + } + if (this.isObjectLiteralFromEtsDynamic(rightTypeClass)) { + this.addIssueReport(stmt, stmt.getRightOp()); + return; + } + } + let results: IssueData[] = []; + this.checkAllClassFieldWithValue(stmt, stmt.getRightOp(), leftTypeClass, results); + for (const result of results) { + this.addIssueReport(result.stmt, result.value); + } + } + + private checkInvokeWithObjectLiteral(stmt: ArkInvokeStmt | ArkAssignStmt, target: ArkMethod): void { + let invokeExpr: AbstractInvokeExpr; + if (stmt instanceof ArkInvokeStmt) { + invokeExpr = stmt.getInvokeExpr(); + } else { + const rightOp = stmt.getRightOp(); + if (!(rightOp instanceof AbstractInvokeExpr)) { + return; + } + invokeExpr = rightOp; + } + const method = this.scene.getMethod(invokeExpr.getMethodSignature()); + if (method === null) { + logger.debug(`Failed to find method in invoke expr, method: ${invokeExpr.getMethodSignature().toString()}`); + return; + } + for (const [index, param] of method.getParameters().entries()) { + const paramType = param.getType(); + if (!(paramType instanceof ClassType)) { + continue; + } + const paramTypeClass = this.getClassWithType(paramType); + if (paramTypeClass === null) { + logger.debug(`Failed to find class of method param type ${paramType.toString()}, method: ${method.getSignature().toString()}`); + continue; + } + if (index >= invokeExpr.getArgs().length) { + logger.debug(`Failed to find param with index ${index} of method: ${method.getSignature().toString()}`); + continue; + } + const arg = invokeExpr.getArg(index); + if (this.isClassFromEtsStatic(paramTypeClass)) { + const argType = arg.getType(); + if (!(argType instanceof ClassType)) { + continue; + } + const argTypeClass = this.getClassWithType(argType); + if (argTypeClass === null) { + logger.debug(`Failed to find class of invoke arg type ${argType.toString()}, method: ${method.getSignature().toString()}`); + continue; + } + if (this.isObjectLiteralFromEtsDynamic(argTypeClass)) { + this.addIssueReport(stmt, arg); + return; + } + } + let results: IssueData[] = []; + this.checkAllClassFieldWithValue(stmt, arg, paramTypeClass, results); + for (const result of results) { + this.addIssueReport(result.stmt, result.value); + } + } + } + + private checkReturnWithObjectLiteral(target: ArkMethod): void { + // 构造函数的返回值一定是当前class本身,其各field和method已在其他地方进行检查,这里无需检查构造函数的返回值 + if (target.getName() === 'constructor') { + return; + } + const returnType = target.getReturnType(); + if (!(returnType instanceof ClassType)) { + return; + } + const returnTypeClass = this.getClassWithType(returnType); + if (returnTypeClass === null) { + logger.debug(`Failed to find method of return type ${returnType.toString()}, method ${target.getSignature().toString()}`); + return; + } + const returnStmts = target.getReturnStmt(); + if (this.isClassFromEtsStatic(returnTypeClass)) { + for (const returnStmt of returnStmts) { + if (!(returnStmt instanceof ArkReturnStmt)) { + continue; + } + const valueType = returnStmt.getOp().getType(); + if (!(valueType instanceof ClassType)) { + continue; + } + const valueTypeClass = this.getClassWithType(valueType); + if (valueTypeClass === null) { + logger.debug(`Failed to find method of return value type ${valueType.toString()}, method ${target.getSignature().toString()}`); + continue; + } + if (this.isObjectLiteralFromEtsDynamic(valueTypeClass)) { + this.addIssueReport(returnStmt, returnStmt.getOp()); + } + } + return; + } + + for (const returnStmt of returnStmts) { + if (!(returnStmt instanceof ArkReturnStmt)) { + continue; + } + let results: IssueData[] = []; + this.checkAllClassFieldWithValue(returnStmt, returnStmt.getOp(), returnTypeClass, results); + if (results.length > 0) { + this.addIssueReport(returnStmt, returnStmt.getOp()); + } + } + } + + private checkAllClassFieldWithValue(sinkStmt: Stmt, val: Value, needCheckClass: ArkClass, result: IssueData[], checkedTypes?: Set): void { + let visited: Set = checkedTypes ?? new Set(); + if (visited.has(needCheckClass.getSignature().toString())) { + return; + } + visited.add(needCheckClass.getSignature().toString()); + for (const field of needCheckClass.getFields()) { + const fieldType = field.getType(); + if (!(fieldType instanceof ClassType)) { + continue; + } + const fieldTypeClass = this.getClassWithType(fieldType); + if (fieldTypeClass === null) { + logger.debug( + `Failed to find class of type ${fieldType.toString()} of field: ${field.getName()}, class ${needCheckClass.getSignature().toString()}}` + ); + continue; + } + const fieldInitializers = this.getFieldInitializersWithValue(field, val); + const fieldAssignStmt = this.getFieldAssignStmtInInitializers(field, fieldInitializers); + if (fieldAssignStmt === null) { + continue; + } + if (this.isClassFromEtsStatic(fieldTypeClass)) { + const rightOpType = fieldAssignStmt.getRightOp().getType(); + if (!(rightOpType instanceof ClassType)) { + continue; + } + const rightOpTypeClass = this.getClassWithType(rightOpType); + if (rightOpTypeClass === null) { + logger.debug( + `Failed to find class of type ${rightOpType.toString()} of field initializer, field: ${field.getName()}, class ${needCheckClass.getSignature().toString()}}` + ); + continue; + } + if (this.isObjectLiteralFromEtsDynamic(rightOpTypeClass)) { + result.push({ stmt: sinkStmt, value: val }); + continue; + } + continue; + } + this.checkAllClassFieldWithValue(fieldAssignStmt, fieldAssignStmt.getRightOp(), fieldTypeClass, result, visited); + } + } + + private getFieldAssignStmtInInitializers(field: ArkField, fieldInitializers: Stmt[]): ArkAssignStmt | null { + for (const stmt of fieldInitializers) { + if (!(stmt instanceof ArkAssignStmt)) { + continue; + } + const leftOp = stmt.getLeftOp(); + if (!(leftOp instanceof ArkInstanceFieldRef)) { + continue; + } + if (leftOp.getFieldName() === field.getName()) { + return stmt; + } + } + return null; + } + + // 对于object literal(主要是多层嵌套场景),根据需要查找的field的名字,获取其对应的内部嵌套class的初始化语句 + private getFieldInitializersWithValue(leftField: ArkField, val: Value): Stmt[] { + const res: Stmt[] = []; + const rightOpType = val.getType(); + if (!(rightOpType instanceof ClassType)) { + return res; + } + const rightOpTypeClass = this.getClassWithType(rightOpType); + if (rightOpTypeClass === null) { + logger.debug(`Failed to find class of type ${rightOpType.toString()} of field: ${leftField.getSignature().toString()}`); + return res; + } + for (const field of rightOpTypeClass.getFields()) { + if (field.getName() === leftField.getName()) { + return field.getInitializer(); + } + } + return res; + } + + private addIssueReport(stmt: Stmt, operand: Value): void { + const severity = this.metaData.severity; + let warnInfo = getLineAndColumn(stmt, operand); + let targetLan1 = getLanguageStr(Language.ARKTS1_1); + let targetLan2 = getLanguageStr(Language.ARKTS1_2); + + const problem = 'Interop'; + const desc = `In ${targetLan1}, it is not allowed to create object literal of type from ${targetLan2} (${s2dRuleId})`; + + 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)); + } +} diff --git a/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts index c25cc59611..dfabd40fe0 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ModifyStateVarCheck.ts @@ -171,7 +171,7 @@ export class ModifyStateVarCheck implements BaseChecker { } private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { - const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { const originPath = arkFile.getFilePath(); diff --git a/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts index f45c63723c..3e6f594aa1 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts @@ -37,6 +37,13 @@ import { BasicBlock, ArkIfStmt, ArkUnopExpr, + RelationalBinaryOperator, + LineColPosition, + UnaryOperator, + ArkNormalBinopExpr, + NormalBinaryOperator, + AbstractFieldRef, + ClassSignature, } from 'arkanalyzer/lib'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; import { BaseChecker, BaseMetaData } from '../BaseChecker'; @@ -47,6 +54,7 @@ import { CALL_DEPTH_LIMIT, getGlobalsDefineInDefaultMethod, GlobalCallGraphHelpe import { WarnInfo } from '../../utils/common/Utils'; import { ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; +import { BooleanConstant } from 'arkanalyzer/lib/core/base/Constant'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoTSLikeAsCheck'); const gMetaData: BaseMetaData = { @@ -55,6 +63,12 @@ const gMetaData: BaseMetaData = { description: '', }; +enum TypeAssuranceCondition { + Positive, + Negative, + NotExist, +} + export class NoTSLikeAsCheck implements BaseChecker { readonly metaData: BaseMetaData = gMetaData; public rule: Rule; @@ -181,21 +195,19 @@ export class NoTSLikeAsCheck implements BaseChecker { 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)) { + // 这里仅判断了cast op是否进行了instanceof判断,如果op是由op1赋值,op1进行了instanceof判断,此处不认为是做了有效检查,因为此赋值链可能很长且中途发生类型变化,极易判断错误 + const checkRes = this.checkTypeAssuranceInBasicBlock(block, castExpr); + if (checkRes === TypeAssuranceCondition.NotExist) { continue; } let checkedBB: Set = new Set(); let needCheckBB: number[] = []; checkedBB.add(block.getId()); const allSuccessors = block.getSuccessors(); - if (allSuccessors.length > 0 && positiveCheck) { + if (allSuccessors.length > 0 && checkRes === TypeAssuranceCondition.Positive) { needCheckBB.push(allSuccessors[0].getId()); } - if (allSuccessors.length > 1 && negativeCheck) { + if (allSuccessors.length > 1 && checkRes === TypeAssuranceCondition.Negative) { needCheckBB.push(allSuccessors[1].getId()); } while (needCheckBB.length > 0) { @@ -221,26 +233,7 @@ export class NoTSLikeAsCheck implements BaseChecker { 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 { + private checkTypeAssuranceInBasicBlock(bb: BasicBlock, castExpr: ArkCastExpr): TypeAssuranceCondition { for (const stmt of bb.getStmts()) { if (!(stmt instanceof ArkIfStmt)) { continue; @@ -248,98 +241,109 @@ export class NoTSLikeAsCheck implements BaseChecker { 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; - } + const operator = conditionExpr.getOperator(); + // 对于if (i instanceof A)这种条件语句,op1总是临时变量,op2总是false,操作符总是!= + if (!(op1 instanceof Local && op2 instanceof BooleanConstant && op2.getValue() === 'false' && operator === RelationalBinaryOperator.InEquality)) { + break; } + return this.checkTypeAssuranceWithLocal(op1, castExpr, stmt.getOriginPositionInfo(), true); } - return false; + return TypeAssuranceCondition.NotExist; } - private isCastExprWithTypeAssuranceNegative(bb: BasicBlock, castExpr: ArkCastExpr): boolean { - for (const stmt of bb.getStmts()) { - if (!(stmt instanceof ArkIfStmt)) { - continue; + private checkTypeAssuranceWithLocal(operand: Local, castExpr: ArkCastExpr, ifStmtPos: LineColPosition, shouldBe: boolean): TypeAssuranceCondition { + const declaringStmt = operand.getDeclaringStmt(); + if (declaringStmt === null) { + return TypeAssuranceCondition.NotExist; + } + // if语句中的所有条件遵从三地址码原则拆分成多个语句时,所有语句的位置信息是一致的,不一致时表示是条件语句之前的赋值或声明情况,不在本判断范围内 + const stmtPos = declaringStmt.getOriginPositionInfo(); + if (stmtPos.getLineNo() !== ifStmtPos.getLineNo() || stmtPos.getColNo() !== ifStmtPos.getColNo()) { + return TypeAssuranceCondition.NotExist; + } + if (!(declaringStmt instanceof ArkAssignStmt)) { + return TypeAssuranceCondition.NotExist; + } + const rightOp = declaringStmt.getRightOp(); + if (rightOp instanceof ArkInstanceOfExpr) { + if (this.isTypeAssuranceMatchCast(rightOp, castExpr)) { + if (shouldBe) { + return TypeAssuranceCondition.Positive; + } else { + return TypeAssuranceCondition.Negative; + } } - 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; + return TypeAssuranceCondition.NotExist; + } + if (rightOp instanceof ArkUnopExpr && rightOp.getOperator() === UnaryOperator.LogicalNot) { + const unaryOp = rightOp.getOp(); + if (unaryOp instanceof Local) { + return this.checkTypeAssuranceWithLocal(unaryOp, castExpr, ifStmtPos, !shouldBe); + } + return TypeAssuranceCondition.NotExist; + } + if (rightOp instanceof ArkNormalBinopExpr) { + const op1 = rightOp.getOp1(); + const op2 = rightOp.getOp2(); + const operator = rightOp.getOperator(); + // 这里仅判断&&和||两种逻辑运算符的场景,其他场景在包含类型守卫判断的条件语句中不常见,暂不考虑 + let res: TypeAssuranceCondition; + if (operator === NormalBinaryOperator.LogicalAnd) { + if (op1 instanceof Local) { + res = this.checkTypeAssuranceWithLocal(op1, castExpr, ifStmtPos, shouldBe); + if (res !== TypeAssuranceCondition.NotExist) { + return res; + } + } + if (op2 instanceof Local) { + res = this.checkTypeAssuranceWithLocal(op2, castExpr, ifStmtPos, shouldBe); + if (res !== TypeAssuranceCondition.NotExist) { + return res; + } } + return TypeAssuranceCondition.NotExist; } - if (op2 instanceof Local) { - const declareStmt = op2.getDeclaringStmt(); - if (declareStmt !== null && this.isStmtWithTypeAssuranceNegative(declareStmt, castExpr)) { - return true; + if (operator === NormalBinaryOperator.LogicalOr) { + // a or b,不论a或b里是类型守卫判断,均无法保证分支中的类型明确 + if (shouldBe) { + return TypeAssuranceCondition.NotExist; } } } - return false; + return TypeAssuranceCondition.NotExist; } - private isStmtWithTypeAssurancePositive(declareStmt: Stmt, castExpr: ArkCastExpr): boolean { - if (!(declareStmt instanceof ArkAssignStmt)) { - return false; - } - const rightOp = declareStmt.getRightOp(); - if (!(rightOp instanceof ArkInstanceOfExpr)) { - return false; - } + private isTypeAssuranceMatchCast(instanceOfExpr: ArkInstanceOfExpr, castExpr: ArkCastExpr): boolean { const castOp = castExpr.getOp(); const castType = castExpr.getType(); - const instanceofType = rightOp.getCheckType(); + const instanceofType = instanceOfExpr.getCheckType(); if (castType.getTypeString() !== instanceofType.getTypeString()) { return false; } - const instanceofOp = rightOp.getOp(); + const instanceofOp = instanceOfExpr.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; + private isStmtInBlock(stmt: Stmt, block: BasicBlock): boolean { + for (const s of block.getStmts()) { + if (s === stmt) { + return true; + } } - const instanceofOp = unaryOpRightOp.getOp(); - if (!(castOp instanceof Local && instanceofOp instanceof Local)) { - return false; + 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 castOp.getName() === instanceofOp.getName(); + return null; } private checkFromStmt( @@ -366,6 +370,11 @@ export class NoTSLikeAsCheck implements BaseChecker { if (this.isWithInterfaceAnnotation(currentStmt, scene)) { return currentStmt; } + + const fieldDeclareStmt = this.isCastOpFieldWithInterfaceType(currentStmt, scene); + if (fieldDeclareStmt) { + return fieldDeclareStmt; + } const gv = this.checkIfCastOpIsGlobalVar(currentStmt); if (gv) { const globalDefs = globalVarMap.get(gv.getName()); @@ -401,9 +410,7 @@ export class NoTSLikeAsCheck implements BaseChecker { const paramRef = this.isFromParameter(currentStmt); if (paramRef) { const paramIdx = paramRef.getIndex(); - const callsites = this.cg.getInvokeStmtByMethod( - currentStmt.getCfg().getDeclaringMethod().getSignature() - ); + const callsites = this.cg.getInvokeStmtByMethod(currentStmt.getCfg().getDeclaringMethod().getSignature()); this.processCallsites(callsites); const argDefs = this.collectArgDefs(paramIdx, callsites); for (const stmt of argDefs) { @@ -418,6 +425,34 @@ export class NoTSLikeAsCheck implements BaseChecker { return null; } + private isCastOpFieldWithInterfaceType(stmt: Stmt, scene: Scene): Stmt | undefined { + const obj = this.getCastOp(stmt); + if (obj === null || !(obj instanceof Local)) { + return undefined; + } + const declaringStmt = obj.getDeclaringStmt(); + if (declaringStmt === null || !(declaringStmt instanceof ArkAssignStmt)) { + return undefined; + } + const rightOp = declaringStmt.getRightOp(); + if (!(rightOp instanceof AbstractFieldRef)) { + return undefined; + } + const fieldDeclaring = rightOp.getFieldSignature().getDeclaringSignature(); + if (fieldDeclaring instanceof ClassSignature) { + const field = scene.getClass(fieldDeclaring)?.getField(rightOp.getFieldSignature()); + if (!field) { + return undefined; + } + const fieldInitializer = field.getInitializer(); + const lastStmt = fieldInitializer[fieldInitializer.length - 1]; + if (this.isWithInterfaceAnnotation(lastStmt, scene)) { + return lastStmt; + } + } + return undefined; + } + private checkIfCastOpIsGlobalVar(stmt: Stmt): Local | undefined { const obj = this.getCastOp(stmt); if (obj instanceof Local && !obj.getDeclaringStmt()) { @@ -568,7 +603,7 @@ export class NoTSLikeAsCheck implements BaseChecker { } private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { - const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { const originPath = arkFile.getFilePath(); diff --git a/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts index 66a5c66380..b582c90aaf 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts @@ -68,7 +68,7 @@ export class ObjectLiteralCheck implements BaseChecker { for (let arkFile of scene.getFiles()) { const topLevelVarMap: Map = new Map(); - this.collectImportedVar(topLevelVarMap, arkFile); + this.collectImportedVar(topLevelVarMap, arkFile, scene); this.collectTopLevelVar(topLevelVarMap, arkFile, scene); const handleClass = (cls: ArkClass): void => { @@ -106,7 +106,7 @@ export class ObjectLiteralCheck implements BaseChecker { } } - private collectImportedVar(importVarMap: Map, file: ArkFile) { + private collectImportedVar(importVarMap: Map, file: ArkFile, scene: Scene) { file.getImportInfos().forEach(importInfo => { const exportInfo = importInfo.getLazyExportInfo(); if (exportInfo === null) { @@ -120,6 +120,7 @@ export class ObjectLiteralCheck implements BaseChecker { if (!declaringStmt) { return; } + DVFGHelper.buildSingleDVFG(declaringStmt.getCfg().getDeclaringMethod(), scene); importVarMap.set(arkExport.getName(), [declaringStmt]); }); } @@ -382,7 +383,7 @@ export class ObjectLiteralCheck implements BaseChecker { } private getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { - const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { const originPath = arkFile.getFilePath(); diff --git a/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts index a6a56e9b4d..8f9c5cdb03 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts @@ -266,7 +266,7 @@ export class ObservedDecoratorCheck implements BaseChecker { canFindAllTargets: boolean = true ): string { if (issueClass === null || !canFindAllTargets) { - return `can not find all classes, please check this field manually`; + return `can not find all classes, please check this field manually (arkui-data-observation)`; } const fieldLine = field.getOriginPosition().getLineNo(); const fieldColumn = field.getOriginPosition().getColNo(); @@ -275,10 +275,10 @@ export class ObservedDecoratorCheck implements BaseChecker { 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; + res = `Class ${issueClass.getName()} is used by state property in [${fieldLine}, ${fieldColumn}], ` + res; } else { const filePath = path.normalize(fieldFileSig.getFileName()); - res = `The class is used by state property in file ${filePath} [${fieldLine}, ${fieldColumn}], ` + res; + res = `Class ${issueClass.getName()} is used by state property in file ${filePath} [${fieldLine}, ${fieldColumn}], ` + res; } return res; } diff --git a/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts index af8657687c..62a43d0c37 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ThisBindCheck.ts @@ -29,6 +29,7 @@ import { ArkNewExpr, ArkClass, ClassSignature, + ArkReturnStmt, } from 'arkanalyzer'; import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger'; import { BaseChecker, BaseMetaData } from '../BaseChecker'; @@ -115,7 +116,18 @@ export class ThisBindCheck implements BaseChecker { private useThisInBody(method: ArkMethod): boolean { const thisInstance = (method.getThisInstance() as Local)!; - return thisInstance.getUsedStmts().length > 0; + const usedStmts = thisInstance.getUsedStmts(); + if (method.getName() !== 'constructor') { + return usedStmts.length > 0; + } + // constructor方法一定会有return this语句,此句若为ArkAnalyzer为constructor方法自动生成,则不在检查范围内 + for (const stmt of usedStmts) { + if (stmt instanceof ArkReturnStmt && stmt.getOriginPositionInfo().getLineNo() <= 0) { + continue; + } + return true; + } + return false; } private isSafeUse(v: Value): boolean { @@ -348,7 +360,7 @@ export class ThisBindCheck implements BaseChecker { } private getLineAndColumn(stmt: ArkAssignStmt, operand: Value): WarnInfo { - const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { const originPath = arkFile.getFilePath(); diff --git a/ets2panda/linter/homecheck/src/checker/migration/Utils.ts b/ets2panda/linter/homecheck/src/checker/migration/Utils.ts index 0992bcbe88..02f114bd0f 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/Utils.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/Utils.ts @@ -13,7 +13,18 @@ * limitations under the License. */ -import { ArkAssignStmt, ArkMethod, CallGraph, CallGraphBuilder, Local, LOG_MODULE_TYPE, Logger, Scene, Stmt, Value } from 'arkanalyzer/lib'; +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'; @@ -25,6 +36,10 @@ export const CALL_DEPTH_LIMIT = 2; export class CallGraphHelper { private static cgInstance: CallGraph | null = null; + public static dispose(): void { + this.cgInstance = null; + } + public static getCGInstance(scene: Scene): CallGraph { if (!this.cgInstance) { this.cgInstance = new CallGraph(scene); @@ -36,6 +51,10 @@ export class CallGraphHelper { export class GlobalCallGraphHelper { private static cgInstance: CallGraph | null = null; + public static dispose(): void { + this.cgInstance = null; + } + public static getCGInstance(scene: Scene): CallGraph { if (!this.cgInstance) { this.cgInstance = new CallGraph(scene); @@ -51,6 +70,14 @@ export class DVFGHelper { private static dvfgBuilder: DVFGBuilder; private static built: Set = new Set(); + public static dispose(): void { + // @ts-ignore + this.dvfgInstance = null; + // @ts-ignore + this.dvfgBuilder = null; + this.built.clear(); + } + private static createDVFGInstance(scene: Scene): void { if (!this.dvfgInstance) { this.dvfgInstance = new DVFG(GlobalCallGraphHelper.getCGInstance(scene)); @@ -117,7 +144,7 @@ export function getLanguageStr(language: Language): string { } export function getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { - const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile(); + const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const originPosition = stmt.getOperandOriginalPosition(operand); if (arkFile && originPosition) { const originPath = arkFile.getFilePath(); @@ -126,7 +153,7 @@ export function getLineAndColumn(stmt: Stmt, operand: Value): WarnInfo { const endCol = startCol; return { line, startCol, endCol, filePath: originPath }; } else { - logger.debug('ArkFile is null.'); + logger.debug('ArkFile or operand position is null.'); } return { line: -1, startCol: -1, endCol: -1, filePath: '' }; } diff --git a/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts b/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts index 5c3f6478ed..7be52a159a 100644 --- a/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts +++ b/ets2panda/linter/homecheck/src/tools/migrationTool/MigrationTool.ts @@ -21,7 +21,8 @@ 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 { FileIssues } from "../../model/Defects"; +import { FileIssues } from '../../model/Defects'; +import { CallGraphHelper, DVFGHelper, GlobalCallGraphHelper } from '../../checker/migration/Utils'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'MigrationTool'); @@ -68,7 +69,16 @@ export class MigrationTool { await this.checkEntry.runAll(); let result = this.checkEntry.sortIssues(); + this.dispose(); logger.info(`MigrationTool run end`); return result; } + + private dispose(): void { + CallGraphHelper.dispose(); + GlobalCallGraphHelper.dispose(); + DVFGHelper.dispose(); + CheckerStorage.dispose(); + this.checkEntry.scene.dispose(); + } } \ 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 index b022e5bd12..9e43517c0f 100644 --- a/ets2panda/linter/homecheck/src/utils/common/CheckerIndex.ts +++ b/ets2panda/linter/homecheck/src/utils/common/CheckerIndex.ts @@ -27,6 +27,8 @@ import { InteropObjectLiteralCheck } from '../../checker/migration/InteropDynami import { InteropAssignCheck } from '../../checker/migration/InteropAssignCheck'; import { InteropJSModifyPropertyCheck } from '../../checker/migration/InteropJSModifyPropertyCheck'; import { NoTSLikeAsCheck } from '../../checker/migration/NoTSLikeAsCheck'; +import { InteropS2DObjectLiteralCheck } from '../../checker/migration/InteropS2DObjectLiteralsCheck'; +import { InteropDeprecatedBuiltInAPICheck } from '../../checker/migration/InteropDeprecatedBuiltInAPICheck'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CheckerIndex'); @@ -38,6 +40,7 @@ export const fileRules = { '@migration/arkui-custombuilder-passing': CustomBuilderCheck, '@migration/no-method-overriding-field-check': NoMethodOverridingFieldCheck, '@migration/interop-boxed-type-check': InteropBoxedTypeCheck, + '@migration/arkts-interop-s2d-object-literal': InteropS2DObjectLiteralCheck, }; export const projectRules = { @@ -47,6 +50,7 @@ export const projectRules = { '@migration/interop-js-modify-property': InteropJSModifyPropertyCheck, '@migration/interop-dynamic-object-literals': InteropObjectLiteralCheck, '@migration/arkts-no-ts-like-as': NoTSLikeAsCheck, + '@migration/arkts-interop-s2d-dynamic-call-builtin-api-not-in-static': InteropDeprecatedBuiltInAPICheck, }; // 新增文件级的checker,需要在此处注册 diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts b/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts index f3bedd5017..922b716e95 100644 --- a/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts +++ b/ets2panda/linter/homecheck/src/utils/common/CheckerStorage.ts @@ -21,6 +21,11 @@ export class CheckerStorage { private apiVersion: number = 16; private product: string = ''; + public static dispose(): void { + // @ts-ignore + this.instance = null; + } + /** * 获取 CheckerStorage 的单例实例 * @returns {CheckerStorage} CheckerStorage 的单例实例 diff --git a/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts b/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts index 48b06a414d..f17425f284 100644 --- a/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts +++ b/ets2panda/linter/homecheck/src/utils/common/FileUtils.ts @@ -232,7 +232,7 @@ export class FileUtils { } private static shouldSkipFile(fileName: string): boolean { - return ['oh_modules', 'node_modules', 'hvigorfile.ts', 'ohosTest'].includes(fileName); + return ['oh_modules', 'node_modules', 'hvigorfile.ts', 'hvigorfile.js', 'hvigor-wrapper.js', 'ohosTest'].includes(fileName); } private static shouldAddFile(filePath: string, exts: string[]): boolean { @@ -310,4 +310,4 @@ export class FileUtils { export enum WriteFileMode { OVERWRITE, APPEND -} \ No newline at end of file +} diff --git a/ets2panda/linter/package.json b/ets2panda/linter/package.json index 9c02abca45..7b374c9944 100644 --- a/ets2panda/linter/package.json +++ b/ets2panda/linter/package.json @@ -17,7 +17,7 @@ "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-and-homecheck.mjs", - "pack:linter": "rimraf bundle && mkdir bundle && npm pack --pack-destination bundle", + "pack:linter": "rimraf bundle && mkdir bundle && npm pack && mv panda-tslinter-*.tgz 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/migration,test/ohmurl,test/interop,test/sdkwhite,test/concurrent,test/builtin", diff --git a/ets2panda/linter/src/cli/CommandLineParser.ts b/ets2panda/linter/src/cli/CommandLineParser.ts index d20a18c218..9849eedf17 100644 --- a/ets2panda/linter/src/cli/CommandLineParser.ts +++ b/ets2panda/linter/src/cli/CommandLineParser.ts @@ -152,6 +152,9 @@ function formArkts2Options(cmdOptions: CommandLineOptions, commanderOpts: Option if (commanderOpts.verbose) { cmdOptions.verbose = true; } + if (commanderOpts.enableInterop) { + cmdOptions.scanWholeProjectInHomecheck = true; + } } function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { @@ -226,12 +229,10 @@ function createCommand(): Command { 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'). - option( - '--only-arkts2-syntax-rules', - 'only syntax rules, excluding rules such as SDK, Arkui, Interop, Concurrent, etc' - ). + option('--only-arkts2-syntax-rules', 'only syntax rules'). option('-o, --output-file-path ', 'path to store all log and result files'). option('--verbose', 'set log level to see debug messages'). + option('--enable-interop', 'scan whole project to report 1.1 import 1.2'). 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 45bd9fddcd..5af05d0e31 100644 --- a/ets2panda/linter/src/cli/LinterCLI.ts +++ b/ets2panda/linter/src/cli/LinterCLI.ts @@ -58,9 +58,10 @@ async function runIdeInteractiveMode(cmdOptions: CommandLineOptions): Promise { + return problem.rule.includes('s2d'); + }); + if (filteredProblems.length > 0) { + mergedProblems.set(file, filteredProblems); + } else { + mergedProblems.delete(file); + } + } + } } async function generateReportFile(reportData, reportPath?: string): Promise { diff --git a/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts b/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts index 82bf349ba6..e1e433013c 100644 --- a/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts @@ -69,7 +69,12 @@ export abstract class BaseTypeScriptLinter { }); } - protected incrementCounters(node: ts.Node | ts.CommentRange, faultId: number, autofix?: Autofix[]): void { + protected incrementCounters( + node: ts.Node | ts.CommentRange, + faultId: number, + autofix?: Autofix[], + errorMsg?: string + ): void { const [startOffset, endOffset] = TsUtils.getHighlightRange(node, faultId); const startPos = this.sourceFile.getLineAndCharacterOfPosition(startOffset); const endPos = this.sourceFile.getLineAndCharacterOfPosition(endOffset); @@ -78,7 +83,7 @@ export abstract class BaseTypeScriptLinter { const faultType = TypeScriptLinterConfig.tsSyntaxKindNames[node.kind]; const cookBookMsgNum = faultsAttrs[faultId] ? faultsAttrs[faultId].cookBookRef : 0; - const cookBookTg = cookBookTag[cookBookMsgNum]; + const cookBookTg = errorMsg ? errorMsg : cookBookTag[cookBookMsgNum]; const severity = faultsAttrs[faultId]?.severity ?? ProblemSeverity.ERROR; const isMsgNumValid = cookBookMsgNum > 0; autofix = autofix ? BaseTypeScriptLinter.addLineColumnInfoInAutofix(autofix, startPos, endPos) : autofix; diff --git a/ets2panda/linter/src/lib/CommandLineOptions.ts b/ets2panda/linter/src/lib/CommandLineOptions.ts index cbcc81f622..1bdde46fae 100644 --- a/ets2panda/linter/src/lib/CommandLineOptions.ts +++ b/ets2panda/linter/src/lib/CommandLineOptions.ts @@ -33,4 +33,5 @@ export interface CommandLineOptions { disableStrictDiagnostics?: boolean; outputFilePath?: string; verbose?: boolean; + scanWholeProjectInHomecheck?: boolean; } diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 4fe5be4659..17c0d8899b 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -236,7 +236,7 @@ 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[206] = '"debugger" is not supported (arkts-no-debugger)'; 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)'; @@ -245,7 +245,7 @@ cookBookTag[210] = 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[214] = 'Objects have no constructor property in ArkTS1.2 (arkts-obj-no-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)'; @@ -265,28 +265,29 @@ cookBookTag[256] = '"@Styles" decorator is not supported (arkui-no-styles-decora 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[259] = 'The ArkUI interface should be imported before it is used (arkui-modular-interface)'; cookBookTag[260] = 'The "@Entry" annotation does not support dynamic parameters (arkui-entry-annotation-parameters)'; 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[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[270] = 'ArkTS1.2 cannot catch a non Error instance thrown from JS code (arkts-interop-js2s-js-exception)'; 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)'; + 'Custom components with custom layout capability need to add the "@CustomLayout" decorator (arkui-custom-layout-need-add-decorator)'; cookBookTag[281] = '"@Prop" decorator is not supported (arkui-no-prop-decorator)'; cookBookTag[282] = '"@StorageProp" decorator is not supported (arkui-no-storageprop-decorator)'; cookBookTag[283] = '"@LocalStorageProp" decorator is not supported (arkui-no-localstorageprop-decorator)'; cookBookTag[284] = '"prop" function is not supported (arkui-no-prop-function)'; cookBookTag[285] = '"setAndProp" function is not supported (arkui-no-setandprop-function)'; +cookBookTag[286] = + 'Parameters decorated with "@Prop" need to call the specific method when receiving data to ensure deep copy of the data (arkui-prop-need-call-method-for-deep-copy)'; 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] = @@ -322,7 +323,7 @@ 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[329] = 'Enum cannot get member name by member value (arkts-enum-no-props-by-index)'; 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)'; diff --git a/ets2panda/linter/src/lib/FaultAttrs.ts b/ets2panda/linter/src/lib/FaultAttrs.ts index e198eb4e83..07f5587812 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -186,10 +186,9 @@ faultsAttrs[FaultID.UIInterfaceImport] = new FaultAttributes(259); faultsAttrs[FaultID.EntryAnnotation] = new FaultAttributes(260); 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.InteropJsObjectCallStaticFunc] = new FaultAttributes(267, ProblemSeverity.WARNING); faultsAttrs[FaultID.InteropJsObjectConditionJudgment] = new FaultAttributes(268); faultsAttrs[FaultID.InteropJsObjectExpandStaticInstance] = new FaultAttributes(269); faultsAttrs[FaultID.InteropJSFunctionInvoke] = new FaultAttributes(270); @@ -200,6 +199,7 @@ faultsAttrs[FaultID.StoragePropDecoratorNotSupported] = new FaultAttributes(282) faultsAttrs[FaultID.LocalStoragePropDecoratorNotSupported] = new FaultAttributes(283); faultsAttrs[FaultID.PropFunctionNotSupported] = new FaultAttributes(284); faultsAttrs[FaultID.SetAndPropFunctionNotSupported] = new FaultAttributes(285); +faultsAttrs[FaultID.PropNeedCallMethodForDeepCopy] = new FaultAttributes(286); 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 1dd89ea968..49646a1965 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -190,7 +190,6 @@ 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'; @@ -252,3 +251,4 @@ faultDesc[FaultID.StoragePropDecoratorNotSupported] = '"@StorageProp" decorator faultDesc[FaultID.LocalStoragePropDecoratorNotSupported] = '"@LocalStorageProp" decorator is not supported'; faultDesc[FaultID.PropFunctionNotSupported] = '"prop" function is not supported'; faultDesc[FaultID.SetAndPropFunctionNotSupported] = '"setAndProp" function is not supported'; +faultDesc[FaultID.PropNeedCallMethodForDeepCopy] = 'Deep copy needs to call the specific method'; diff --git a/ets2panda/linter/src/lib/HomeCheck.ts b/ets2panda/linter/src/lib/HomeCheck.ts index abf128b57f..6ad5e01ad9 100644 --- a/ets2panda/linter/src/lib/HomeCheck.ts +++ b/ets2panda/linter/src/lib/HomeCheck.ts @@ -18,6 +18,7 @@ import type { FileIssues, RuleFix } from 'homecheck'; import type { CommandLineOptions } from './CommandLineOptions'; import type { ProblemInfo } from './ProblemInfo'; import { FaultID } from './Problems'; +import { shouldProcessFile } from './LinterRunner'; interface RuleConfigInfo { ruleSet: string[]; @@ -39,8 +40,18 @@ export function getHomeCheckConfigInfo(cmdOptions: CommandLineOptions): { ruleConfigInfo: RuleConfigInfo; projectConfigInfo: ProjectConfigInfo; } { + let inputFiles = cmdOptions.inputFiles; + let fliesTocheck: string[] = inputFiles; + if (cmdOptions.scanWholeProjectInHomecheck === true) { + fliesTocheck = []; + } + inputFiles = inputFiles.filter((input) => { + return shouldProcessFile(cmdOptions, input); + }); const languageTags = new Map(); - const inputFiles = cmdOptions.inputFiles; + inputFiles.forEach((file) => { + languageTags.set(path.normalize(file), 2); + }); const ruleConfigInfo = { ruleSet: ['plugin:@migration/all'], files: ['**/*.ets', '**/*.ts', '**/*.js'] @@ -54,7 +65,7 @@ export function getHomeCheckConfigInfo(cmdOptions: CommandLineOptions): { hmsSdkPath: cmdOptions.sdkExternalApiPath ? cmdOptions.sdkExternalApiPath[0] : '', reportDir: './', languageTags: languageTags, - fileOrFolderToCheck: inputFiles, + fileOrFolderToCheck: fliesTocheck, logLevel: cmdOptions.verbose ? 'DEBUG' : 'INFO', arkAnalyzerLogLevel: cmdOptions.verbose ? 'DEBUG' : 'ERROR' }; diff --git a/ets2panda/linter/src/lib/LinterOptions.ts b/ets2panda/linter/src/lib/LinterOptions.ts index f6124ac4ab..72613a4cd1 100644 --- a/ets2panda/linter/src/lib/LinterOptions.ts +++ b/ets2panda/linter/src/lib/LinterOptions.ts @@ -45,4 +45,5 @@ export interface LinterOptions { migrationReport?: boolean; wholeProjectPath?: string; checkTsAndJs?: boolean; + inputFiles?: string[]; } diff --git a/ets2panda/linter/src/lib/LinterRunner.ts b/ets2panda/linter/src/lib/LinterRunner.ts index 04fc4174f4..453731f7bc 100644 --- a/ets2panda/linter/src/lib/LinterRunner.ts +++ b/ets2panda/linter/src/lib/LinterRunner.ts @@ -31,6 +31,7 @@ import { ARKTS_IGNORE_DIRS_OH_MODULES, ARKTS_IGNORE_FILES } from './utils/consts/ArktsIgnorePaths'; +import { USE_STATIC } from './utils/consts/InteropAPI'; import { EXTNAME_TS, EXTNAME_JS } from './utils/consts/ExtensionName'; import { mergeArrayMaps } from './utils/functions/MergeArrayMaps'; import { clearPathHelperCache, pathContainsDirectory } from './utils/functions/PathHelper'; @@ -42,7 +43,9 @@ import { ProjectStatistics } from './statistics/ProjectStatistics'; import type { BaseTypeScriptLinter } from './BaseTypeScriptLinter'; function prepareInputFilesList(cmdOptions: CommandLineOptions): string[] { - let inputFiles = cmdOptions.inputFiles; + let inputFiles = cmdOptions.inputFiles.map((x) => { + return path.normalize(x); + }); if (!cmdOptions.parsedConfigFile) { return inputFiles; } @@ -93,6 +96,7 @@ function lintImpl(config: LinterConfig): LintRunResult { inputFiles = inputFiles.filter((input) => { return shouldProcessFile(options, input); }); + options.inputFiles = inputFiles; const srcFiles: ts.SourceFile[] = []; for (const inputFile of inputFiles) { const srcFile = tsProgram.getSourceFile(inputFile); @@ -185,6 +189,18 @@ function migrate( return lintResult; } +function hasUseStaticDirective(srcFile: ts.SourceFile): boolean { + if (!srcFile?.statements.length) { + return false; + } + const statements = srcFile.statements; + return ( + ts.isExpressionStatement(statements[0]) && + ts.isStringLiteral(statements[0].expression) && + statements[0].expression.getText() === USE_STATIC + ); +} + function fix( linterConfig: LinterConfig, lintResult: LintRunResult, @@ -204,17 +220,22 @@ function fix( } } mergedProblems.forEach((problemInfos, fileName) => { - // If nothing to fix, skip file - if (!qEd.QuasiEditor.hasAnyAutofixes(problemInfos)) { - return; - } - const srcFile = program.getSourceFile(fileName); if (!srcFile) { - Logger.error(`Failed to retrieve source file: ${fileName}`); + if (!linterConfig.cmdOptions.homecheck) { + Logger.error(`Failed to retrieve source file: ${fileName}`); + } + return; + } + const needToAddUseStatic = + linterConfig.cmdOptions.linterOptions.arkts2 && + linterConfig.cmdOptions.inputFiles.includes(fileName) && + !hasUseStaticDirective(srcFile) && + linterConfig.cmdOptions.linterOptions.ideInteractive; + // If nothing to fix or don't need to add 'use static', then skip file + if (!qEd.QuasiEditor.hasAnyAutofixes(problemInfos) && !needToAddUseStatic) { return; } - const qe: qEd.QuasiEditor = new qEd.QuasiEditor( fileName, srcFile.text, @@ -222,7 +243,7 @@ function fix( undefined, linterConfig.cmdOptions.outputFilePath ); - updatedSourceTexts.set(fileName, qe.fix(problemInfos)); + updatedSourceTexts.set(fileName, qe.fix(problemInfos, needToAddUseStatic)); appliedFix = true; }); @@ -242,7 +263,7 @@ function getMigrationCreateProgramCallback(updatedSourceTexts: Map; static literalAsPropertyNameTypeSet: Set; private localApiListItem: ApiListItem | undefined = undefined; + static constructorFuncsSet: Set; static initGlobals(): void { TypeScriptLinter.sharedModulesCache = new Map(); @@ -249,6 +250,12 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + private static addSdkConstructorFuncsSetData(item: ApiListItem): void { + if (item.api_info.problem === SdkProblem.ConstructorFuncs) { + TypeScriptLinter.constructorFuncsSet.add(item); + } + } + private static addGlobalApiInfosCollocetionData(item: ApiListItem): void { const problemType = item.api_info.problem; const isGlobal = item.is_global; @@ -264,6 +271,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { private static initSdkWhitelist(): void { TypeScriptLinter.indexedTypeSet = new Set(); TypeScriptLinter.literalAsPropertyNameTypeSet = new Set(); + TypeScriptLinter.constructorFuncsSet = new Set(); const list: ApiList = new ApiList(apiWhiteList); if (list?.api_list?.length > 0) { for (const item of list.api_list) { @@ -275,6 +283,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { }); TypeScriptLinter.addSdkIndexedTypeSetData(item); TypeScriptLinter.addSdkliteralAsPropertyNameTypeSetData(item); + TypeScriptLinter.addSdkConstructorFuncsSetData(item); TypeScriptLinter.addGlobalApiInfosCollocetionData(item); } } @@ -324,7 +333,6 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { [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], @@ -399,7 +407,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.autofixer = new Autofixer(this.tsTypeChecker, this.tsUtils, this.sourceFile, this.options.cancellationToken); } - this.useStatic = TsUtils.isArkts12File(this.sourceFile); + this.useStatic = this.tsUtils.isArkts12File(this.sourceFile); this.fileExportDeclCaches = undefined; this.extractImportedNames(this.sourceFile); this.visitSourceFile(this.sourceFile); @@ -610,9 +618,6 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } for (const prop of invalidProps) { - if (ts.isShorthandPropertyAssignment(prop) && !TsUtils.isAnyType(this.tsTypeChecker.getTypeAtLocation(prop))) { - continue; - } const autofix = ts.isShorthandPropertyAssignment(prop) ? this.autofixer?.fixShorthandPropertyAssignment(prop) : objLiteralAutofix; @@ -643,6 +648,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { * e.g. there is no element which is untyped object literals */ const arrayLitElements = arrayLitNode.elements; + if (this.options.arkts2 && !arrayLitType && arrayLitElements.length === 0) { + this.incrementCounters(node, FaultID.NosparseArray); + } for (const element of arrayLitElements) { const elementContextType = this.tsTypeChecker.getContextualType(element); if (ts.isObjectLiteralExpression(element)) { @@ -683,10 +691,11 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleDeclarationDestructuring(tsParam); this.handleDeclarationInferredType(tsParam); this.handleInvalidIdentifier(tsParam); - this.handleSdkDuplicateDeclName(tsParam); + this.handleSdkGlobalApi(tsParam); const typeNode = tsParam.type; - if (this.options.arkts2 && typeNode && typeNode.kind === ts.SyntaxKind.VoidKeyword) { - this.incrementCounters(typeNode, FaultID.LimitedVoidType); + if (this.options.arkts2 && typeNode && TsUtils.typeContainsVoid(typeNode)) { + const autofix = this.autofixer?.fixLimitedVoidType(tsParam); + this.incrementCounters(typeNode, FaultID.LimitedVoidType, autofix); } this.handlePropertyDescriptorInScenarios(tsParam); } @@ -913,78 +922,10 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const tsForStmt = node as ts.ForStatement; const tsForInit = tsForStmt.initializer; if (tsForInit) { - this.checkStaticArrayControl(tsForStmt); this.checkForLoopDestructuring(tsForInit); } } - private checkStaticArrayControl(tsForStmt: ts.ForStatement): void { - if (!this.options.arkts2 || !this.useStatic) { - return; - } - - if (!ts.isBlock(tsForStmt.statement)) { - return; - } - - const loopBody = tsForStmt.statement; - const arrayAccessInfo = this.checkBodyHasArrayAccess(loopBody); - const loopCondition = tsForStmt.condition; - - if (!arrayAccessInfo) { - return; - } - if (!loopCondition) { - this.incrementCounters(arrayAccessInfo.arrayIdent.parent, FaultID.RuntimeArrayCheck); - return; - } - const arraySymbol = this.tsUtils.trueSymbolAtLocation(arrayAccessInfo.arrayIdent); - if (!arraySymbol) { - return; - } - - const arrayCheckedAgainst = this.checkConditionForArrayAccess(loopCondition, arraySymbol); - if (!arrayCheckedAgainst) { - this.incrementCounters(arrayAccessInfo.arrayIdent.parent, FaultID.RuntimeArrayCheck); - return; - } - - this.checkIfAccessAndCheckVariablesMatch(arrayAccessInfo, arrayCheckedAgainst); - } - - 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 (checkedAgainst === NUMBER_LITERAL) { - this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); - return; - } - - const checkedAgainstSym = this.tsUtils.trueSymbolAtLocation(checkedAgainst); - if (!checkedAgainstSym) { - return; - } - - const accessingIdentSym = this.tsUtils.trueSymbolAtLocation(accessingIdentifier); - - if (checkedAgainstSym !== accessingIdentSym) { - this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); - return; - } - - if (this.isChangedAfterCheck(arrayIdent.getSourceFile(), checkedAgainstSym)) { - this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); - } - } - private checkConditionForArrayAccess(condition: ts.Expression, arraySymbol: ts.Symbol): UncheckedIdentifier { if (!ts.isBinaryExpression(condition)) { return undefined; @@ -1048,115 +989,6 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { 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(); - let boundChecked = true; - - for (const statement of sourceFile.statements) { - const checkResult = this.checkStatementForArrayAccess(statement, arrayAccessInfo, arraySym); - if (checkResult === CheckResult.SKIP) { - boundChecked = false; - continue; - } - - if (checkResult === CheckResult.HAS_ARRAY_ACCES) { - continue; - } - - if (checkResult === CheckResult.CHECKED) { - boundChecked = true; - break; - } - } - - if (!boundChecked) { - this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); - } - } - - private checkStatementForArrayAccess( - statement: ts.Statement, - accessInfo: ArrayAccess, - arraySym: ts.Symbol - ): CheckResult { - if (ts.isForStatement(statement)) { - return this.isThisArrayAccess(statement.statement as ts.Block, accessInfo.arrayIdent); - } - - if (!ts.isIfStatement(statement)) { - return CheckResult.SKIP; - } - - const thisArrayAccess = this.isThisArrayAccess(statement.thenStatement as ts.Block, accessInfo.arrayIdent); - if (thisArrayAccess !== CheckResult.SKIP) { - return thisArrayAccess; - } - - const checkedAgainst = this.checkConditionForArrayAccess(statement.expression, arraySym); - if (!checkedAgainst) { - return CheckResult.SKIP; - } - - this.checkIfAccessAndCheckVariablesMatch(accessInfo, checkedAgainst); - return CheckResult.CHECKED; - } - - private isThisArrayAccess(block: ts.Block, arrayIdent: ts.Identifier): CheckResult { - const info = this.checkBodyHasArrayAccess(block); - if (!info) { - return CheckResult.SKIP; - } - - if (info.arrayIdent === arrayIdent) { - return CheckResult.CHECKED; - } - - return CheckResult.HAS_ARRAY_ACCES; - } - - 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; @@ -1168,42 +1000,21 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const tsForOfStmt = node as ts.ForOfStatement; const tsForOfInit = tsForOfStmt.initializer; this.checkForLoopDestructuring(tsForOfInit); + this.handleForOfJsArray(tsForOfStmt); } - 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) { + private updateDataSdkJsonInfo(importDeclNode: ts.ImportDeclaration, importClause: ts.ImportClause): void { + const sdkInfo = TypeScriptLinter.pathMap.get(importDeclNode.moduleSpecifier.getText()); + if (!sdkInfo) { return; } - - const checkedAgainst = this.checkConditionForArrayAccess(ifStatement.expression, arraySymbol); - if (!checkedAgainst) { - this.incrementCounters(arrayIdent, FaultID.RuntimeArrayCheck); - return; + if (importClause.name) { + const importClauseName = importClause.name.text; + sdkInfo.forEach((info) => { + TypeScriptLinter.addOrUpdateData(this.interfaceMap, importClauseName, info); + }); } - - 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) { + if (importClause.namedBindings) { const namedImports = importClause.namedBindings as ts.NamedImports; if (!namedImports.elements) { return; @@ -1364,11 +1175,12 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleLimitedVoidTypeFromSdkOnPropertyAccessExpression(node as ts.PropertyAccessExpression); this.checkDepricatedIsConcurrent(node as ts.PropertyAccessExpression); this.propertyAccessExpressionForBuiltin(node as ts.PropertyAccessExpression); - + this.checkConstrutorAccess(node as ts.PropertyAccessExpression); + this.handleTaskPoolDeprecatedUsages(node as ts.PropertyAccessExpression); + this.handleNoTuplesArraysForPropertyAccessExpression(node as ts.PropertyAccessExpression); if (ts.isCallExpression(node.parent) && node === node.parent.expression) { return; } - const propertyAccessNode = node as ts.PropertyAccessExpression; const exprSym = this.tsUtils.trueSymbolAtLocation(propertyAccessNode); const baseExprSym = this.tsUtils.trueSymbolAtLocation(propertyAccessNode.expression); @@ -1412,6 +1224,36 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + private isJsRelated(node: ts.Expression): boolean { + if (this.tsUtils.isJsImport(node)) { + return true; + } + + if (ts.isNewExpression(node)) { + return this.tsUtils.isJsImport(node.expression); + } + + if (ts.isIdentifier(node)) { + const symbol = this.tsUtils.trueSymbolAtLocation(node); + if (!symbol) { + return false; + } + + const declarations = symbol.getDeclarations(); + if (!declarations || declarations.length === 0) { + return false; + } + + for (const declaration of declarations) { + if (ts.isVariableDeclaration(declaration) && declaration.initializer) { + return this.isJsRelated(declaration.initializer); + } + } + } + + return false; + } + propertyAccessExpressionForInterop(propertyAccessNode: ts.PropertyAccessExpression): void { if (!this.useStatic || !this.options.arkts2) { return; @@ -1424,20 +1266,28 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } return current; - } + }; const firstObjNode = getFirstObjectNode(propertyAccessNode); - const isFromJs = this.tsUtils.isJsImport(firstObjNode); + const isJsObject = this.isJsRelated(firstObjNode); + if (!isJsObject) { + return; + } - if(isFromJs) { - 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); - } + if (ts.isBinaryExpression(propertyAccessNode.parent)) { + const isAssignment = propertyAccessNode.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken; + const autofix = isAssignment ? + this.autofixer?.fixInteropBinaryExpression(propertyAccessNode.parent) : + this.autofixer?.fixInteropPropertyAccessExpression(propertyAccessNode); + + this.incrementCounters( + isAssignment ? propertyAccessNode.parent : propertyAccessNode, + FaultID.InteropObjectProperty, + autofix + ); + } else { + const autofix = this.autofixer?.fixInteropPropertyAccessExpression(propertyAccessNode); + this.incrementCounters(propertyAccessNode, FaultID.InteropObjectProperty, autofix); } } @@ -1448,36 +1298,31 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (!ts.isCallExpression(node.parent)) { return; } - const methodName = node.name.getText(); if (methodName !== ISCONCURRENT) { return; } - - const symbol = this.tsUtils.trueSymbolAtLocation(node.expression); - if (!symbol) { + const moduleSpecifier = this.findModuleSpecifierforDepricatedIsConcurrent(node); + if (!moduleSpecifier || !ts.isStringLiteral(moduleSpecifier)) { return; } + if ( + TASKPOOL_MODULES.some((moduleName) => { + return TsUtils.removeOrReplaceQuotes(moduleSpecifier.getText(), false) === moduleName; + }) + ) { + this.incrementCounters(node.name, FaultID.IsConcurrentDeprecated); + } + } - 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); - } + findModuleSpecifierforDepricatedIsConcurrent(node: ts.PropertyAccessExpression): ts.Expression | undefined { + let symbol = this.tsUtils.trueSymbolAtLocation(node.expression); + if (symbol && 'unknown' === symbol.name) { + symbol = this.tsTypeChecker.getSymbolAtLocation(node.expression); } + const importDecl = ts.findAncestor(TsUtils.getDeclaration(symbol), ts.isImportDeclaration); + return importDecl?.moduleSpecifier; } checkFunctionProperty( @@ -1588,8 +1433,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { ); const classDecorators = ts.getDecorators(node.parent); const propType = node.type?.getText(); - if (this.options.arkts2 && propType === 'void' && node.type) { - this.incrementCounters(node.type, FaultID.LimitedVoidType); + if (this.options.arkts2 && node.type && TsUtils.typeContainsVoid(node.type)) { + const autofix = this.autofixer?.fixLimitedVoidType(node); + this.incrementCounters(node.type, FaultID.LimitedVoidType, autofix); } this.filterOutDecoratorsDiagnostics( classDecorators, @@ -1609,7 +1455,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleInvalidIdentifier(node); this.handleStructPropertyDecl(node); this.handlePropertyDeclarationForProp(node); - this.handleSdkDuplicateDeclName(node); + this.handleSdkGlobalApi(node); this.handleObjectLiteralAssignmentToClass(node); } @@ -1634,6 +1480,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { private handlePropertyAssignment(node: ts.PropertyAssignment): void { this.handleDollarBind(node); + this.handlePropertyAssignmentForProp(node); this.handleQuotedHyphenPropsDeprecated(node); const propName = node.name; @@ -1863,6 +1710,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (hasUnfixableReturnType) { this.incrementCounters(funcExpr, FaultID.LimitedReturnTypeInference); } + this.handleLimitedVoidFunction(funcExpr); } private handleArrowFunction(node: ts.Node): void { @@ -1877,6 +1725,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } this.checkDefaultParamBeforeRequired(arrowFunc); + this.handleLimitedVoidFunction(arrowFunc); } private handleFunctionDeclaration(node: ts.Node): void { @@ -1922,6 +1771,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.checkAssignmentNumericSemanticsFuntion(tsFunctionDeclaration); this.handleInvalidIdentifier(tsFunctionDeclaration); this.checkDefaultParamBeforeRequired(tsFunctionDeclaration); + this.handleLimitedVoidFunction(tsFunctionDeclaration); } private handleMissingReturnType( @@ -2037,7 +1887,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const propertyAccess = ts.isParenthesizedExpression(expr) ? expr.expression : expr; if (ts.isPropertyAccessExpression(propertyAccess)) { - const exprSym = this.tsUtils.trueSymbolAtLocation(propertyAccess); + const exprSym = this.tsUtils.trueSymbolAtLocation(propertyAccess.expression); const declaration = exprSym?.declarations?.[0]; this.checkAndProcessDeclaration(declaration, tsUnaryArithm); } @@ -2131,8 +1981,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.checkAssignmentMatching(tsBinaryExpr, leftOperandType, tsRhsExpr); this.checkFunctionTypeCompatible(typeNode, tsRhsExpr); this.handleEsObjectAssignment(tsBinaryExpr, typeNode, tsRhsExpr); - this.handleSdkDuplicateDeclName(tsBinaryExpr); - this.checkArrayTypeImmutable(tsBinaryExpr); + this.handleSdkGlobalApi(tsBinaryExpr); break; case ts.SyntaxKind.AmpersandAmpersandEqualsToken: case ts.SyntaxKind.QuestionQuestionEqualsToken: @@ -2158,7 +2007,8 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const processExpression = (expr: ts.Expression): void => { const symbol = this.tsUtils.trueSymbolAtLocation(expr); if (this.isJsFileSymbol(symbol) || this.isJsFileExpression(expr)) { - this.incrementCounters(expr, FaultID.InterOpImportJsDataCompare); + const autofix = this.autofixer?.fixInteropOperators(expr); + this.incrementCounters(expr, FaultID.InterOpImportJsDataCompare, autofix); } }; @@ -2576,45 +2426,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { 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); - } - } - } + this.handleSdkGlobalApi(tsVarDecl); } private checkTypeFromSdk(type: ts.TypeNode | undefined): void { @@ -2917,12 +2729,25 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.incrementCounters(node, FaultID.CatchWithUnsupportedType, autofix); } - if ( - this.options.arkts2 && - tsCatch.variableDeclaration && - TsUtils.isAnyType(this.tsTypeChecker.getTypeAtLocation(tsCatch.variableDeclaration)) - ) { - this.incrementCounters(node, FaultID.TsLikeCatchType); + if (this.options.arkts2 && tsCatch.variableDeclaration?.name) { + const varDeclName = tsCatch.variableDeclaration?.name.getText(); + tsCatch.block.statements.forEach((statement) => { + this.checkTsLikeCatchType(statement, varDeclName); + }); + } + } + + private checkTsLikeCatchType(node: ts.Node, variableDeclarationName: string): void { + if (!node) { + return; + } + for (const child of node.getChildren()) { + if (ts.isPropertyAccessExpression(child)) { + if (child.expression.getText() === variableDeclarationName && !ERROR_PROP_LIST.has(child.name.getText())) { + this.incrementCounters(child, FaultID.TsLikeCatchType); + } + } + this.checkTsLikeCatchType(child, variableDeclarationName); } } @@ -3035,6 +2860,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { methodName?: string ): boolean { return heritageClause.types.some((type) => { + const parentName = ts.isPropertyAccessExpression(type.expression) ? + type.expression.name.text : + type.expression.getText(); const fullTypeName = TypeScriptLinter.findFinalExpression(type).getText(); const sdkInfos = this.interfaceMap.get(fullTypeName); if (!sdkInfos || sdkInfos.size === 0) { @@ -3046,7 +2874,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return false; } - if (!methodName) { + if (!methodName && sdkInfo.parent_api[0].api_name === parentName) { this.processSdkInfoWithMembers(sdkInfo, tsClassDecl.members, tsClassDecl); return false; } @@ -3108,12 +2936,12 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { ): boolean { const apiParamCout = sdkFuncArgs.length; const memberParamCout = memberParams.length; - if (apiParamCout > memberParamCout && sdkFuncArgs[memberParamCout + 1]) { + if (apiParamCout > memberParamCout && sdkFuncArgs[memberParamCout]) { return false; } for (let i = 0; i < apiParamCout; i++) { - const typeName = memberParams[i].type?.getText(); + const typeName = memberParams[i]?.type?.getText(); if (!typeName?.match(sdkFuncArgs[i].type)) { return false; } @@ -3496,6 +3324,22 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } this.checkDefaultParamBeforeRequired(tsMethodDecl); this.handleMethodInherit(tsMethodDecl); + this.handleSdkGlobalApi(tsMethodDecl); + this.handleLimitedVoidFunction(tsMethodDecl); + } + + private handleLimitedVoidFunction(node: ts.FunctionLikeDeclaration): void { + const typeNode = node.type; + if (!typeNode || !ts.isUnionTypeNode(typeNode)) { + return; + } + const containsVoid = typeNode.types.some((t) => { + return t.kind === ts.SyntaxKind.VoidKeyword; + }); + if (this.options.arkts2 && containsVoid) { + const autofix = this.autofixer?.fixLimitedVoidTypeFunction(node); + this.incrementCounters(typeNode, FaultID.LimitedVoidType, autofix); + } } private checkDefaultParamBeforeRequired(node: ts.FunctionLikeDeclarationBase): void { @@ -3533,42 +3377,73 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } const classType = this.tsTypeChecker.getTypeAtLocation(classDecl); - const baseTypes = classType.getBaseTypes(); - if (!baseTypes || baseTypes.length === 0) { + const allBaseTypes = this.getAllBaseTypes(classType, classDecl); + if (!allBaseTypes || allBaseTypes.length === 0) { return; } const methodName = node.name.text; - for (const baseType of baseTypes) { + for (const baseType of allBaseTypes) { const baseMethod = baseType.getProperty(methodName); if (!baseMethod) { continue; } - const baseMethodDecl = baseMethod.declarations?.find(ts.isMethodDeclaration); + const baseMethodDecl = baseMethod.declarations?.find((d) => { + return ts.isMethodDeclaration(d) || ts.isMethodSignature(d); + }) as ts.MethodDeclaration | ts.MethodSignature | undefined; + if (!baseMethodDecl) { continue; } - // Check parameter compatibility this.checkMethodParameters(node, baseMethodDecl); - // Check return type compatibility this.checkMethodReturnType(node, baseMethodDecl); break; } } + private getAllBaseTypes(type: ts.Type, classDecl: ts.ClassDeclaration): ts.Type[] | undefined { + const baseClasses = type.getBaseTypes() || []; + if (!classDecl.heritageClauses) { + return baseClasses; + } + const interfaces: ts.Type[] = []; + for (const clause of classDecl.heritageClauses) { + if (clause.token !== ts.SyntaxKind.ImplementsKeyword) { + continue; + } + for (const typeNode of clause.types) { + const interfaceType = this.tsTypeChecker.getTypeAtLocation(typeNode); + interfaces.push(interfaceType); + const parentInterfaces = interfaceType.getBaseTypes(); + if (parentInterfaces) { + interfaces.push(...parentInterfaces); + } + } + } + return [...baseClasses, ...interfaces]; + } + /** - * Checks if child parameters accept at least as many types as parent parameters. - * (Child parameter type should be same or wider than parent.) + * Checks method parameter compatibility + * Derived parameter types must be same or wider than base (contravariance principle) */ - private checkMethodParameters(derivedMethod: ts.MethodDeclaration, baseMethod: ts.MethodDeclaration): void { + private checkMethodParameters( + derivedMethod: ts.MethodDeclaration, + baseMethod: ts.MethodDeclaration | ts.MethodSignature + ): void { const derivedParams = derivedMethod.parameters; const baseParams = baseMethod.parameters; + if (derivedParams.length !== baseParams.length) { + this.incrementCounters(derivedMethod.name, FaultID.MethodInheritRule); + return; + } + const paramCount = Math.min(derivedParams.length, baseParams.length); for (let i = 0; i < paramCount; i++) { @@ -3582,15 +3457,27 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } /** - * Checks return type covariance between base and derived methods. - * (Derived return type must be assignable to base return type.) + * Checks return type compatibility + * Derived return type must be same or narrower than base (covariance principle) */ - private checkMethodReturnType(derivedMethod: ts.MethodDeclaration, baseMethod: ts.MethodDeclaration): void { - if (!baseMethod.type || !derivedMethod.type) { + private checkMethodReturnType( + derivedMethod: ts.MethodDeclaration, + baseMethod: ts.MethodDeclaration | ts.MethodSignature + ): void { + if ( + this.IsVoidTypeOnActualReturnType(baseMethod) && + derivedMethod.type && + !this.IsVoidTypeOnActualReturnType(derivedMethod) + ) { + this.incrementCounters(derivedMethod.type, FaultID.MethodInheritRule); return; } - const baseReturnType = this.tsTypeChecker.getTypeAtLocation(baseMethod.type); + 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)) { @@ -3598,6 +3485,19 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + private IsVoidTypeOnActualReturnType(method: ts.MethodDeclaration | ts.MethodSignature): boolean | undefined { + let type: ts.Type | undefined; + if (method.type) { + type = this.tsTypeChecker.getTypeAtLocation(method.type); + } else { + const signature = this.tsTypeChecker.getSignatureFromDeclaration(method); + if (signature) { + type = this.tsTypeChecker.getReturnTypeOfSignature(signature); + } + } + return type && TsUtils.isVoidType(type); + } + /** * 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. @@ -3847,7 +3747,6 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { private handleGlobalThisCase(node: ts.Identifier, isArkTs2: boolean | undefined): void { let faultId = FaultID.GlobalThis; - let autofix: Autofix[] | undefined; let targetNode: ts.Node = node; if (!isArkTs2) { @@ -3864,14 +3763,12 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { 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); + this.incrementCounters(targetNode, faultId); } // hard-coded alternative to TypeScriptLinter.advancedClassChecks @@ -3963,12 +3860,20 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + this.handleIllegalSymbolUsage(tsIdentifier, tsIdentSym); + } + + private handleIllegalSymbolUsage(tsIdentifier: ts.Identifier, tsIdentSym: ts.Symbol): void { if (tsIdentSym.flags & ts.SymbolFlags.ValueModule) { this.incrementCounters(tsIdentifier, FaultID.NamespaceAsObject); } else { - // missing EnumAsObject - const faultId = this.options.arkts2 ? FaultID.ClassAsObjectError : FaultID.ClassAsObject; - this.incrementCounters(tsIdentifier, faultId); + const typeName = tsIdentifier.getText(); + const isWrapperObject = typeName === 'Number' || typeName === 'String' || typeName === 'Boolean'; + + if (!isWrapperObject) { + const faultId = this.options.arkts2 ? FaultID.ClassAsObjectError : FaultID.ClassAsObject; + this.incrementCounters(tsIdentifier, faultId); + } } } @@ -4093,7 +3998,6 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } - const argExpr = TypeScriptLinter.getUnwrappedArgumentExpression(expr.argumentExpression); const validStringLiteralTypes = [ STRINGLITERAL_INT, STRINGLITERAL_BYTE, @@ -4104,19 +4008,14 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const argTypeString = this.tsTypeChecker.typeToString(argType); if (this.tsUtils.isNumberLikeType(argType)) { - this.handleNumericArgument(argExpr, expr.argumentExpression, argType); + this.handleNumericArgument(expr.argumentExpression, argType); } else if (!validStringLiteralTypes.includes(argTypeString)) { - this.incrementCounters(argExpr, FaultID.ArrayIndexExprType); + this.incrementCounters(expr.argumentExpression, FaultID.ArrayIndexExprType); } } - private static getUnwrappedArgumentExpression(argExpr: ts.Expression): ts.Expression { - return argExpr.kind === ts.SyntaxKind.AsExpression ? (argExpr as ts.AsExpression).expression : argExpr; - } - - private handleNumericArgument(argExpr: ts.Expression, asExpr: ts.Expression, argType: ts.Type): void { + private handleNumericArgument(argExpr: 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); @@ -4125,7 +4024,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const containsDot = argText.includes('.'); if (!isInteger || containsDot) { - const autofix = this.autofixer?.fixArrayIndexExprType(isAsExpression ? asExpr : argExpr); + const autofix = this.autofixer?.fixArrayIndexExprType(argExpr); this.incrementCounters(argExpr, FaultID.ArrayIndexExprType, autofix); } } else if (this.tsTypeChecker.typeToString(argType) === 'number') { @@ -4479,9 +4378,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleInteropForCallJSExpression(tsCallExpr, calleeSym, callSignature); this.handleNoTsLikeFunctionCall(tsCallExpr); this.handleObjectLiteralInFunctionArgs(tsCallExpr); - this.handleTaskPoolDeprecatedUsages(tsCallExpr); - this.handleSdkDuplicateDeclName(tsCallExpr); + this.handleSdkGlobalApi(tsCallExpr); this.handleObjectLiteralAssignmentToClass(tsCallExpr); + this.checkRestrictedAPICall(tsCallExpr); } handleNoTsLikeFunctionCall(callExpr: ts.CallExpression): void { @@ -4556,13 +4455,11 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (!this.options.arkts2 || !this.useStatic) { return; } - - // Typeof expressions is handled by a different rule, early return if parent is a typeof expression - if (ts.isTypeOfExpression(tsCallExpr.parent)) { + if (ts.isAwaitExpression(tsCallExpr.parent) || ts.isTypeOfExpression(tsCallExpr.parent)) { return; } - if (!callSignature || TypeScriptLinter.isDeclaredInArkTs2(callSignature)) { + if (!callSignature || this.isDeclaredInArkTs2(callSignature)) { return; } @@ -4589,7 +4486,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } - if (!TypeScriptLinter.isDeclaredInArkTs2(callSignature)) { + if (!this.isDeclaredInArkTs2(callSignature)) { return; } @@ -4648,7 +4545,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return false; } - private static isDeclaredInArkTs2(callSignature: ts.Signature): boolean | undefined { + private isDeclaredInArkTs2(callSignature: ts.Signature): boolean | undefined { const declarationSourceFile = callSignature?.declaration?.getSourceFile(); if (!declarationSourceFile) { return undefined; @@ -4656,13 +4553,44 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (!declarationSourceFile.statements) { return undefined; } - // check for 'use static' at the start of the file this function declared at - if (declarationSourceFile.statements[0].getText() === USE_STATIC) { + + if (this.tsUtils.isArkts12File(declarationSourceFile)) { return true; } return false; } + private checkRestrictedAPICall(node: ts.Node): void { + if (ts.isCallExpression(node)) { + if (TypeScriptLinter.isReflectAPICall(node)) { + this.incrementCounters(node.parent, FaultID.InteropCallReflect); + return; + } + + const signature = this.tsTypeChecker.getResolvedSignature(node); + if (signature) { + this.checkForForbiddenAPIs(signature, node); + } + } + } + + static isReflectAPICall(callExpr: ts.CallExpression): boolean { + if (ts.isPropertyAccessExpression(callExpr.expression)) { + const expr = callExpr.expression.expression; + if (ts.isIdentifier(expr) && expr.text === REFLECT_LITERAL) { + return true; + } + } + + if (ts.isElementAccessExpression(callExpr.expression)) { + const expr = callExpr.expression.expression; + if (ts.isIdentifier(expr) && expr.text === REFLECT_LITERAL) { + return true; + } + } + return false; + } + private checkForForbiddenAPIs(callSignature: ts.Signature, tsCallExpr: ts.CallExpression): void { if (!callSignature.declaration) { return; @@ -4677,6 +4605,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (!TypeScriptLinter.isFunctionLike(functionDeclaration)) { return; } + switch (TypeScriptLinter.containsForbiddenAPI(functionDeclaration)) { case REFLECT_LITERAL: this.incrementCounters(tsCallExpr.parent, FaultID.InteropCallReflect); @@ -4780,29 +4709,92 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } const resolvedTypeArgs = signDecl.typeArguments; - const startTypeArg = callLikeExpr.typeArguments?.length ?? 0; + const providedTypeArgs = callLikeExpr.typeArguments; + const startTypeArg = providedTypeArgs?.length ?? 0; + let shouldReportError = startTypeArg !== resolvedTypeArgs.length; if (this.options.arkts2 && callLikeExpr.kind === ts.SyntaxKind.NewExpression) { - if (startTypeArg !== resolvedTypeArgs.length) { + shouldReportError = this.shouldReportGenericTypeArgsError( + callLikeExpr, + resolvedTypeArgs, + providedTypeArgs, + startTypeArg, + shouldReportError + ); + if (shouldReportError) { const autofix = this.autofixer?.fixGenericCallNoTypeArgs(callLikeExpr); this.incrementCounters(callLikeExpr, FaultID.GenericCallNoTypeArgs, autofix); } } else { - for (let i = startTypeArg; i < resolvedTypeArgs.length; ++i) { - const typeNode = resolvedTypeArgs[i]; + this.checkForUnknownTypeInNonArkTS2(callLikeExpr, resolvedTypeArgs, startTypeArg); + } + } - /* - * if compiler infers 'unknown' type there are 2 possible cases: - * 1. Compiler unable to infer type from arguments and use 'unknown' - * 2. Compiler infer 'unknown' from arguments - * We report error in both cases. It is ok because we cannot use 'unknown' - * in ArkTS and already have separate check for it. - */ - if (typeNode.kind === ts.SyntaxKind.UnknownKeyword) { - this.incrementCounters(callLikeExpr, FaultID.GenericCallNoTypeArgs); - break; - } + private checkForUnknownTypeInNonArkTS2( + callLikeExpr: ts.CallExpression | ts.NewExpression, + resolvedTypeArgs: ts.NodeArray, + startTypeArg: number + ): void { + for (let i = startTypeArg; i < resolvedTypeArgs.length; ++i) { + const typeNode = resolvedTypeArgs[i]; + + /* + * if compiler infers 'unknown' type there are 2 possible cases: + * 1. Compiler unable to infer type from arguments and use 'unknown' + * 2. Compiler infer 'unknown' from arguments + * We report error in both cases. It is ok because we cannot use 'unknown' + * in ArkTS and already have separate check for it. + */ + if (typeNode.kind === ts.SyntaxKind.UnknownKeyword) { + this.incrementCounters(callLikeExpr, FaultID.GenericCallNoTypeArgs); + break; + } + } + } + + private shouldReportGenericTypeArgsError( + callLikeExpr: ts.CallExpression | ts.NewExpression, + resolvedTypeArgs: ts.NodeArray, + providedTypeArgs: ts.NodeArray | undefined, + startTypeArg: number, + initialErrorState: boolean + ): boolean { + const typeParameters = this.getOriginalTypeParameters(callLikeExpr); + if (!typeParameters || typeParameters.length === 0) { + return initialErrorState; + } + const optionalParamsCount = typeParameters.filter((param, index) => { + return param.default && (!providedTypeArgs || index >= providedTypeArgs.length); + }).length; + if (optionalParamsCount === 0) { + return initialErrorState; + } + return startTypeArg + optionalParamsCount !== resolvedTypeArgs.length; + } + + private getOriginalTypeParameters( + callLikeExpr: ts.CallExpression | ts.NewExpression + ): ts.TypeParameterDeclaration[] | undefined { + const typeChecker = this.tsTypeChecker; + const expressionType = typeChecker.getTypeAtLocation(callLikeExpr.expression); + const declarations = expressionType.symbol?.declarations; + if (!declarations || declarations.length === 0) { + return undefined; + } + for (const decl of declarations) { + if (ts.isFunctionDeclaration(decl) && decl.typeParameters) { + return [...decl.typeParameters]; + } + if (ts.isMethodDeclaration(decl) && decl.typeParameters) { + return [...decl.typeParameters]; + } + if (ts.isClassDeclaration(decl) && decl.typeParameters) { + return [...decl.typeParameters]; + } + if (ts.isInterfaceDeclaration(decl) && decl.typeParameters) { + return [...decl.typeParameters]; } } + return undefined; } private isNonGenericClass(expression: ts.NewExpression): boolean { @@ -5007,17 +4999,13 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { ); } - private checkConstrutorAccess(newExpr: ts.NewExpression): void { + private checkConstrutorAccess(propertyAccessExpr: ts.PropertyAccessExpression): 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); + if (propertyAccessExpr.name.text === 'constructor') { + this.incrementCounters(propertyAccessExpr, FaultID.NoConstructorOnClass); } } @@ -5036,9 +5024,19 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } const type = this.tsTypeChecker.getTypeAtLocation(calleeExpr); - if (type.isClassOrInterface()) { - this.incrementCounters(calleeExpr, FaultID.ConstructorIfaceFromSdk); + if (!type.symbol) { + return; + } + const typeDeclarations = type.symbol.declarations; + if (!typeDeclarations || typeDeclarations.length === 0) { + return; + } + + if (!ts.isInterfaceDeclaration(typeDeclarations[0])) { + return; } + + this.incrementCounters(calleeExpr, FaultID.ConstructorIfaceFromSdk); } private handleNewExpression(node: ts.Node): void { @@ -5046,8 +5044,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.checkForInterfaceInitialization(tsNewExpr); this.handleSharedArrayBuffer(tsNewExpr); - this.handleSdkDuplicateDeclName(tsNewExpr); - this.checkConstrutorAccess(tsNewExpr); + this.handleSdkGlobalApi(tsNewExpr); this.checkCreatingPrimitiveTypes(tsNewExpr); if (this.options.advancedClassChecks || this.options.arkts2) { @@ -5146,6 +5143,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.options.arkts2 && this.tsUtils.needToDeduceStructuralIdentity(targetType, exprType, tsAsExpr.expression, true) ) { + if (this.isExemptedAsExpression(tsAsExpr)) { + return; + } if (!this.tsUtils.isObject(exprType)) { this.incrementCounters(node, FaultID.StructuralIdentity); } @@ -5153,6 +5153,42 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleAsExpressionImport(tsAsExpr); this.handleNoTuplesArrays(node, targetType, exprType); this.handleObjectLiteralAssignmentToClass(tsAsExpr); + this.handleArrayTypeImmutable(tsAsExpr, exprType, targetType); + } + + private isExemptedAsExpression(node: ts.AsExpression): boolean { + if (!ts.isElementAccessExpression(node.expression)) { + return false; + } + + const sourceType = this.tsTypeChecker.getTypeAtLocation(node.expression); + const targetType = this.tsTypeChecker.getTypeAtLocation(node.type); + const isRecordIndexAccess = (): boolean => { + const exprType = this.tsTypeChecker.getTypeAtLocation(node.expression); + const hasNumberIndex = !!exprType.getNumberIndexType(); + const hasStringIndex = !!exprType.getStringIndexType(); + const hasBooleanIndex = !!exprType.getProperty('true') || !!exprType.getProperty('false'); + + return hasNumberIndex || hasStringIndex || hasBooleanIndex; + }; + + if (isRecordIndexAccess()) { + const targetSymbol = targetType.getSymbol(); + if (targetSymbol && targetSymbol.getName() === 'Array') { + return true; + } + } + const primitiveFlags = ts.TypeFlags.Number | ts.TypeFlags.String | ts.TypeFlags.Boolean; + const objectFlag = ts.TypeFlags.Object; + return ( + sourceType.isUnion() && + sourceType.types.some((t) => { + return t.flags & primitiveFlags; + }) && + sourceType.types.some((t) => { + return t.flags & objectFlag; + }) + ); } private handleAsExpressionImport(tsAsExpr: ts.AsExpression): void { @@ -5230,7 +5266,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } - private handleSharedArrayBuffer(node: ts.TypeReferenceNode | ts.NewExpression): void { + private handleSharedArrayBuffer( + node: ts.TypeReferenceNode | ts.NewExpression | ts.ExpressionWithTypeArguments + ): void { if (!this.options.arkts2) { return; } @@ -5239,22 +5277,40 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (!ts.isIdentifier(typeNameIdentifier) || typeNameIdentifier.getText() !== ESLIB_SHAREDARRAYBUFFER) { return; } + const symbol = this.tsUtils.trueSymbolAtLocation(typeNameIdentifier); + if (!symbol) { + return; + } + + const isImported = this.sourceFile.statements.some((stmt) => { + if (!ts.isImportDeclaration(stmt)) { + return false; + } + const importClause = stmt.importClause; + if (!importClause?.namedBindings || !ts.isNamedImports(importClause.namedBindings)) { + return false; + } - const decls = this.tsUtils.trueSymbolAtLocation(typeNameIdentifier)?.getDeclarations(); + const elements = importClause.namedBindings.elements.some((element) => { + return element.name.text === ESLIB_SHAREDARRAYBUFFER; + }); + return elements; + }); + if (isImported) { + return; + } + const decls = symbol.getDeclarations(); const isSharedMemoryEsLib = decls?.some((decl) => { const srcFileName = decl.getSourceFile().fileName; return srcFileName.endsWith(ESLIB_SHAREDMEMORY_FILENAME); }); + if (!isSharedMemoryEsLib || this.hasLocalSharedArrayBufferClass()) { 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); - } + + const autofix = this.autofixer?.replaceNode(typeNameIdentifier, 'ArrayBuffer'); + this.incrementCounters(typeNameIdentifier, FaultID.SharedArrayBufferDeprecated, autofix); } private hasLocalSharedArrayBufferClass(): boolean { @@ -5268,7 +5324,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleBuiltinCtorCallSignature(typeRef); this.handleSharedArrayBuffer(typeRef); - this.handleSdkDuplicateDeclName(typeRef); + this.handleSdkGlobalApi(typeRef); this.handleSdkConstructorIface(typeRef); @@ -5298,6 +5354,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } this.checkNoEnumProp(typeRef); + if (ts.isQualifiedName(typeRef.typeName)) { + this.handleSdkForConstructorFuncs(typeRef.typeName); + } } private checkNoEnumProp(typeRef: ts.TypeReferenceNode): void { @@ -5401,7 +5460,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const faultId = this.options.arkts2 ? FaultID.EsValueTypeError : FaultID.EsValueType; this.incrementCounters(tsTypeExpr, faultId); } - this.handleSdkDuplicateDeclName(tsTypeExpr); + this.handleSdkGlobalApi(tsTypeExpr); } private handleComputedPropertyName(node: ts.Node): void { @@ -5655,6 +5714,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { private handleConstructorDeclaration(node: ts.Node): void { const ctorDecl = node as ts.ConstructorDeclaration; + this.checkDefaultParamBeforeRequired(ctorDecl); this.handleTSOverload(ctorDecl); const paramProperties = ctorDecl.parameters.filter((x) => { return this.tsUtils.hasAccessModifier(x); @@ -5931,6 +5991,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { ): void { const rhsType = this.tsTypeChecker.getTypeAtLocation(rhsExpr); this.handleNoTuplesArrays(field, lhsType, rhsType); + this.handleArrayTypeImmutable(field, lhsType, rhsType, rhsExpr); // check that 'sendable typeAlias' is assigned correctly if (this.tsUtils.isWrongSendableFunctionAssignment(lhsType, rhsType)) { this.incrementCounters(field, FaultID.SendableFunctionAssignment); @@ -5941,6 +6002,19 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } if (this.tsUtils.needToDeduceStructuralIdentity(lhsType, rhsType, rhsExpr, isStrict)) { + if (ts.isNewExpression(rhsExpr) && ts.isIdentifier(rhsExpr.expression) && rhsExpr.expression.text === 'Promise') { + const isReturnStatement = ts.isReturnStatement(rhsExpr.parent); + const enclosingFunction = ts.findAncestor(rhsExpr, ts.isFunctionLike); + const isAsyncFunction = + enclosingFunction && + (enclosingFunction.modifiers?.some((m) => { + return m.kind === ts.SyntaxKind.AsyncKeyword; + }) || + false); + if (isReturnStatement && isAsyncFunction) { + return; + } + } this.incrementCounters(field, FaultID.StructuralIdentity); } } @@ -6044,8 +6118,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } const typeNode = node.type; - if (typeNode && typeNode.kind === ts.SyntaxKind.VoidKeyword) { - this.incrementCounters(typeNode, FaultID.LimitedVoidType); + if (typeNode && TsUtils.typeContainsVoid(typeNode)) { + const autofix = this.autofixer?.fixLimitedVoidType(node); + this.incrementCounters(typeNode, FaultID.LimitedVoidType, autofix); } } @@ -6059,12 +6134,44 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } const signature = this.tsTypeChecker.getResolvedSignature(node); - if (signature) { - const returnType = this.tsTypeChecker.getReturnTypeOfSignature(signature); - if (this.tsTypeChecker.typeToString(returnType) === 'void') { + if (!signature) { + return; + } + + const returnType = this.tsTypeChecker.getReturnTypeOfSignature(signature); + if (this.tsTypeChecker.typeToString(returnType) !== 'void') { + return; + } + + if (ts.isReturnStatement(node.parent)) { + const functionLike = TypeScriptLinter.findContainingFunction(node); + if (functionLike && TypeScriptLinter.isRecursiveCall(node, functionLike)) { this.incrementCounters(node, FaultID.LimitedVoidType); } + return; + } + + this.incrementCounters(node, FaultID.LimitedVoidType); + } + + private static findContainingFunction(node: ts.Node): ts.FunctionLikeDeclaration | undefined { + while (node) { + if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)) { + return node; + } + node = node.parent; } + return undefined; + } + + // Helper function to check if a call is recursive + private static isRecursiveCall(callExpr: ts.CallExpression, fn: ts.FunctionLikeDeclaration): boolean { + return ( + ts.isIdentifier(callExpr.expression) && + ts.isFunctionDeclaration(fn) && + !!fn.name && + fn.name.text === callExpr.expression.text + ); } private handleArrayType(arrayType: ts.Node): void { @@ -6102,8 +6209,8 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (!this.options.arkts2) { return; } - const autofix = this.autofixer?.fixDebuggerStatement(node as ts.DebuggerStatement); - this.incrementCounters(node, FaultID.DebuggerStatement, autofix); + + this.incrementCounters(node, FaultID.DebuggerStatement); } private handleTSOverload(decl: ts.FunctionDeclaration | ts.MethodDeclaration | ts.ConstructorDeclaration): void { @@ -6450,6 +6557,67 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + private handleNoTuplesArraysForPropertyAccessExpression(node: ts.PropertyAccessExpression): void { + if (!this.options.arkts2) { + return; + } + const lhsType = this.tsTypeChecker.getTypeAtLocation(node.expression); + if (this.tsUtils.isOrDerivedFrom(lhsType, TsUtils.isTuple)) { + if (ARRAY_API_LIST.includes(node.name.text)) { + this.incrementCounters(node, FaultID.NoTuplesArrays); + } + } + } + + private handleArrayTypeImmutable(node: ts.Node, lhsType: ts.Type, rhsType: ts.Type, rhsExpr?: ts.Expression): void { + if (!this.options.arkts2) { + return; + } + if ( + !( + this.tsUtils.isOrDerivedFrom(lhsType, this.tsUtils.isArray) && + this.tsUtils.isOrDerivedFrom(rhsType, this.tsUtils.isArray) && + lhsType !== rhsType + ) + ) { + return; + } + + const rhsTypeStr = this.tsTypeChecker.typeToString(rhsType); + let lhsTypeStr = this.tsTypeChecker.typeToString(lhsType); + if (rhsExpr && (this.isNullOrEmptyArray(rhsExpr) || ts.isArrayLiteralExpression(rhsExpr))) { + return; + } + + if (ts.isAsExpression(node) && ts.isArrayLiteralExpression(node.expression)) { + node.expression.elements.forEach((elem) => { + if (elem.kind === ts.SyntaxKind.FalseKeyword || elem.kind === ts.SyntaxKind.TrueKeyword) { + lhsTypeStr = rhsTypeStr.replace(elem.getText(), 'boolean'); + } + }); + } + if (lhsTypeStr !== rhsTypeStr) { + this.incrementCounters(node, FaultID.ArrayTypeImmutable); + } + } + + private isNullOrEmptyArray(expr: ts.Expression): boolean { + if (ts.isNewExpression(expr)) { + const constructorSym = this.tsTypeChecker.getSymbolAtLocation(expr.expression); + if (constructorSym?.name === 'Array') { + if (!expr.arguments || expr.arguments.length === 0) { + return true; + } + if (expr.arguments.length === 1) { + const argType = this.tsTypeChecker.getTypeAtLocation(expr.arguments[0]); + return !!(argType.flags & ts.TypeFlags.NumberLike); + } + } + } + + return false; + } + private handleExponentOperation(node: ts.Node): void { if (!this.options.arkts2) { return; @@ -6467,6 +6635,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { !ts.isNonNullExpression(node) || !ts.isNonNullExpression(node.expression) || ts.isNonNullExpression(node.parent) || + ts.isPropertyAccessExpression(node.parent) || ts.isNonNullExpression(node.expression.expression) ) { return; @@ -6474,26 +6643,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const statement = ts.findAncestor(node, ts.isExpressionStatement); if (statement && this.isCustomComponent(statement)) { - let currentParam: ts.Identifier | undefined; - if (ts.isPropertyAccessExpression(node.expression.expression)) { - currentParam = node.expression.expression.name as ts.Identifier; - } - - let customParam: ts.Identifier | undefined; - if (ts.isPropertyAssignment(node.parent)) { - customParam = node.parent.name as ts.Identifier; - } - - if (!currentParam || !customParam) { - return; - } - - const originalExpr = node.parent.parent; - if (!ts.isObjectLiteralExpression(originalExpr)) { - return; - } - const autofix = this.autofixer?.fixCustomBidirectionalBinding(originalExpr, currentParam, customParam); - this.incrementCounters(node, FaultID.DoubleExclaBindingNotSupported, autofix); + this.handleCustomBidirectionalBinding(node, node.expression); } else { const autofix = this.autofixer?.fixNativeBidirectionalBinding(node, this.interfacesNeedToImport); this.incrementCounters(node, FaultID.DoubleExclaBindingNotSupported, autofix); @@ -6522,6 +6672,30 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return this.interfacesAlreadyImported.has(callExpr.expression.getText()); } + private handleCustomBidirectionalBinding(firstExpr: ts.NonNullExpression, secondExpr: ts.NonNullExpression): void { + let currentParam: ts.Identifier | undefined; + if (ts.isPropertyAccessExpression(secondExpr.expression)) { + currentParam = secondExpr.expression.name as ts.Identifier; + } + + let customParam: ts.Identifier | undefined; + if (ts.isPropertyAssignment(firstExpr.parent)) { + customParam = firstExpr.parent.name as ts.Identifier; + } + + if (!currentParam || !customParam) { + return; + } + + const originalExpr = firstExpr.parent.parent; + if (!ts.isObjectLiteralExpression(originalExpr)) { + return; + } + + const autofix = this.autofixer?.fixCustomBidirectionalBinding(originalExpr, currentParam, customParam); + this.incrementCounters(firstExpr, FaultID.DoubleExclaBindingNotSupported, autofix); + } + private handleDoubleDollar(node: ts.Node): void { if (!this.options.arkts2) { return; @@ -6764,8 +6938,11 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (parent.right.text !== node.text) { return; } - this.checkAsonUsage(parent.left); - + if (ts.isQualifiedName(parent.parent) && ASON_WHITE_SET.has(parent.parent.right.text)) { + this.checkAsonUsage(parent.left, true); + } else { + this.checkAsonUsage(parent.left, false); + } break; case ts.SyntaxKind.PropertyAccessExpression: if (!ts.isPropertyAccessExpression(parent)) { @@ -6774,20 +6951,26 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (parent.name.text !== node.text) { return; } - this.checkAsonUsage(parent.expression); - + if (ts.isPropertyAccessExpression(parent.parent) && ASON_WHITE_SET.has(parent.parent.name.text)) { + this.checkAsonUsage(parent.expression, true); + } else { + this.checkAsonUsage(parent.expression, false); + } break; default: } } - private checkAsonUsage(nodeToCheck: ts.Node): void { + private checkAsonUsage(nodeToCheck: ts.Node, needAutofix: boolean): void { if (!ts.isIdentifier(nodeToCheck)) { return; } + const declaration = this.tsUtils.getDeclarationNode(nodeToCheck); if (!declaration && nodeToCheck.text === ARKTS_UTILS_TEXT) { - this.incrementCounters(nodeToCheck, FaultID.LimitedStdLibNoASON); + const autofix = + needAutofix && this.autofixer ? this.autofixer.replaceNode(nodeToCheck.parent, JSON_TEXT) : undefined; + this.incrementCounters(nodeToCheck, FaultID.LimitedStdLibNoASON, autofix); return; } @@ -6803,7 +6986,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return fileName.startsWith(moduleName); }) ) { - this.incrementCounters(nodeToCheck, FaultID.LimitedStdLibNoASON); + const autofix = + needAutofix && this.autofixer ? this.autofixer.replaceNode(nodeToCheck.parent, JSON_TEXT) : undefined; + this.incrementCounters(nodeToCheck, FaultID.LimitedStdLibNoASON, autofix); } } @@ -6950,7 +7135,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { ); this.interfacesNeedToAlarm.forEach((identifier) => { - this.incrementCounters(identifier, FaultID.UIInterfaceImport, autofix); + const name = identifier.getText(); + const errorMsg = `The ArkUI interface "${name}" should be imported before it is used (arkui-modular-interface)`; + this.incrementCounters(identifier, FaultID.UIInterfaceImport, autofix, errorMsg); }); this.interfacesNeedToAlarm = []; @@ -7286,7 +7473,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } - if (!TypeScriptLinter.isDeclaredInArkTs2(callSignature)) { + if (!this.isDeclaredInArkTs2(callSignature)) { return; } @@ -7388,21 +7575,49 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isFunctionExpression(node); } - private handleSdkForConstructorFuncs(node: ts.PropertyAccessExpression): void { - if (!this.options.arkts2 || !node) { - return; + private static isThirdPartyBySymbol(symbol: ts.Symbol | undefined, apiList: ApiListItem): boolean { + if (!symbol) { + return false; } - const sdkInfos = this.interfaceMap.get(node.expression.getText()); - if (!sdkInfos || sdkInfos.size === 0) { - return; + const declaration = symbol.getDeclarations()?.[0]; + if (declaration && ts.isImportClause(declaration)) { + const importDecl = declaration.parent; + const importPath = TsUtils.removeOrReplaceQuotes(importDecl.moduleSpecifier.getText(), false); + const import_path = TypeScriptLinter.getLocalApiListItemByKey(SdkNameInfo.ImportPath, apiList); + if (import_path.includes(importPath)) { + return true; + } } + return false; + } - for (const sdkInfo of sdkInfos) { - const propertyName = node.name.getText(); - if (propertyName === sdkInfo.api_name) { - this.incrementCounters(node.name, FaultID.ConstructorTypesDeprecated); - } + private static getLocalApiListItemByKey(key: string, apiList: ApiListItem): string | string[] { + if (!apiList) { + return ''; } + if (SdkNameInfo.ImportPath === key) { + return apiList.import_path; + } + return ''; + } + + private handleSdkForConstructorFuncs(node: ts.PropertyAccessExpression | ts.QualifiedName): void { + if (!this.options.arkts2) { + return; + } + const rightNode = ts.isPropertyAccessExpression(node) ? node.name : node.right; + const leftNode = ts.isPropertyAccessExpression(node) ? node.expression : node.left; + const constructorFuncsInfos = Array.from(TypeScriptLinter.constructorFuncsSet); + constructorFuncsInfos.some((constructorFuncsInfo) => { + const api_name = constructorFuncsInfo.api_info.api_name; + if (api_name !== rightNode.getText()) { + return; + } + const parentSym = this.tsTypeChecker.getSymbolAtLocation(leftNode); + if (TypeScriptLinter.isThirdPartyBySymbol(parentSym, constructorFuncsInfo)) { + this.incrementCounters(rightNode, FaultID.ConstructorTypesDeprecated); + } + }); } private handleQuotedHyphenPropsDeprecated(node: ts.PropertyAccessExpression | ts.PropertyAssignment): void { @@ -7450,7 +7665,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } if (ts.isPropertySignature(node)) { - return this.tsTypeChecker.getTypeAtLocation(node.type!).getSymbol(); + return this.tsTypeChecker.getSymbolAtLocation(node); } const nodesWithResolvableType = [ @@ -7488,38 +7703,27 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { 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(); + return this.resolveTypeNoSymbol(typeNode); } 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)) { + + const symbol = this.tsUtils.trueSymbolAtLocation(typeNode.typeName); + if (symbol?.declarations && symbol.declarations.length > 0) { + const globalDeclaration = symbol.declarations[0]; + if (ts.isTypeAliasDeclaration(globalDeclaration)) { return this.resolveTypeNodeSymbol(globalDeclaration.type); + } else if (ts.isInterfaceDeclaration(globalDeclaration)) { + return this.processQuotedHyphenPropsDeprecatedOnInterfaceDeclaration(globalDeclaration); } } - return this.tsTypeChecker.getTypeAtLocation(typeNode).getSymbol(); } @@ -7604,8 +7808,14 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return undefined; } - private processApiNodeSdkDuplicateDeclName(apiName: string, errorNode: ts.Node): void { - const setApiListItem = TypeScriptLinter.globalApiInfo.get(SdkProblem.DeclWithDuplicateName); + private processApiNodeSdkGlobalApi(apiName: string, errorNode: ts.Node): void { + for (const [key, value] of globalApiAssociatedInfo) { + this.doProcessApiNodeSdkGlobalApi(apiName, errorNode, key, value); + } + } + + private doProcessApiNodeSdkGlobalApi(apiName: string, errorNode: ts.Node, key: string, faultId: number): void { + const setApiListItem = TypeScriptLinter.globalApiInfo.get(key); if (!setApiListItem) { return; } @@ -7628,11 +7838,11 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { }); if (matchedApi) { - this.incrementCounters(errorNode, FaultID.DuplicateDeclNameFromSdk); + this.incrementCounters(errorNode, faultId); } } - private handleSdkDuplicateDeclName( + private handleSdkGlobalApi( node: | ts.TypeReferenceNode | ts.NewExpression @@ -7643,75 +7853,86 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { | ts.BinaryExpression | ts.ExpressionWithTypeArguments | ts.Identifier + | ts.MethodDeclaration ): void { if (!this.options.arkts2) { return; } switch (node.kind) { case ts.SyntaxKind.TypeReference: - this.checkTypeReferenceForSdkDuplicateDeclName(node); + this.checkTypeReferenceForSdkGlobalApi(node); break; case ts.SyntaxKind.NewExpression: - this.checkNewExpressionForSdkDuplicateDeclName(node); + this.checkNewExpressionForSdkGlobalApi(node); break; case ts.SyntaxKind.Identifier: - this.checkHeritageClauseForSdkDuplicateDeclName(node); + this.checkHeritageClauseForSdkGlobalApi(node); break; case ts.SyntaxKind.VariableDeclaration: case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.Parameter: - this.checkDeclarationForSdkDuplicateDeclName(node); + this.checkDeclarationForSdkGlobalApi(node); break; case ts.SyntaxKind.CallExpression: - this.checkCallExpressionForSdkDuplicateDeclName(node); + this.checkCallExpressionForSdkGlobalApi(node); break; case ts.SyntaxKind.BinaryExpression: - this.checkBinaryExpressionForSdkDuplicateDeclName(node); + this.checkBinaryExpressionForSdkGlobalApi(node); + break; + case ts.SyntaxKind.MethodDeclaration: + this.checkMethodDeclarationForSdkGlobalApi(node); break; default: } } - private checkTypeReferenceForSdkDuplicateDeclName(node: ts.TypeReferenceNode): void { + private checkTypeReferenceForSdkGlobalApi(node: ts.TypeReferenceNode): void { const typeName = node.typeName; if (ts.isIdentifier(typeName)) { - this.processApiNodeSdkDuplicateDeclName(typeName.text, node); + this.processApiNodeSdkGlobalApi(typeName.text, node); } } - private checkNewExpressionForSdkDuplicateDeclName(node: ts.NewExpression): void { + private checkNewExpressionForSdkGlobalApi(node: ts.NewExpression): void { const expression = node.expression; if (ts.isIdentifier(expression)) { - this.processApiNodeSdkDuplicateDeclName(expression.text, expression); + this.processApiNodeSdkGlobalApi(expression.text, expression); } } - private checkHeritageClauseForSdkDuplicateDeclName(node: ts.Identifier): void { + private checkHeritageClauseForSdkGlobalApi(node: ts.Identifier): void { if (ts.isIdentifier(node)) { - this.processApiNodeSdkDuplicateDeclName(node.text, node); + this.processApiNodeSdkGlobalApi(node.text, node); } } - private checkDeclarationForSdkDuplicateDeclName( + private checkDeclarationForSdkGlobalApi( node: ts.VariableDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration ): void { const expression = node.initializer; if (expression && ts.isIdentifier(expression)) { - this.processApiNodeSdkDuplicateDeclName(expression.text, expression); + this.processApiNodeSdkGlobalApi(expression.text, expression); } } - private checkCallExpressionForSdkDuplicateDeclName(node: ts.CallExpression): void { + private checkCallExpressionForSdkGlobalApi(node: ts.CallExpression): void { if (ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)) { const expression = node.expression.expression; - this.processApiNodeSdkDuplicateDeclName(expression.text, expression); + this.processApiNodeSdkGlobalApi(expression.text, expression); } } - private checkBinaryExpressionForSdkDuplicateDeclName(node: ts.BinaryExpression): void { + private checkBinaryExpressionForSdkGlobalApi(node: ts.BinaryExpression): void { const expression = node.right; if (ts.isIdentifier(expression)) { - this.processApiNodeSdkDuplicateDeclName(expression.text, expression); + this.processApiNodeSdkGlobalApi(expression.text, expression); + } + } + + private checkMethodDeclarationForSdkGlobalApi(node: ts.MethodDeclaration): void { + const expression = node.name; + if (ts.isIdentifier(expression)) { + this.processApiNodeSdkGlobalApi(expression.text, expression); } } @@ -7721,9 +7942,10 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } if (node.token === ts.SyntaxKind.ExtendsKeyword || node.token === ts.SyntaxKind.ImplementsKeyword) { node.types.forEach((type) => { + this.handleSharedArrayBuffer(type); const expr = type.expression; if (ts.isIdentifier(expr)) { - this.processApiNodeSdkDuplicateDeclName(expr.text, expr); + this.processApiNodeSdkGlobalApi(expr.text, expr); } }); } @@ -7890,7 +8112,12 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } private fixJsImportCallExpression(callExpr: ts.CallExpression): void { - if (!this.options.arkts2 || !this.useStatic) { + if ( + !this.options.arkts2 || + !this.useStatic || + ts.isAwaitExpression(callExpr.parent) || + ts.isTypeOfExpression(callExpr.parent) + ) { return; } @@ -7956,34 +8183,25 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } // Try direct check first - if (this.tsUtils.isImportedFromJS(identifier)) { - const autofix = this.autofixer?.createReplacementForJsImportPropertyAccessExpression( - node as ts.PropertyAccessExpression - ); - - this.incrementCounters( - node, - TsUtils.isInsideIfCondition(node) ? FaultID.InteropJsObjectConditionJudgment : FaultID.InteropJsObjectUsage, - autofix - ); + if (!this.tsUtils.isImportedFromJS(identifier)) { 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); + const autofix = this.autofixer?.createReplacementForJsImportPropertyAccessExpression( + node as ts.PropertyAccessExpression + ); + if (!TsUtils.isInsideIfCondition(node)) { + return; } + this.incrementCounters(node, FaultID.InteropJsObjectConditionJudgment, autofix); } private fixJsImportElementAccessExpression(elementAccessExpr: ts.ElementAccessExpression): void { if (!this.options.arkts2 || !this.useStatic) { return; } - + if (!TypeScriptLinter.isInForLoopBody(elementAccessExpr)) { + return; + } const variableDeclaration = ts.isIdentifier(elementAccessExpr.expression) ? this.tsUtils.findVariableDeclaration(elementAccessExpr.expression) : undefined; @@ -8002,58 +8220,54 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } - const autofix = this.autofixer?.createReplacementJsImportElementAccessExpression( - elementAccessExpr, - elementAccessExpr.expression as ts.Identifier - ); + const autofix = this.autofixer?.fixJsImportElementAccessExpression(elementAccessExpr); this.incrementCounters(elementAccessExpr, FaultID.InteropJsObjectTraverseJsInstance, autofix); } - private handleTaskPoolDeprecatedUsages(node: ts.CallExpression): void { - if (!this.options.arkts2 || !this.useStatic) { - return; + private static isInForLoopBody(node: ts.Node): boolean { + let current: ts.Node | undefined = node.parent; + while (current) { + if (ts.isForStatement(current) || ts.isForInStatement(current) || ts.isForOfStatement(current)) { + return true; + } + current = current.parent; } + return false; + } - if (!ts.isPropertyAccessExpression(node.expression)) { + private handleTaskPoolDeprecatedUsages(propertyAccess: ts.PropertyAccessExpression): void { + if (!this.options.arkts2 || !this.useStatic) { return; } - - const propertyAccess = node.expression; - const objectExpr = propertyAccess.expression; - + const objectExpr = ts.isNewExpression(propertyAccess.expression) ? + propertyAccess.expression.expression : + propertyAccess.expression; // Step 1: Must be either setCloneList or setTransferList if (!TypeScriptLinter.isDeprecatedTaskPoolMethodCall(propertyAccess)) { return; } - - if (!ts.isIdentifier(objectExpr)) { + const variableDecl = TsUtils.getDeclaration(this.tsUtils.trueSymbolAtLocation(objectExpr)); + const isNoContinue = + !variableDecl || + !ts.isVariableDeclaration(variableDecl) || + !variableDecl?.initializer || + !ts.isNewExpression(variableDecl.initializer); + if (isNoContinue) { 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)) { + if (!this.isTaskPoolTaskCreation(taskpoolExpr)) { return; } - const faultId = propertyAccess.name.text === DEPRECATED_TASKPOOL_METHOD_SETCLONELIST ? FaultID.SetCloneListDeprecated : FaultID.SetTransferListDeprecated; - this.incrementCounters(node.parent, faultId); + this.incrementCounters(propertyAccess.name, 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 || @@ -8061,13 +8275,83 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { ); } - 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 isTaskPoolTaskCreation(taskpoolExpr: ts.Expression): boolean { + if ( + ts.isIdentifier(taskpoolExpr) || + ts.isPropertyAccessExpression(taskpoolExpr) && taskpoolExpr.name.text === STDLIB_TASK_CLASS_NAME + ) { + const objectExpr = ts.isIdentifier(taskpoolExpr) ? taskpoolExpr : taskpoolExpr.expression; + return this.isTaskPoolReferenceisTaskPoolImportForTaskPoolDeprecatedUsages(objectExpr); + } + return false; + } + + private isTaskPoolReferenceisTaskPoolImportForTaskPoolDeprecatedUsages(expr: ts.Expression): boolean { + if (ts.isIdentifier(expr)) { + const sym = this.tsTypeChecker.getSymbolAtLocation(expr); + const importChild = TsUtils.getDeclaration(sym); + if (!importChild) { + return false; + } + if (ts.isImportSpecifier(importChild)) { + return TypeScriptLinter.isTaskPoolImportForTaskPoolDeprecatedUsages(importChild); + } + if (ts.isImportClause(importChild) && importChild.name?.text === STDLIB_TASKPOOL_OBJECT_NAME) { + return TypeScriptLinter.checkModuleSpecifierForTaskPoolDeprecatedUsages(importChild.parent); + } + } + if (ts.isPropertyAccessExpression(expr)) { + return this.isTaskPoolReferenceOnPropertyAccessExpression(expr); + } + return false; + } + + private static checkModuleSpecifierForTaskPoolDeprecatedUsages(importDecl: ts.ImportDeclaration): boolean { + if (ts.isImportDeclaration(importDecl) && ts.isStringLiteral(importDecl.moduleSpecifier)) { + const moduleSpecifier = importDecl.moduleSpecifier; + return TASKPOOL_MODULES.includes(TsUtils.removeOrReplaceQuotes(moduleSpecifier.getText(), false)); + } + return false; + } + + private isTaskPoolReferenceOnPropertyAccessExpression(expr: ts.PropertyAccessExpression): boolean { + if (expr.name.text !== STDLIB_TASKPOOL_OBJECT_NAME || !ts.isIdentifier(expr.expression)) { + return false; + } + const sym = this.tsTypeChecker.getSymbolAtLocation(expr.expression); + const importChild = TsUtils.getDeclaration(sym); + if (importChild && ts.isNamespaceImport(importChild)) { + return TypeScriptLinter.checkModuleSpecifierForTaskPoolDeprecatedUsages(importChild.parent.parent); + } + return false; + } + + private static isTaskPoolImportForTaskPoolDeprecatedUsages(specifier: ts.ImportSpecifier): boolean { + const specifierName = specifier.propertyName ? specifier.propertyName : specifier.name; + if (STDLIB_TASKPOOL_OBJECT_NAME !== specifierName.text) { + return false; + } + const importDeclaration = specifier.parent.parent.parent; + return TypeScriptLinter.checkModuleSpecifierForTaskPoolDeprecatedUsages(importDeclaration); + } + + private handleForOfJsArray(node: ts.ForOfStatement): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + + const expr = node.expression; + if (!ts.isIdentifier(expr) || !this.tsUtils.isPossiblyImportedFromJS(expr)) { + return; + } + + const exprType = this.tsTypeChecker.getTypeAtLocation(expr); + + if (!this.tsUtils.isArray(exprType)) { + return; + } + + this.incrementCounters(node, FaultID.InteropJsObjectTraverseJsInstance); } private checkStdLibConcurrencyImport(importDeclaration: ts.ImportDeclaration): void { @@ -8242,7 +8526,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { defaultSymbol = this.tsUtils.trueSymbolAtLocation(importClause.name); } if (namedBindings) { - if (ts.isNamedImports(namedBindings)) { + if (ts.isNamedImports(namedBindings) && namedBindings.elements?.length > 0 && namedBindings.elements[0]?.name) { symbol = this.tsUtils.trueSymbolAtLocation(namedBindings.elements[0].name); } else if (ts.isNamespaceImport(namedBindings)) { symbol = this.tsUtils.trueSymbolAtLocation(namedBindings.name); @@ -8301,27 +8585,41 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { 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); + + if (!this.tsUtils.isJsImport(leftExpr) && !this.tsUtils.isJsImport(rightExpr)) { + return; } + + const autofix = this.autofixer?.fixInteropJsInstanceOfExpression(node); + this.incrementCounters(node, FaultID.InteropJsInstanceof, autofix); } 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); - } - } + if (!this.useStatic || !this.options.arkts2) { + return; } + + if (!ts.isPropertyAccessExpression(unaryExpr.operand)) { + return; + } + + const propertyAccess = unaryExpr.operand; + if (!this.tsUtils.isJsImport(propertyAccess.expression)) { + return; + } + + const autofix = this.autofixer?.fixUnaryIncrDecr(unaryExpr, propertyAccess); + + this.incrementCounters(unaryExpr, FaultID.InteropIncrementDecrement, autofix); } private handleObjectLiteralforUnionTypeInterop(node: ts.VariableDeclaration): void { @@ -8349,7 +8647,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return false; } for (const declaration of symbol.declarations ?? []) { - if (!TsUtils.isArkts12File(declaration.getSourceFile())) { + if (!this.tsUtils.isArkts12File(declaration.getSourceFile())) { return true; } } @@ -8414,7 +8712,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } const isFromArkTs2 = declarations.some((decl) => { - return TsUtils.isArkts12File(decl.getSourceFile()); + return this.tsUtils.isArkts12File(decl.getSourceFile()); }); if (isFromArkTs2) { @@ -8551,17 +8849,17 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return false; } - return TypeScriptLinter.isTypeFromArkts12(type); + return this.isTypeFromArkts12(type); } - private static isTypeFromArkts12(type: ts.Type): boolean { + private isTypeFromArkts12(type: ts.Type): boolean { const symbol = type?.getSymbol(); if (!symbol) { return false; } const isFromArkts12 = (symbol.declarations ?? []).some((decl) => { - return TsUtils.isArkts12File(decl.getSourceFile()); + return this.tsUtils.isArkts12File(decl.getSourceFile()); }); if (isFromArkts12) { @@ -8607,13 +8905,13 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const propType = this.tsTypeChecker.getTypeOfSymbolAtLocation(property, property.valueDeclaration); - if (TypeScriptLinter.isTypeFromArkts12(propType)) { + if (this.isTypeFromArkts12(propType)) { this.incrementCounters(prop.initializer, FaultID.InteropStaticObjectLiterals); } } private handleObjectLiteralAssignment(node: ts.VariableDeclaration): void { - if (TsUtils.isArkts12File(node.getSourceFile())) { + if (this.tsUtils.isArkts12File(node.getSourceFile())) { return; } @@ -8637,7 +8935,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } private handleObjectLiteralInFunctionArgs(node: ts.CallExpression): void { - if (TsUtils.isArkts12File(node.getSourceFile())) { + if (this.tsUtils.isArkts12File(node.getSourceFile())) { return; } const signature = this.tsTypeChecker.getResolvedSignature(node); @@ -8660,7 +8958,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const paramType = this.tsTypeChecker.getTypeOfSymbolAtLocation(param, param.valueDeclaration); - if (TypeScriptLinter.isTypeFromArkts12(paramType)) { + if (this.isTypeFromArkts12(paramType)) { this.incrementCounters(arg, FaultID.InteropStaticObjectLiterals); } } else if (this.isObjectLiteralAssignedToArkts12Type(arg)) { @@ -8670,7 +8968,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } private handleObjectLiteralInReturn(node: ts.ReturnStatement): void { - if (TsUtils.isArkts12File(node.getSourceFile())) { + if (this.tsUtils.isArkts12File(node.getSourceFile())) { return; } @@ -8696,7 +8994,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (functionNode?.type) { const returnType = this.tsTypeChecker.getTypeAtLocation(functionNode.type); - if (TypeScriptLinter.isTypeFromArkts12(returnType)) { + if (this.isTypeFromArkts12(returnType)) { this.incrementCounters(node.expression, FaultID.InteropStaticObjectLiterals); } } else if (this.isObjectLiteralAssignedToArkts12Type(node.expression)) { @@ -8723,23 +9021,32 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { 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)) { + if (ts.isEnumDeclaration(decl) && this.shouldIncrementCounters(node)) { this.incrementCounters(node, FaultID.UnsupportPropNameFromValue); return; } } } + private shouldIncrementCounters(node: ts.ElementAccessExpression): boolean { + const indexExpr = node.argumentExpression; + if (!indexExpr) { + return false; + } + if (ts.isStringLiteral(indexExpr) || ts.isNumericLiteral(indexExpr)) { + return true; + } + const type = this.tsTypeChecker.getTypeAtLocation(indexExpr); + const typeString = this.tsTypeChecker.typeToString(type); + return typeString === 'number' || typeString === 'string'; + } + private handleMakeObserved(node: ts.PropertyAccessExpression): void { if (!this.options.arkts2) { return; @@ -8794,15 +9101,16 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } + const autofix = this.autofixer?.fixPropDecorator(decorators[0], decoratorName); switch (decoratorName) { case PropDecoratorName.Prop: - this.incrementCounters(node, FaultID.PropDecoratorNotSupported); + this.incrementCounters(node, FaultID.PropDecoratorNotSupported, autofix); break; case PropDecoratorName.StorageProp: - this.incrementCounters(node, FaultID.StoragePropDecoratorNotSupported); + this.incrementCounters(node, FaultID.StoragePropDecoratorNotSupported, autofix); break; case PropDecoratorName.LocalStorageProp: - this.incrementCounters(node, FaultID.LocalStoragePropDecoratorNotSupported); + this.incrementCounters(node, FaultID.LocalStoragePropDecoratorNotSupported, autofix); break; default: } @@ -8872,101 +9180,255 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return targetTypes.includes(storageType.getText()); } - private handleAwaitExpression(node: ts.Node): void { - if (!this.options.arkts2 || !this.useStatic) { + private handlePropertyAssignmentForProp(node: ts.PropertyAssignment): void { + if (!this.options.arkts2) { 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; + + const callExpr = node.parent.parent; + if (!ts.isCallExpression(callExpr)) { + return; + } + + const structDecl = TsUtils.getDeclaration(this.tsTypeChecker.getSymbolAtLocation(callExpr.expression)); + if (!structDecl || !ts.isStructDeclaration(structDecl) || !structDecl.name) { + return; + } + + const variable = node.name; + if (!ts.isIdentifier(variable)) { + return; + } + + const targetNode = TypeScriptLinter.findVariableChangeNodeInStruct(variable, structDecl); + if (!targetNode) { + return; + } + + const targetDecl = TsUtils.getDeclaration(this.tsTypeChecker.getSymbolAtLocation(targetNode)); + if (!targetDecl || !ts.isPropertyDeclaration(targetDecl)) { + return; + } + + const decorators = ts.getDecorators(targetDecl); + if (!decorators || decorators.length === 0) { + return; + } + + const decorator = decorators[0]; + const decoratorName = TsUtils.getDecoratorName(decorator); + if (decoratorName === PropDecoratorName.Prop) { + this.incrementCounters(node, FaultID.PropNeedCallMethodForDeepCopy); + } + } + + private static findVariableChangeNodeInStruct( + variable: ts.Identifier, + structDecl: ts.StructDeclaration + ): ts.MemberName | undefined { + let changeNode: ts.MemberName | undefined; + + function traverse(node: ts.Node): void { + if (changeNode) { + return; } - return false; - }; + + if (ts.isPropertyAccessExpression(node)) { + if ( + node.expression.kind === ts.SyntaxKind.ThisKeyword && + node.name.getText() === variable.getText() && + (ts.findAncestor(node, ts.isPostfixUnaryExpression) || + ts.findAncestor(node, ts.isPrefixUnaryExpression) || + ts.findAncestor(node, ts.isBinaryExpression)) + ) { + changeNode = node.name; + } + } + + ts.forEachChild(node, traverse); + } + + traverse(structDecl); + return changeNode; + } + + private getIdentifierForAwaitExpr(awaitExpr: ts.AwaitExpression): IdentifierAndArguments { + void this; + + let ident: undefined | ts.Identifier; + let args: ts.NodeArray | undefined; + const expr = awaitExpr.expression; - checkAndReportJsImportAwait(expr); if (ts.isCallExpression(expr)) { - checkAndReportJsImportAwait(expr.expression); + if (ts.isIdentifier(expr.expression)) { + ident = expr.expression; + } + + if (ts.isPropertyAccessExpression(expr.expression)) { + if (ts.isIdentifier(expr.expression.name)) { + ident = expr.expression.name; + } + } + args = expr.arguments; + } else if (ts.isIdentifier(expr)) { + ident = expr; } + + return { ident, args }; + } + + private handleAwaitExpression(awaitExpr: ts.AwaitExpression): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + const { ident, args } = this.getIdentifierForAwaitExpr(awaitExpr); + if (!ident) { + return; + } + + if (!this.tsUtils.isJsImport(ident)) { + return; + } + + const declaration = this.tsUtils.getDeclarationNode(ident); + if (!declaration) { + return; + } + + if ( + ts.isFunctionDeclaration(declaration) && + TsUtils.hasModifier(declaration.modifiers, ts.SyntaxKind.AsyncKeyword) + ) { + const autofix = this.autofixer?.fixAwaitJsCallExpression(ident, args); + this.incrementCounters(awaitExpr, FaultID.NoAwaitJsPromise, autofix); + return; + } + + if (ts.isMethodDeclaration(declaration) && TsUtils.hasModifier(declaration.modifiers, ts.SyntaxKind.AsyncKeyword)) { + const autofix = this.autofixer?.fixAwaitJsMethodCallExpression(ident, args); + this.incrementCounters(awaitExpr, FaultID.NoAwaitJsPromise, autofix); + return; + } + + if (!ts.isVariableDeclaration(declaration)) { + return; + } + + const type = this.tsTypeChecker.getTypeAtLocation(declaration); + const typeString = this.tsTypeChecker.typeToString(type); + + if (typeString.split('<')[0] !== 'Promise') { + return; + } + + const autofix = this.autofixer?.fixAwaitJsPromise(ident); + this.incrementCounters(awaitExpr, FaultID.NoAwaitJsPromise, autofix); } private handleNotsLikeSmartType(classDecl: ts.ClassDeclaration): void { if (!this.options.arkts2) { return; } + const className = classDecl.name?.getText(); + const { staticProps, instanceProps } = this.collectClassProperties(classDecl); + classDecl.members.forEach((member) => { - if (ts.isMethodDeclaration(member)) { - this.checkMethod(member, className); + if (!ts.isMethodDeclaration(member) || !member.body) { + return; } + + const methodReturnType = this.tsTypeChecker.getTypeAtLocation(member); + this.checkMethodAndReturnStatements(member.body, className, methodReturnType, staticProps, instanceProps); }); } - 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); - }); - } + private checkMethodAndReturnStatements( + body: ts.Block, + className: string | undefined, + methodReturnType: ts.Type, + staticProps: Map, + instanceProps: Map + ): void { + body.forEachChild((node) => { + if (!ts.isReturnStatement(node) || !node.expression) { + return; + } - const isStaticPropertyAccess = (node: ts.Expression, className: string): boolean => { - return ( - ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === className - ); - }; + 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; + }; - const isInstancePropertyAccess = (node: ts.Expression): boolean => { - return ts.isPropertyAccessExpression(node) && node.expression.kind === ts.SyntaxKind.ThisKeyword; - }; + if (className && isStaticPropertyAccess(node.expression, className)) { + this.checkPropertyAccess(node, node.expression as ts.PropertyAccessExpression, staticProps, methodReturnType); + return; + } - this.checkReturnStatements(returnStatements, className, isStaticPropertyAccess, isInstancePropertyAccess); + if (isInstancePropertyAccess(node.expression)) { + this.checkPropertyAccess(node, node.expression as ts.PropertyAccessExpression, instanceProps, methodReturnType); + } + }); } - private visitMethodBody( - node: ts.Node, - variableDeclarations: Map, - returnStatements: ts.ReturnStatement[] + private checkPropertyAccess( + returnNode: ts.ReturnStatement, + propAccess: ts.PropertyAccessExpression, + propsMap: Map, + methodReturnType: ts.Type ): void { - if (ts.isVariableStatement(node)) { - node.declarationList.declarations.forEach((decl) => { - if (ts.isIdentifier(decl.name)) { - variableDeclarations.set(decl.name.text, decl.type); - } - }); - } + const propName = propAccess.name.getText(); + const propType = propsMap.get(propName); - if (ts.isReturnStatement(node)) { - returnStatements.push(node); + if (propType && this.isExactlySameType(propType, methodReturnType)) { + return; } - ts.forEachChild(node, (child) => { - this.visitMethodBody(child, variableDeclarations, returnStatements); - }); + this.incrementCounters(returnNode, FaultID.NoTsLikeSmartType); } - 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) { + private collectClassProperties(classDecl: ts.ClassDeclaration): { + staticProps: Map; + instanceProps: Map; + } { + const result = { + staticProps: new Map(), + instanceProps: new Map() + }; + + classDecl.members.forEach((member) => { + if (!ts.isPropertyDeclaration(member)) { return; } - const returnType = this.tsTypeChecker.getTypeAtLocation(returnStmt.expression); - if (className && isStaticPropertyAccess(returnStmt.expression, className) && returnType.isUnion()) { - this.incrementCounters(returnStmt, FaultID.NoTsLikeSmartType); - } + const propName = member.name.getText(); + const propType = this.tsTypeChecker.getTypeAtLocation(member); + const isStatic = member.modifiers?.some((m) => { + return m.kind === ts.SyntaxKind.StaticKeyword; + }); - if (isInstancePropertyAccess(returnStmt.expression) && returnType.isUnion()) { - this.incrementCounters(returnStmt, FaultID.NoTsLikeSmartType); + if (isStatic) { + result.staticProps.set(propName, propType); + } else { + result.instanceProps.set(propName, propType); } }); + + return result; + } + + private isExactlySameType(type1: ts.Type, type2: ts.Type): boolean { + if (type2.getCallSignatures().length > 0) { + const returnType = TsUtils.getFunctionReturnType(type2); + return returnType ? + this.tsTypeChecker.typeToString(type1) === this.tsTypeChecker.typeToString(returnType) : + false; + } + return this.tsTypeChecker.typeToString(type1) === this.tsTypeChecker.typeToString(type2); } private handleNumericBigintCompare(node: ts.BinaryExpression): void { @@ -8983,7 +9445,8 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return (type.flags & ts.TypeFlags.Number) !== 0 || (type.flags & ts.TypeFlags.NumberLiteral) !== 0; }; - const isBigIntAndNumberOperand = isNumber(leftType) && isBigInt(rightType) || isBigInt(leftType) && isNumber(rightType); + const isBigIntAndNumberOperand = + isNumber(leftType) && isBigInt(rightType) || isBigInt(leftType) && isNumber(rightType); if (isBigIntAndNumberOperand) { this.incrementCounters(node, FaultID.NumericBigintCompare); } @@ -9031,7 +9494,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (decorators) { for (const decorator of decorators) { const decoratorName = TsUtils.getDecoratorName(decorator); - if (decoratorName && decoratorName === CustomDecoratorName.Layoutable) { + if (decoratorName && decoratorName === CustomDecoratorName.CustomLayout) { return; } } @@ -9048,8 +9511,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const processExpression = (expr: ts.Expression): void => { const symbol = this.tsUtils.trueSymbolAtLocation(expr); - if (this.isJsFileSymbol(symbol)) { - this.incrementCounters(expr, FaultID.BinaryOperations); + if (this.isJsFileSymbol(symbol) || this.isJsFileExpression(expr)) { + const autofix = this.autofixer?.fixInteropOperators(expr); + this.incrementCounters(expr, FaultID.BinaryOperations, autofix); } }; @@ -9081,10 +9545,14 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } return false; }; + const isStandardFloatFormat = (): boolean => { + const text = node.getText(); + return (/\.\d*0+$/).test(text); + }; const isNoNeedFix = isInElementAccessExpression(node) || - ts.isEnumMember(node.parent) || - 'name' in node.parent && node.parent.name === node; + 'name' in node.parent && node.parent.name === node || + isStandardFloatFormat(); if (isNoNeedFix) { return; } @@ -9097,4 +9565,390 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.incrementCounters(node, FaultID.NumericSemantics, autofix); } } + + private checkArrayUsageWithoutBound(accessExpr: ts.ElementAccessExpression): void { + if (!this.options.arkts2 || !this.useStatic) { + return; + } + + const arrayAccessInfo = this.getArrayAccessInfo(accessExpr); + if (!arrayAccessInfo) { + const accessArgument = accessExpr.argumentExpression; + if (TypeScriptLinter.isFunctionCall(accessArgument)) { + this.incrementCounters(accessExpr, FaultID.RuntimeArrayCheck); + } + return; + } + + const { arrayIdent } = arrayAccessInfo; + const arraySym = this.tsUtils.trueSymbolAtLocation(arrayIdent); + if (!arraySym) { + return; + } + + const indexExpr = accessExpr.argumentExpression; + const loopVarName = ts.isIdentifier(indexExpr) ? indexExpr.text : undefined; + + const { isInSafeContext, isValidBoundCheck, isVarModifiedBeforeAccess } = this.analyzeSafeContext( + accessExpr, + loopVarName, + arraySym + ); + + if (isInSafeContext) { + if (!isValidBoundCheck || isVarModifiedBeforeAccess) { + this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); + } + } else { + this.incrementCounters(arrayIdent.parent, FaultID.RuntimeArrayCheck); + } + } + + private analyzeSafeContext( + accessExpr: ts.ElementAccessExpression, + loopVarName: string | undefined, + arraySym: ts.Symbol + ): { isInSafeContext: boolean; isValidBoundCheck: boolean; isVarModifiedBeforeAccess: boolean } { + const context = TypeScriptLinter.findSafeContext(accessExpr); + if (!context) { + return { isInSafeContext: false, isValidBoundCheck: false, isVarModifiedBeforeAccess: false }; + } + + return this.analyzeContextSafety(context, accessExpr, loopVarName, arraySym); + } + + static findSafeContext( + accessExpr: ts.ElementAccessExpression + ): { node: ts.ForStatement | ts.WhileStatement | ts.IfStatement } | void { + let currentNode: ts.Node | undefined = accessExpr; + + while (currentNode) { + if (ts.isForStatement(currentNode) || ts.isWhileStatement(currentNode) || ts.isIfStatement(currentNode)) { + return { node: currentNode }; + } + currentNode = currentNode.parent; + } + + return undefined; + } + + private analyzeContextSafety( + context: { node: ts.ForStatement | ts.WhileStatement | ts.IfStatement }, + accessExpr: ts.ElementAccessExpression, + loopVarName: string | undefined, + arraySym: ts.Symbol + ): { isInSafeContext: boolean; isValidBoundCheck: boolean; isVarModifiedBeforeAccess: boolean } { + const { node } = context; + + if (!loopVarName) { + return { + isInSafeContext: true, + isValidBoundCheck: false, + isVarModifiedBeforeAccess: false + }; + } + + const analysis = this.analyzeStatementType(node, accessExpr, loopVarName, arraySym); + + return { + isInSafeContext: true, + isValidBoundCheck: analysis.isValidBoundCheck, + isVarModifiedBeforeAccess: analysis.isVarModifiedBeforeAccess + }; + } + + private analyzeStatementType( + node: ts.ForStatement | ts.WhileStatement | ts.IfStatement, + accessExpr: ts.ElementAccessExpression, + loopVarName: string, + arraySym: ts.Symbol + ): { isValidBoundCheck: boolean; isVarModifiedBeforeAccess: boolean } { + switch (node.kind) { + case ts.SyntaxKind.ForStatement: + return this.analyzeForStatement(node, accessExpr, loopVarName, arraySym); + case ts.SyntaxKind.WhileStatement: + return this.analyzeWhileStatement(node, accessExpr, loopVarName, arraySym); + case ts.SyntaxKind.IfStatement: + return this.analyzeIfStatement(node, accessExpr, loopVarName, arraySym); + default: + return { isValidBoundCheck: false, isVarModifiedBeforeAccess: false }; + } + } + + private analyzeForStatement( + forNode: ts.ForStatement, + accessExpr: ts.ElementAccessExpression, + loopVarName: string, + arraySym: ts.Symbol + ): { isValidBoundCheck: boolean; isVarModifiedBeforeAccess: boolean } { + const isValidBoundCheck = forNode.condition ? + this.checkBoundCondition(forNode.condition, loopVarName, arraySym) : + false; + + const isVarModifiedBeforeAccess = forNode.statement ? + TypeScriptLinter.checkVarModifiedBeforeNode(forNode.statement, accessExpr, loopVarName) : + false; + + return { isValidBoundCheck, isVarModifiedBeforeAccess }; + } + + private analyzeWhileStatement( + whileNode: ts.WhileStatement, + accessExpr: ts.ElementAccessExpression, + loopVarName: string, + arraySym: ts.Symbol + ): { isValidBoundCheck: boolean; isVarModifiedBeforeAccess: boolean } { + const isValidBoundCheck = whileNode.expression ? + this.checkBoundCondition(whileNode.expression, loopVarName, arraySym) : + false; + + const isVarModifiedBeforeAccess = whileNode.statement ? + TypeScriptLinter.checkVarModifiedBeforeNode(whileNode.statement, accessExpr, loopVarName) : + false; + + return { isValidBoundCheck, isVarModifiedBeforeAccess }; + } + + private analyzeIfStatement( + ifNode: ts.IfStatement, + accessExpr: ts.ElementAccessExpression, + loopVarName: string, + arraySym: ts.Symbol + ): { isValidBoundCheck: boolean; isVarModifiedBeforeAccess: boolean } { + const isValidBoundCheck = ifNode.expression ? + this.checkBoundCondition(ifNode.expression, loopVarName, arraySym) : + false; + + let isVarModifiedBeforeAccess = false; + const statementBlock = ts.isBlock(ifNode.thenStatement) ? ifNode.thenStatement : undefined; + if (statementBlock) { + isVarModifiedBeforeAccess = TypeScriptLinter.checkVarModifiedBeforeNode(statementBlock, accessExpr, loopVarName); + } + + return { isValidBoundCheck, isVarModifiedBeforeAccess }; + } + + private checkBoundCondition(condition: ts.Expression, varName: string, arraySym: ts.Symbol): boolean { + if (ts.isBinaryExpression(condition)) { + const { left, right, operatorToken } = condition; + + if (this.checkVarLessThanArrayLength(left, right, operatorToken, varName, arraySym)) { + return true; + } + + if (this.checkArrayLengthGreaterThanVar(left, right, operatorToken, varName, arraySym)) { + return true; + } + + if (ts.isIdentifier(left) && left.text === varName && ts.isNumericLiteral(right)) { + const value = parseFloat(right.text); + if ( + operatorToken.kind === ts.SyntaxKind.GreaterThanEqualsToken && value <= 0 || + operatorToken.kind === ts.SyntaxKind.GreaterThanToken && value < 0 + ) { + return true; + } + } + + return this.checkBoundCondition(left, varName, arraySym) || this.checkBoundCondition(right, varName, arraySym); + } + + return false; + } + + private checkArrayLengthGreaterThanVar( + left: ts.Expression, + right: ts.Expression, + operatorToken: ts.Token, + varName: string, + arraySym: ts.Symbol + ): boolean { + if ( + ts.isPropertyAccessExpression(left) && + left.name.text === 'length' && + ts.isIdentifier(right) && + right.text === varName + ) { + const leftArraySym = this.tsUtils.trueSymbolAtLocation(left.expression); + if (leftArraySym === arraySym) { + return ( + operatorToken.kind === ts.SyntaxKind.GreaterThanToken || + operatorToken.kind === ts.SyntaxKind.GreaterThanEqualsToken + ); + } + } + return false; + } + + private checkVarLessThanArrayLength( + left: ts.Expression, + right: ts.Expression, + operatorToken: ts.Token, + varName: string, + arraySym: ts.Symbol + ): boolean { + return ( + ts.isIdentifier(left) && + left.text === varName && + ts.isPropertyAccessExpression(right) && + right.name.text === 'length' && + (operatorToken.kind === ts.SyntaxKind.LessThanToken || + operatorToken.kind === ts.SyntaxKind.LessThanEqualsToken) && + this.tsUtils.trueSymbolAtLocation(right.expression) === arraySym + ); + } + + private static traverseNodesUntilTarget( + node: ts.Node, + targetNode: ts.Node, + varName: string, + scopeStack: { shadowed: boolean; localVars: Set }[], + state: { targetFound: boolean; modified: boolean } + ): void { + if (node === targetNode) { + state.targetFound = true; + return; + } + + if (state.targetFound) { + return; + } + + const newScope = this.handleNewScope(node, scopeStack); + + TypeScriptLinter.getVariablesFromScope(node, varName, scopeStack); + + if (this.isVariableModified(node, varName, scopeStack)) { + state.modified = true; + } + + ts.forEachChild(node, (child) => { + this.traverseNodesUntilTarget(child, targetNode, varName, scopeStack, state); + }); + + if (newScope) { + scopeStack.pop(); + } + } + + private static handleNewScope( + node: ts.Node, + scopeStack: { shadowed: boolean; localVars: Set }[] + ): { shadowed: boolean; localVars: Set } | null { + if (ts.isBlock(node) || ts.isFunctionLike(node) || ts.isCatchClause(node)) { + const parentScope = scopeStack[scopeStack.length - 1]; + const newScope = { + shadowed: parentScope.shadowed, + localVars: new Set() + }; + scopeStack.push(newScope); + return newScope; + } + return null; + } + + static getVariablesFromScope( + node: ts.Node, + varName: string, + scopeStack: { shadowed: boolean; localVars: Set }[] + ): void { + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === varName) { + const parent = node.parent; + if ( + ts.isVariableDeclarationList(parent) && + (parent.flags & ts.NodeFlags.Let || parent.flags & ts.NodeFlags.Const) + ) { + scopeStack[scopeStack.length - 1].localVars.add(varName); + } + } + + if (ts.isParameter(node) && ts.isIdentifier(node.name) && node.name.text === varName) { + scopeStack[scopeStack.length - 1].localVars.add(varName); + } + } + + private static isVariableModified( + node: ts.Node, + varName: string, + scopeStack: { shadowed: boolean; localVars: Set }[] + ): boolean { + if (!ts.isBinaryExpression(node) || node.operatorToken.kind !== ts.SyntaxKind.EqualsToken) { + return false; + } + + if (!ts.isIdentifier(node.left) || node.left.text !== varName) { + return false; + } + + for (let i = scopeStack.length - 1; i >= 0; i--) { + if (scopeStack[i].localVars.has(varName)) { + return false; + } + } + + return true; + } + + static checkVarModifiedBeforeNode(container: ts.Node, targetNode: ts.Node, varName: string): boolean { + const scopeStack: { shadowed: boolean; localVars: Set }[] = []; + scopeStack.push({ shadowed: false, localVars: new Set() }); + + const state = { + targetFound: false, + modified: false + }; + + this.traverseNodesUntilTarget(container, targetNode, varName, scopeStack, state); + return state.modified; + } + + static isFunctionCall(node: ts.Node): boolean { + return ts.isCallExpression(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node); + } + + private getArrayAccessInfo(expr: ts.ElementAccessExpression): false | ArrayAccess { + if (!ts.isIdentifier(expr.expression)) { + return false; + } + const baseType = this.tsTypeChecker.getTypeAtLocation(expr.expression); + if (!this.tsUtils.isArray(baseType)) { + return false; + } + const accessArgument = expr.argumentExpression; + + TypeScriptLinter.isFunctionCall(accessArgument); + + const checkNumericType = (node: ts.Node): boolean => { + const argType = this.tsTypeChecker.getTypeAtLocation(node); + return ( + (argType.flags & ts.TypeFlags.NumberLike) !== 0 || + argType.isUnionOrIntersection() && + argType.types.some((t) => { + return t.flags & ts.TypeFlags.NumberLike; + }) + ); + }; + + const isEnumMember = (node: ts.Node): boolean => { + if (ts.isPropertyAccessExpression(node)) { + const symbol = this.tsUtils.trueSymbolAtLocation(node); + return !!symbol && (symbol.flags & ts.SymbolFlags.EnumMember) !== 0; + } + return false; + }; + + if (TypeScriptLinter.isFunctionCall(accessArgument)) { + return false; + } + + if (checkNumericType(accessArgument) || isEnumMember(accessArgument)) { + return { + pos: expr.getEnd(), + accessingIdentifier: accessArgument, + arrayIdent: expr.expression + }; + } + + return false; + } } diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index 8b54a99d03..9a990259ea 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -38,8 +38,8 @@ export const cookBookRefToFixTitle: Map = new Map([ [177, 'Add \'Sendable\' decorator'], [180, 'Remove the decorator'], [189, 'Add type annotations to numerical variables'], + [192, 'Use "undefined" instead "void"'], [193, 'Replace with arrow function'], - [206, 'Replace with a special library to call'], [209, 'Transform "number" to "int"'], [251, 'Transform "!!" to "$$()"'], [252, 'Transform "$$" to "$$()"'], @@ -52,6 +52,9 @@ export const cookBookRefToFixTitle: Map = new Map([ [260, '"@Entry" annotaion fixed'], [263, '"@Provide" annotation fixed'], [275, 'Custom layout need add decorator'], + [281, '"@Prop" transform to "@PropRef"'], + [282, '"@StorageProp" transform to "@StoragePropRef"'], + [283, '"@LocalStorageProp" transform to "@LocalStoragePropRef"'], [300, 'Replace calling method of the TS-like `Function` type'], [330, 'Convert import named objects from JS to ESValue'], [332, 'Using the ESValue interface to access properties'], diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index 564ebc117d..dc78eabc87 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -39,9 +39,11 @@ import { GET_LOCAL_STORAGE_FUNC_NAME, PROVIDE_DECORATOR_NAME, PROVIDE_ALIAS_PROPERTY_NAME, - PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME + PROVIDE_ALLOW_OVERRIDE_PROPERTY_NAME, + NEW_PROP_DECORATOR_SUFFIX } from '../utils/consts/ArkuiConstants'; import { ES_VALUE } from '../utils/consts/ESObject'; +import type { IncrementDecrementNodeInfo } from '../utils/consts/InteropAPI'; import { LOAD, GET_PROPERTY_BY_NAME, @@ -53,8 +55,11 @@ import { WRAP, INSTANTIATE, TO_NUMBER, + TO_PROMISE, INVOKE, - INVOKE_METHOD + INVOKE_METHOD, + LENGTH, + IS_INSTANCE_OF } from '../utils/consts/InteropAPI'; import { ESLIB_SHAREDARRAYBUFFER } from '../utils/consts/ConcurrentAPI'; @@ -86,6 +91,9 @@ const GENERATED_DESTRUCT_ARRAY_TRESHOLD = 1000; const GENERATED_IMPORT_VARIABLE_NAME = 'GeneratedImportVar_'; const GENERATED_IMPORT_VARIABLE_TRESHOLD = 1000; +const GENERATED_TMP_VARIABLE_NAME = 'tmp_'; +const GENERATED_TMP_VARIABLE_TRESHOLD = 1000; + const SPECIAL_LIB_NAME = 'specialAutofixLib'; const OBJECT_LITERAL_CLASS_CONSTRUCTOR_PARAM_NAME = 'init'; @@ -150,6 +158,11 @@ export class Autofixer { GENERATED_IMPORT_VARIABLE_TRESHOLD ); + private readonly tmpVariableNameGenerator = new NameGenerator( + GENERATED_TMP_VARIABLE_NAME, + GENERATED_TMP_VARIABLE_TRESHOLD + ); + private modVarName: string = ''; private readonly lastImportEndMap = new Map(); @@ -962,7 +975,43 @@ export class Autofixer { return this.renameSymbolAsIdentifier(symbol, enumMember); } + renameAsObjectElementAccessExpression(node: ts.ElementAccessExpression): Autofix[] | undefined { + const parenExpr = ts.isParenthesizedExpression(node.expression) ? node.expression : undefined; + const asExpr = parenExpr && ts.isAsExpression(parenExpr.expression) ? parenExpr.expression : undefined; + if (!asExpr) { + return undefined; + } + + const argument = node.argumentExpression; + const propertyName = ts.isStringLiteral(argument) ? argument.text : undefined; + if (!propertyName) { + return undefined; + } + + const realObj = asExpr.expression; + const type = this.typeChecker.getTypeAtLocation(realObj); + const property = this.typeChecker.getPropertyOfType(type, propertyName); + if (!property) { + return undefined; + } + + return [ + { + replacementText: realObj.getText() + '.' + propertyName, + start: node.getStart(), + end: node.getEnd() + } + ]; + } + fixPropertyAccessByIndex(node: ts.ElementAccessExpression): Autofix[] | undefined { + if (ts.isParenthesizedExpression(node.expression) && ts.isAsExpression(node.expression.expression)) { + const assertedType = this.typeChecker.getTypeAtLocation(node.expression.expression.type); + if (this.typeChecker.typeToString(assertedType) === 'object') { + return this.renameAsObjectElementAccessExpression(node); + } + } + const symbol = this.typeChecker.getSymbolAtLocation(node.argumentExpression); if (symbol === undefined) { return undefined; @@ -2013,7 +2062,8 @@ export class Autofixer { private fixObjectLiteralAsClass( objectLiteralExpr: ts.ObjectLiteralExpression, typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined, - enclosingStmt: ts.Node + enclosingStmt: ts.Node, + typeNode?: ts.TypeReferenceNode ): Autofix[] | undefined { if (this.utils.nodeCapturesValueFromEnclosingLocalScope(objectLiteralExpr, enclosingStmt)) { return undefined; @@ -2032,9 +2082,9 @@ export class Autofixer { const classDeclAndCtorInitProps = this.createClassDeclForObjectLiteral( objectLiteralExpr, enclosingStmt, - newClassName, - newInitInterfaceName, - typeDecl + { className: newClassName, initInterfaceName: newInitInterfaceName }, + typeDecl, + typeNode ); if (!classDeclAndCtorInitProps) { return undefined; @@ -2063,10 +2113,11 @@ export class Autofixer { private createClassDeclForObjectLiteral( objectLiteralExpr: ts.ObjectLiteralExpression, enclosingStmt: ts.Node, - newClassName: string, - newInitInterfaceName: string, - typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined + names: { className: string; initInterfaceName: string }, + typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined, + typeNode?: ts.TypeReferenceNode ): { classDecl: ts.ClassDeclaration; ctorInitProps: ts.PropertyAssignment[] } | undefined { + const { className, initInterfaceName } = names; const classFields: ts.PropertyDeclaration[] = []; const classMethods: (ts.MethodDeclaration | ts.AccessorDeclaration)[] = []; const ctorBodyStmts: ts.Statement[] = []; @@ -2096,14 +2147,14 @@ export class Autofixer { const classElements: ts.ClassElement[] = [...classFields]; if (ctorInitProps.length) { - classElements.push(Autofixer.createClassConstructorForObjectLiteral(newInitInterfaceName, ctorBodyStmts)); + classElements.push(Autofixer.createClassConstructorForObjectLiteral(initInterfaceName, ctorBodyStmts)); } classElements.push(...classMethods); - const heritageClauses = Autofixer.createHeritageClausesForObjectLiteralClass(typeDecl); + const heritageClauses = Autofixer.createHeritageClausesForObjectLiteralClass(typeDecl, typeNode); return { - classDecl: ts.factory.createClassDeclaration(undefined, newClassName, undefined, heritageClauses, classElements), + classDecl: ts.factory.createClassDeclaration(undefined, className, undefined, heritageClauses, classElements), ctorInitProps }; } @@ -2162,20 +2213,32 @@ export class Autofixer { } private static createHeritageClausesForObjectLiteralClass( - typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined + typeDecl: ts.ClassDeclaration | ts.InterfaceDeclaration | undefined, + typeNode?: ts.TypeReferenceNode ): ts.HeritageClause[] | undefined { if (!typeDecl?.name) { return undefined; } + const heritageTypeExpression = typeNode ? + Autofixer.entityNameToExpression(typeNode.typeName) : + ts.factory.createIdentifier(typeDecl.name.text); + return [ ts.factory.createHeritageClause( ts.isClassDeclaration(typeDecl) ? ts.SyntaxKind.ExtendsKeyword : ts.SyntaxKind.ImplementsKeyword, - [ts.factory.createExpressionWithTypeArguments(typeDecl.name, undefined)] + [ts.factory.createExpressionWithTypeArguments(heritageTypeExpression, undefined)] ) ]; } + private static entityNameToExpression(name: ts.EntityName): ts.Expression { + if (ts.isQualifiedName(name)) { + return ts.factory.createPropertyAccessExpression(Autofixer.entityNameToExpression(name.left), name.right); + } + return ts.factory.createIdentifier(name.text); + } + private static createClassConstructorForObjectLiteral( newInitInterfaceName: string, ctorBodyStmts: ts.Statement[] @@ -2242,7 +2305,8 @@ export class Autofixer { return undefined; } - return this.fixObjectLiteralAsClass(objectLiteralExpr, typeDecl, enclosingStmt); + const typeNode = (objectLiteralExpr.parent as ts.VariableDeclaration).type as ts.TypeReferenceNode | undefined; + return this.fixObjectLiteralAsClass(objectLiteralExpr, typeDecl, enclosingStmt, typeNode); } private hasMethodOverridingProperty( @@ -2483,12 +2547,6 @@ export class Autofixer { return undefined; } - fixGlobalThisGet(node: ts.PropertyAccessExpression): Autofix[] { - void this; - const replacement = `${SPECIAL_LIB_NAME}.globalThis.get("${node.name.text}")`; - return [{ start: node.getStart(), end: node.getEnd(), replacementText: replacement }]; - } - fixVoidOperator(voidExpr: ts.VoidExpression): Autofix[] { let newExpr = voidExpr.expression; @@ -2619,12 +2677,6 @@ export class Autofixer { return { pattern, flag }; } - fixDebuggerStatement(debuggerStmt: ts.DebuggerStatement): Autofix[] { - void this; - const text = SPECIAL_LIB_NAME + '.debugger();'; - return [{ start: debuggerStmt.getStart(), end: debuggerStmt.getEnd(), replacementText: text }]; - } - /* * "unsafe" (result is not common subset) autofixes */ @@ -3063,6 +3115,229 @@ export class Autofixer { } } + private getVariableName(node: ts.Node): string | undefined { + let variableName: string | undefined; + + switch (node.kind) { + case ts.SyntaxKind.BinaryExpression: { + const binaryExpr = node as ts.BinaryExpression; + if (binaryExpr.operatorToken.kind !== ts.SyntaxKind.EqualsToken) { + return undefined; + } + + variableName = binaryExpr.left.getText(); + break; + } + case ts.SyntaxKind.VariableDeclaration: { + const variableDecl = node as ts.VariableDeclaration; + variableName = variableDecl.name.getText(); + break; + } + case ts.SyntaxKind.ExpressionStatement: { + variableName = TsUtils.generateUniqueName(this.tmpVariableNameGenerator, this.sourceFile); + break; + } + default: { + return undefined; + } + } + + return variableName; + } + + private getNewNodesForIncrDecr(variableName: string, operator: number): IncrementDecrementNodeInfo | undefined { + let update: string | undefined; + let updateNode: ts.BinaryExpression | undefined; + + switch (operator) { + case ts.SyntaxKind.MinusMinusToken: { + const { varAssignText, addOrDecrOperation } = this.createNewIncrDecrNodes( + variableName, + ts.SyntaxKind.MinusToken + ); + update = varAssignText; + updateNode = addOrDecrOperation; + break; + } + case ts.SyntaxKind.PlusPlusToken: { + const { varAssignText, addOrDecrOperation } = this.createNewIncrDecrNodes( + variableName, + ts.SyntaxKind.PlusToken + ); + update = varAssignText; + updateNode = addOrDecrOperation; + break; + } + default: + return undefined; + } + + return { varAssignText: update, addOrDecrOperation: updateNode }; + } + + fixUnaryIncrDecr( + node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression, + pan: ts.PropertyAccessExpression + ): Autofix[] | undefined { + const parent = node.parent; + const grandParent = parent.parent; + + const { expression, name } = pan; + const { operator } = node; + const isVariableDeclaration = ts.isVariableDeclaration(node.parent); + + const variableName = this.getVariableName(node.parent); + + if (!variableName) { + return undefined; + } + + const updateNodes = this.getNewNodesForIncrDecr(variableName, operator); + + if (!updateNodes?.varAssignText || !updateNodes.addOrDecrOperation) { + return undefined; + } + + const replacementText = this.getReplacementTextForPrefixAndPostfixUnary( + node, + updateNodes, + expression, + name, + variableName + ); + + if (!replacementText) { + return undefined; + } + + if (isVariableDeclaration) { + const start = grandParent.getStart(); + const end = grandParent.getEnd(); + return [{ replacementText, start, end }]; + } + + const start = parent.getStart(); + const end = parent.getEnd(); + return [{ replacementText, start, end }]; + } + + private getReplacementTextForPrefixAndPostfixUnary( + node: ts.Node, + updateNodes: IncrementDecrementNodeInfo, + expression: ts.LeftHandSideExpression, + name: ts.MemberName, + variableName: string + ): string | undefined { + const { varAssignText, addOrDecrOperation } = updateNodes; + const converted: ts.Node = this.createGetPropertyForIncrDecr(expression.getText(), name.text); + let convertedAssigned = ''; + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) { + convertedAssigned = this.wrapPropertyAccessInBinaryExpr(variableName, converted); + } else { + convertedAssigned = this.wrapPropertyAccessInVariableDeclaration(variableName, converted); + } + let replacementText = ''; + + switch (node.kind) { + case ts.SyntaxKind.PrefixUnaryExpression: { + const assign = this.createSetProperty( + expression.getText(), + name.text, + ts.factory.createIdentifier(variableName) + ); + replacementText = `${convertedAssigned}\n${varAssignText}\n${assign}\n`; + break; + } + case ts.SyntaxKind.PostfixUnaryExpression: { + const assign = this.createSetProperty(expression.getText(), name.text, addOrDecrOperation as ts.Expression); + replacementText = `${convertedAssigned}\n${assign}\n${varAssignText}\n`; + break; + } + default: { + return undefined; + } + } + + return replacementText; + } + + private wrapPropertyAccessInVariableDeclaration(variableName: string, wrappedNode: ts.Node): string { + const node = ts.factory.createVariableDeclarationList( + [ + ts.factory.createVariableDeclaration( + ts.factory.createIdentifier(variableName), + undefined, + undefined, + wrappedNode as ts.Expression + ) + ], + ts.NodeFlags.Let + ); + + return this.printer.printNode(ts.EmitHint.Unspecified, node, this.sourceFile); + } + + private wrapPropertyAccessInBinaryExpr(variableName: string, wrappedNode: ts.Node): string { + const node = ts.factory.createBinaryExpression( + ts.factory.createIdentifier(variableName), + ts.SyntaxKind.EqualsToken, + wrappedNode as ts.Expression + ); + + return this.printer.printNode(ts.EmitHint.Unspecified, node, this.sourceFile); + } + + private createGetPropertyForIncrDecr(expression: string, name: string): ts.Node { + void this; + return ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(expression), + ts.factory.createIdentifier(GET_PROPERTY_BY_NAME) + ), + undefined, + [ts.factory.createStringLiteral(name)] + ), + ts.factory.createIdentifier(TO_NUMBER) + ), + undefined, + [] + ); + } + + private createNewIncrDecrNodes(variableName: string, token: number): IncrementDecrementNodeInfo { + const update = ts.factory.createBinaryExpression( + ts.factory.createIdentifier(variableName), + ts.factory.createToken(token), + ts.factory.createNumericLiteral('1') + ); + + const node = ts.factory.createBinaryExpression( + ts.factory.createIdentifier(variableName), + ts.factory.createToken(ts.SyntaxKind.EqualsToken), + update + ); + + return { + addOrDecrOperation: update, + varAssignText: this.printer.printNode(ts.EmitHint.Unspecified, node, this.sourceFile) + }; + } + + private createSetProperty(expression: string, field: string, value: ts.Expression): string { + const node = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(expression), + ts.factory.createIdentifier(SET_PROPERTY_BY_NAME) + ), + undefined, + [ts.factory.createIdentifier(field), value] + ); + + return this.printer.printNode(ts.EmitHint.Unspecified, node, this.sourceFile); + } + fixVariableDeclaration(node: ts.VariableDeclaration, isEnum: boolean): Autofix[] | undefined { const initializer = node.initializer; const name = node.name; @@ -3106,7 +3381,11 @@ export class Autofixer { node.initializer ); - const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, newProperty, node.getSourceFile()); + const replacementText = this.nonCommentPrinter.printNode( + ts.EmitHint.Unspecified, + newProperty, + node.getSourceFile() + ); return [ { @@ -3231,7 +3510,7 @@ export class Autofixer { initializer ); - const text = this.printer.printNode(ts.EmitHint.Unspecified, newPropDecl, node.getSourceFile()); + const text = this.nonCommentPrinter.printNode(ts.EmitHint.Unspecified, newPropDecl, node.getSourceFile()); return [{ start: node.getStart(), end: node.getEnd(), replacementText: text }]; } @@ -3594,6 +3873,30 @@ export class Autofixer { return [{ start: binaryExpr.getStart(), end: binaryExpr.getEnd(), replacementText }]; } + /** + * Autofix for `foo instanceof Foo` → `foo.isInstanceOf(Foo)`. + * + * @param node The binary `instanceof` expression node. + * @returns A single Autofix replacing the entire `foo instanceof Foo` text. + */ + fixInteropJsInstanceOfExpression(node: ts.BinaryExpression): Autofix[] { + // left-hand and right-hand operands of the `instanceof` + const leftExpr = node.left; + const rightExpr = node.right; + + // build: leftExpr.isInstanceOf(rightExpr) + const callExpr = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(leftExpr, ts.factory.createIdentifier(IS_INSTANCE_OF)), + undefined, + [rightExpr] + ); + + // render back to source text + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, callExpr, node.getSourceFile()); + + return [{ replacementText, start: node.getStart(), end: node.getEnd() }]; + } + createReplacementForJsIndirectImportPropertyAccessExpression(node: ts.PropertyAccessExpression): Autofix[] { // Bypass eslint-check void this; @@ -3603,7 +3906,7 @@ export class Autofixer { let start = node.getStart(); let end = node.getEnd(); - let replacementText = `${objName}.getPropertyByName('${propName}')`; + let replacementText = `${objName}.${GET_PROPERTY_BY_NAME}('${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) { @@ -3622,29 +3925,93 @@ export class Autofixer { const start = node.getStart(); const end = node.getEnd(); - const replacement = `${objName}.getPropertyByName('${propName}')${this.utils.findTypeOfNodeForConversion(node)}`; + const typeTag = this.utils.findTypeOfNodeForConversion(node); + const replacement = `${objName}.${GET_PROPERTY_BY_NAME}('${propName}')${typeTag}`; 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},` + - ` ESValue.wrap(${elementAccessExpr.parent.right.getText()}))` : - `${identifier.text}.getPropertyByIndex(${exprText})` + - this.utils.findTypeOfNodeForConversion(elementAccessExpr); + /** + * Converts a JS element access (e.g. `arr[index]`) into the corresponding + * interop call: + * - On assignment (`arr[index] = value`), emits `arr.setPropertyByIndex(index, ESValue.wrap(value))` + * - On read, emits `arr.getPropertyByIndex(index)` plus any type conversion suffix + * + * @param elementAccessExpr The original `ElementAccessExpression` node. + * @returns An array with a single `Autofix` describing the replacement range and text. + */ + fixJsImportElementAccessExpression(elementAccessExpr: ts.ElementAccessExpression): Autofix[] { + const parent = elementAccessExpr.parent; + + const isAssignment = + parent !== undefined && ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken; + + // array identifier (e.g. "arr") + const identifierNode = elementAccessExpr.expression as ts.Identifier; + + let replacementText: string; + if (isAssignment) { + // arr.setPropertyByIndex(index, ESValue.wrap(value)) + const wrapped = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(ES_VALUE), + ts.factory.createIdentifier(WRAP) + ), + undefined, + [parent.right] + ); + + const callExpr = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(identifierNode, ts.factory.createIdentifier(SET_PROPERTY_BY_INDEX)), + undefined, + [elementAccessExpr.argumentExpression, wrapped] + ); + + replacementText = this.printer.printNode(ts.EmitHint.Unspecified, callExpr, elementAccessExpr.getSourceFile()); + } else { + // arr.getPropertyByIndex(index) plus conversion + const callExpr = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(identifierNode, ts.factory.createIdentifier(GET_PROPERTY_BY_INDEX)), + undefined, + [elementAccessExpr.argumentExpression] + ); + + replacementText = + this.printer.printNode(ts.EmitHint.Unspecified, callExpr, elementAccessExpr.getSourceFile()) + + this.utils.findTypeOfNodeForConversion(elementAccessExpr); + } + + const start = isAssignment ? (parent as ts.Node).getStart() : elementAccessExpr.getStart(); + const end = isAssignment ? (parent as ts.Node).getEnd() : elementAccessExpr.getEnd(); + return [{ replacementText, start, end }]; } + /** + * Replace each loop‐variable reference (e.g. `element`) with + * `array.getPropertyByIndex(i)` plus appropriate conversion. + * + * @param identifier The Identifier node of the loop variable usage. + * @param arrayName The name of the array being iterated. + */ + fixInteropArrayElementUsage(identifier: ts.Identifier, arrayName: string): Autofix { + // arr.getPropertyByIndex(i) + const callExpr = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(arrayName), + ts.factory.createIdentifier(GET_PROPERTY_BY_INDEX) + ), + undefined, + [ts.factory.createIdentifier('i')] + ); + + // Print and append proper conversion suffix + const printed = this.printer.printNode(ts.EmitHint.Unspecified, callExpr, identifier.getSourceFile()); + const replacementText = printed + this.utils.findTypeOfNodeForConversion(identifier); + + return { replacementText, start: identifier.getStart(), end: identifier.getEnd() }; + } + fixSharedArrayBufferConstructor(node: ts.NewExpression): Autofix[] | undefined { void this; @@ -3671,6 +4038,63 @@ export class Autofixer { return [{ replacementText, start: node.getStart(), end: node.getEnd() }]; } + /** + * Converts a `for...of` over an interop array into + * an index-based `for` loop using `getPropertyByName("length")`. + * + * @param node The `ForOfStatement` node to fix. + * @returns A single Autofix for the loop header replacement. + */ + fixInteropArrayForOf(node: ts.ForOfStatement): Autofix { + const iterableName = node.expression.getText(); + + const initializer = ts.factory.createVariableDeclarationList( + [ + ts.factory.createVariableDeclaration( + ts.factory.createIdentifier('i'), + undefined, + undefined, + ts.factory.createNumericLiteral('0') + ) + ], + ts.NodeFlags.Let + ); + + const lengthAccess = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(iterableName), + ts.factory.createIdentifier(GET_PROPERTY_BY_NAME) + ), + undefined, + [ts.factory.createStringLiteral(LENGTH)] + ); + const condition = ts.factory.createBinaryExpression( + ts.factory.createIdentifier('i'), + ts.SyntaxKind.LessThanToken, + lengthAccess + ); + + const incrementor = ts.factory.createPrefixUnaryExpression( + ts.SyntaxKind.PlusPlusToken, + ts.factory.createIdentifier('i') + ); + + // Render just the "(initializer; condition; incrementor)" text: + const headerText = [ + this.printer.printNode(ts.EmitHint.Unspecified, initializer, node.getSourceFile()), + '; ', + this.printer.printNode(ts.EmitHint.Unspecified, condition, node.getSourceFile()), + '; ', + this.printer.printNode(ts.EmitHint.Unspecified, incrementor, node.getSourceFile()) + ].join(''); + + // Only replace from the start of the initializer to the end of the 'of' expression + const start = node.initializer.getStart(); + const end = node.expression.getEnd(); + + return { start, end, replacementText: headerText }; + } + fixAppStorageCallExpression(callExpr: ts.CallExpression): Autofix[] | undefined { const varDecl = Autofixer.findParentVariableDeclaration(callExpr); if (!varDecl || varDecl.type) { @@ -3757,30 +4181,52 @@ export class Autofixer { return ''; } - private static fixInterOpImportJsWrapArgs(args: ts.NodeArray): string { - return args. - map((arg) => { - return `ESValue.wrap(${arg.getText()})`; - }). - join(', '); - } - - private fixInterOpImportJsProcessNode(node: ts.Node): string { + private fixInterOpImportJsProcessNode(node: ts.Node): string | undefined { 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})`; + const newArgs = this.createArgs(node.arguments); + const callee = node.expression; + switch (callee.kind) { + case ts.SyntaxKind.PropertyAccessExpression: { + const propertyAccessExpr = node.expression as ts.PropertyAccessExpression; + const newCallExpr = this.createJSInvokeCallExpression(propertyAccessExpr.expression, INVOKE_METHOD, [ + ts.factory.createStringLiteral(propertyAccessExpr.name.text), + ...newArgs || [] + ]); + + if (!newCallExpr) { + return undefined; + } + return this.printer.printNode(ts.EmitHint.Unspecified, newCallExpr, node.getSourceFile()); + } + default: { + const callExpr = this.createJSInvokeCallExpression(node.expression, INVOKE, [...newArgs || []]); + + if (!callExpr) { + return undefined; + } + + return this.printer.printNode(ts.EmitHint.Unspecified, callExpr, node.getSourceFile()); + } + } } else if (ts.isPropertyAccessExpression(node)) { const base = this.fixInterOpImportJsProcessNode(node.expression); + if (!base) { + return undefined; + } const propName = node.name.text; - return `${base}.getPropertyByName('${propName}')`; + return `${base}.${GET_PROPERTY_BY_NAME}('${propName}')`; } else if (ts.isNewExpression(node)) { - const constructor = this.fixInterOpImportJsProcessNode(node.expression); - return `${constructor}.instantiate()`; + const newArgs = this.createArgs(node.arguments); + const newCallExpr = this.createJSInvokeCallExpression(node.expression, INSTANTIATE, [...newArgs || []]); + + if (!newCallExpr) { + return undefined; + } + return this.printer.printNode(ts.EmitHint.Unspecified, newCallExpr, node.getSourceFile()); } - return ''; + return undefined; } fixInterOpImportJs( @@ -3946,6 +4392,65 @@ export class Autofixer { ]; } + fixInteropOperators(expr: ts.Expression): Autofix[] | undefined { + if (ts.isPropertyAccessExpression(expr)) { + return this.fixPropertyAccessToNumber(expr); + } + + if (ts.isIdentifier(expr)) { + const symbol = this.utils.trueSymbolAtLocation(expr); + + if (this.utils.isJsImport(expr)) { + const toNumberCall = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(expr, ts.factory.createIdentifier(TO_NUMBER)), + undefined, + [] + ); + + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, toNumberCall, expr.getSourceFile()); + + return [ + { + start: expr.getStart(), + end: expr.getEnd(), + replacementText + } + ]; + } + + const decl = symbol?.declarations?.find(ts.isVariableDeclaration); + if (decl?.initializer && ts.isPropertyAccessExpression(decl.initializer)) { + return this.fixPropertyAccessToNumber(decl.initializer); + } + } + + return undefined; + } + + private fixPropertyAccessToNumber(expr: ts.PropertyAccessExpression): Autofix[] { + const getPropCall = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(expr.expression, ts.factory.createIdentifier(GET_PROPERTY_BY_NAME)), + undefined, + [ts.factory.createStringLiteral(expr.name.getText())] + ); + + const toNumberCall = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(getPropCall, ts.factory.createIdentifier(TO_NUMBER)), + undefined, + [] + ); + + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, toNumberCall, expr.getSourceFile()); + + return [ + { + start: expr.getStart(), + end: expr.getEnd(), + replacementText + } + ]; + } + fixInteropArrayElementAccessExpression(express: ts.ElementAccessExpression): Autofix[] | undefined { const statements = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier(GET_PROPERTY_BY_INDEX)), @@ -3986,8 +4491,11 @@ export class Autofixer { const start = typeofExpress.getStart(); const end = typeofExpress.getEnd(); const processed = this.fixInterOpImportJsProcessNode(node); + if (!processed) { + return undefined; + } const replacementText = `${processed}.typeOf()`; - return replacementText ? [{ start, end, replacementText }] : undefined; + return [{ start, end, replacementText }]; } fixInteropInterfaceConvertNum(express: ts.PrefixUnaryExpression): Autofix[] | undefined { @@ -4122,7 +4630,7 @@ export class Autofixer { fixNoTsLikeFunctionCall(identifier: ts.Node): Autofix[] { void this; const funcName = identifier.getText(); - const replacementText = `${funcName}.unSafeCall`; + const replacementText = `${funcName}.unsafeCall`; return [ { replacementText, @@ -4209,24 +4717,208 @@ export class Autofixer { return !builtInTypes.has(type.typeName.getText()); } + fixLimitedVoidType( + node: ts.VariableDeclaration | ts.ParameterDeclaration | ts.PropertyDeclaration + ): Autofix[] | undefined { + const srcFile = node.getSourceFile(); + const newType = Autofixer.createNewTypeFromVoid(node.type); + const newInit = Autofixer.createNewInitializer(node.initializer, newType); + + const newDecl = Autofixer.createNewDeclaration(node, newType, newInit); + if (!newDecl) { + return undefined; + } + + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, newDecl, srcFile); + return [{ start: node.getStart(), end: node.getEnd(), replacementText }]; + } + + private static createNewTypeFromVoid(type: ts.TypeNode | undefined): ts.TypeNode { + const identUndefined = ts.factory.createIdentifier(UNDEFINED_NAME); + if (type && ts.isUnionTypeNode(type)) { + const updatedTypes = type.types.map((t) => { + return t.kind === ts.SyntaxKind.VoidKeyword ? ts.factory.createTypeReferenceNode(UNDEFINED_NAME) : t; + }); + return ts.factory.createUnionTypeNode(updatedTypes); + } + return ts.factory.createTypeReferenceNode(identUndefined); + } + + private static createNewInitializer(initializer: ts.Expression | undefined, newType: ts.TypeNode): ts.Expression { + const identUndefined = ts.factory.createIdentifier(UNDEFINED_NAME); + if (!initializer) { + return identUndefined; + } + + const stmts: ts.Statement[] = [ + ts.factory.createExpressionStatement(initializer), + ts.factory.createReturnStatement(identUndefined) + ]; + const funcBody = ts.factory.createBlock(stmts); + const arrowFunc = ts.factory.createArrowFunction( + undefined, + undefined, + [], + newType, + ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), + funcBody + ); + return ts.factory.createCallExpression(ts.factory.createParenthesizedExpression(arrowFunc), undefined, undefined); + } + + private static createNewDeclaration( + node: ts.VariableDeclaration | ts.ParameterDeclaration | ts.PropertyDeclaration, + newType: ts.TypeNode, + newInit: ts.Expression + ): ts.Node | undefined { + if (ts.isVariableDeclaration(node)) { + return ts.factory.createVariableDeclaration(node.name, node.exclamationToken, newType, newInit); + } + + if (ts.isParameter(node)) { + return ts.factory.createParameterDeclaration( + node.modifiers, + node.dotDotDotToken, + node.name, + node.questionToken, + newType, + node.initializer ? newInit : undefined + ); + } + + if (ts.isPropertyDeclaration(node)) { + const optionalToken = node.questionToken || node.exclamationToken; + return ts.factory.createPropertyDeclaration(node.modifiers, node.name, optionalToken, newType, newInit); + } + + return undefined; + } + + /** + * Fixes function declarations/expressions that return `void` as part of a union. + * Replaces `void` with `undefined` in the return type, + * replaces `return;` with `return undefined;`, + * and adds `return undefined;` if the function has no returns. + */ + fixLimitedVoidTypeFunction(fn: ts.FunctionLikeDeclaration): Autofix[] | undefined { + const fixes: Autofix[] = []; + const returnType = fn.type; + if (!returnType || !ts.isUnionTypeNode(returnType) || !TsUtils.typeContainsVoid(returnType)) { + return undefined; + } + + const updatedTypes = returnType.types.map((t) => { + return t.kind === ts.SyntaxKind.VoidKeyword ? ts.factory.createTypeReferenceNode(UNDEFINED_NAME) : t; + }); + + const newType = ts.factory.createUnionTypeNode(updatedTypes); + fixes.push({ + start: returnType.getStart(), + end: returnType.getEnd(), + replacementText: this.printer.printNode(ts.EmitHint.Unspecified, newType, fn.getSourceFile()) + }); + + let hasReturn = false; + function visit(node: ts.Node): void { + if (ts.isReturnStatement(node)) { + hasReturn = true; + if (!node.expression) { + fixes.push({ + start: node.getStart(), + end: node.getEnd(), + replacementText: 'return undefined;' + }); + } + } + ts.forEachChild(node, visit); + } + if (fn.body) { + visit(fn.body); + + if (!hasReturn) { + if (ts.isBlock(fn.body)) { + const lastBrace = fn.body.getEnd() - 1; + fixes.push({ + start: lastBrace, + end: lastBrace, + replacementText: '\nreturn undefined;\n' + }); + } + } + } + + return fixes; + } + + private fixGenericCallNoTypeArgsWithContextualType(node: ts.NewExpression): Autofix[] | undefined { + const contextualType = this.typeChecker.getContextualType(node); + if (!contextualType) { + return undefined; + } + + const typeArgs = Autofixer.getTypeArgumentsFromType(contextualType); + if (typeArgs.length === 0) { + return undefined; + } + const reference = typeArgs.map((arg) => { + return ts.factory.createTypeReferenceNode(this.typeChecker.typeToString(arg)); + }); + return this.generateGenericTypeArgumentsAutofix(node, reference); + } + fixGenericCallNoTypeArgs(node: ts.NewExpression): Autofix[] | undefined { const typeNode = this.getTypeNodeForNewExpression(node); - if (!typeNode || !ts.isTypeReferenceNode(typeNode) || typeNode.typeName.getText() !== node.expression.getText()) { + if (!typeNode) { + return this.fixGenericCallNoTypeArgsWithContextualType(node); + } + if (!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 typeArgsText = `<${typeNode.typeArguments?. + map((arg) => { + return this.printer.printNode(ts.EmitHint.Unspecified, arg, srcFile); + }). + join(', ')}>`; + + // Insert the type arguments immediately after the constructor name + const insertPos = node.expression.getEnd(); + return [{ start: insertPos, end: insertPos, replacementText: typeArgsText }]; + } + + private generateGenericTypeArgumentsAutofix( + node: ts.NewExpression, + typeArgs: ts.TypeReferenceNode[] + ): Autofix[] | undefined { const srcFile = node.getSourceFile(); const identifier = node.expression; const args = node.arguments; - const newExpression = ts.factory.createNewExpression(identifier, reference, args); + const hasValidArgs = typeArgs.some((arg) => { + return arg?.typeName && ts.isIdentifier(arg.typeName); + }); + if (!hasValidArgs) { + return undefined; + } + const hasAnyType = typeArgs.some((arg) => { + return ts.isIdentifier(arg?.typeName) && arg.typeName.text === 'any'; + }); + if (hasAnyType) { + return undefined; + } + const newExpression = ts.factory.createNewExpression(identifier, typeArgs, args); const text = this.printer.printNode(ts.EmitHint.Unspecified, newExpression, srcFile); return [{ start: node.getStart(), end: node.getEnd(), replacementText: text }]; } + static getTypeArgumentsFromType(type: ts.Type): ts.Type[] { + const typeReference = type as ts.TypeReference; + if (typeReference.typeArguments) { + return [...typeReference.typeArguments]; + } + return []; + } + private getTypeNodeForNewExpression(node: ts.NewExpression): ts.TypeNode | undefined { if (ts.isVariableDeclaration(node.parent) || ts.isPropertyDeclaration(node.parent)) { return node.parent.type; @@ -4250,6 +4942,80 @@ export class Autofixer { return undefined; } + private createJSInvokeCallExpression( + ident: ts.Expression, + method: string, + args: ts.Expression[] | undefined + ): ts.CallExpression | undefined { + if (ts.isNewExpression(ident)) { + const instantiatedClass = this.createJSInvokeCallExpression( + ident.expression, + INSTANTIATE, + this.createArgs(ident.arguments) + ); + if (!instantiatedClass) { + return undefined; + } + return this.createJSInvokeCallExpression(instantiatedClass, method, args); + } + return ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(ident, ts.factory.createIdentifier(method)), + undefined, + args + ); + } + + fixAwaitJsCallExpression(ident: ts.Identifier, args: ts.NodeArray | undefined): Autofix[] | undefined { + const newArgs = this.createArgs(args); + + const newCallExpr = this.createJSInvokeCallExpression(ident, INVOKE, newArgs); + if (!newCallExpr) { + return undefined; + } + + const replacedNode = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(newCallExpr, ts.factory.createIdentifier(TO_PROMISE)), + undefined, + undefined + ); + + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, replacedNode, ident.getSourceFile()); + return [{ start: ident.parent.getStart(), end: ident.parent.getEnd(), replacementText }]; + } + + fixAwaitJsMethodCallExpression( + ident: ts.Identifier, + args: ts.NodeArray | undefined + ): Autofix[] | undefined { + const propertyAccessExpr = ident.parent as ts.PropertyAccessExpression; + const accessedProperty = propertyAccessExpr.expression; + const newArgs = this.createArgs(args); + + const newCallExpr = this.createJSInvokeCallExpression(accessedProperty, INVOKE_METHOD, [ + ts.factory.createStringLiteral(ident.text), + ...newArgs || [] + ]); + + if (!newCallExpr) { + return undefined; + } + + const replacedNode = ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(newCallExpr, ts.factory.createIdentifier(TO_PROMISE)), + undefined, + undefined + ); + + const replacementText = this.printer.printNode(ts.EmitHint.Unspecified, replacedNode, ident.getSourceFile()); + return [{ start: propertyAccessExpr.parent.getStart(), end: propertyAccessExpr.parent.getEnd(), replacementText }]; + } + + fixAwaitJsPromise(ident: ts.Identifier): Autofix[] { + void this; + const replacementText = `${ident.text}.toPromise()`; + return [{ start: ident.getStart(), end: ident.getEnd(), replacementText }]; + } + fixMissingAttribute(node: ts.PropertyAccessExpression): Autofix[] { const exprName = node.expression.getText(); const propertyAccessExpr = ts.factory.createPropertyAccessExpression( @@ -4268,7 +5034,7 @@ export class Autofixer { fixCustomLayout(node: ts.StructDeclaration): Autofix[] { const startPos = Autofixer.getStartPositionWithoutDecorators(node); - const decorator = ts.factory.createDecorator(ts.factory.createIdentifier(CustomDecoratorName.Layoutable)); + const decorator = ts.factory.createDecorator(ts.factory.createIdentifier(CustomDecoratorName.CustomLayout)); const text = this.getNewLine() + this.printer.printNode(ts.EmitHint.Unspecified, decorator, node.getSourceFile()); return [{ start: startPos, end: startPos, replacementText: text }]; @@ -4285,6 +5051,35 @@ export class Autofixer { fixNumericLiteralIntToNumber(node: ts.NumericLiteral): Autofix[] | undefined { void this; - return [{ start: node.getStart(), end: node.getEnd(), replacementText: `${node.getText()}.0` }]; + let replacementText = node.getText(); + const parent = node.parent; + + if (ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.MinusToken) { + replacementText = `-${replacementText}.0`; + return [ + { + start: parent.getStart(), + end: node.getEnd(), + replacementText + } + ]; + } + + return [ + { + start: node.getStart(), + end: node.getEnd(), + replacementText: `${replacementText}.0` + } + ]; + } + + fixPropDecorator(node: ts.Decorator, decoratorName: string): Autofix[] { + const newDecorator = ts.factory.createDecorator( + ts.factory.createIdentifier(decoratorName + NEW_PROP_DECORATOR_SUFFIX) + ); + + const text = this.printer.printNode(ts.EmitHint.Unspecified, newDecorator, node.getSourceFile()); + return [{ start: node.getStart(), end: node.getEnd(), replacementText: text }]; } } diff --git a/ets2panda/linter/src/lib/autofixes/QuasiEditor.ts b/ets2panda/linter/src/lib/autofixes/QuasiEditor.ts index 462d6d8b13..7d8aad8513 100644 --- a/ets2panda/linter/src/lib/autofixes/QuasiEditor.ts +++ b/ets2panda/linter/src/lib/autofixes/QuasiEditor.ts @@ -20,6 +20,7 @@ import { Logger } from '../Logger'; import type { ProblemInfo } from '../ProblemInfo'; import type { Autofix } from './Autofixer'; import type { LinterOptions } from '../LinterOptions'; +import { USE_STATIC } from '../utils/consts/InteropAPI'; import { AUTOFIX_HTML_TEMPLATE_TEXT, AutofixHtmlTemplate } from './AutofixReportHtmlHelper'; const BACKUP_AFFIX = '~'; @@ -42,12 +43,6 @@ export class QuasiEditor { fs.copyFileSync(filePath, QuasiEditor.getBackupFileName(filePath)); } - static hasAnyAutofixes(problemInfos: ProblemInfo[]): boolean { - return problemInfos.some((problemInfo) => { - return problemInfo.autofix !== undefined; - }); - } - private generateReport(acceptedPatches: Autofix[]): void { const report = { filePath: this.srcFileName, @@ -95,14 +90,16 @@ export class QuasiEditor { } } - fix(problemInfos: ProblemInfo[]): string { + fix(problemInfos: ProblemInfo[], needAddUseStatic: boolean | undefined): string { const acceptedPatches = QuasiEditor.sortAndRemoveIntersections(problemInfos); - const result = this.applyFixes(acceptedPatches); + let result = this.applyFixes(acceptedPatches); if (this.linterOpts.migrationReport) { this.generateReport(acceptedPatches); } - + if (needAddUseStatic) { + result = QuasiEditor.addUseStaticDirective(result); + } return result; } @@ -196,4 +193,18 @@ export class QuasiEditor { */ return !(lhs.end < rhs.start || rhs.end < lhs.start); } + + private static addUseStaticDirective(content: string): string { + const lines = content.split('\n'); + if (lines.length > 0 && lines[0].trim() === USE_STATIC) { + return content; + } + return USE_STATIC + '\n' + content; + } + + static hasAnyAutofixes(problemInfos: ProblemInfo[]): boolean { + return problemInfos.some((problemInfo) => { + return problemInfo.autofix !== undefined; + }); + } } diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 2327bf026c..7aa8050e88 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -44,9 +44,8 @@ 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 { USE_STATIC } from './consts/InteropAPI'; import { ETS_MODULE, PATH_SEPARATOR, VALID_OHM_COMPONENTS_MODULE_PATH } from './consts/OhmUrl'; -import { EXTNAME_ETS, EXTNAME_JS } from './consts/ExtensionName'; +import { EXTNAME_ETS, EXTNAME_JS, EXTNAME_D_ETS } from './consts/ExtensionName'; import { STRING_ERROR_LITERAL } from './consts/Literals'; export const SYMBOL = 'Symbol'; @@ -2140,6 +2139,14 @@ export class TsUtils { return callSigns && callSigns.length > 0; } + static getFunctionReturnType(type: ts.Type): ts.Type | null { + const signatures = type.getCallSignatures(); + if (signatures.length === 0) { + return null; + } + return signatures[0].getReturnType(); + } + isStdFunctionType(type: ts.Type): boolean { const sym = type.getSymbol(); return !!sym && sym.getName() === 'Function' && this.isGlobalSymbol(sym); @@ -2175,8 +2182,10 @@ export class TsUtils { return true; } } - // We allow computed property names if expression is string literal or string Enum member - return ts.isStringLiteralLike(expr) || this.isEnumStringLiteral(computedProperty.expression); + // In ArkTS 1.0, the computed property names are allowed if expression is string literal or string Enum member. + return ( + !this.options.arkts2 && (ts.isStringLiteralLike(expr) || this.isEnumStringLiteral(computedProperty.expression)) + ); } skipPropertyInferredTypeCheck( @@ -3654,7 +3663,7 @@ export class TsUtils { ) { return false; } - + return true; } current = current.parent; @@ -3722,21 +3731,19 @@ export class TsUtils { return ( importSourceFile.fileName.endsWith(EXTNAME_ETS) && currentSourceFile.fileName.endsWith(EXTNAME_ETS) && - !TsUtils.isArkts12File(importSourceFile) && - TsUtils.isArkts12File(currentSourceFile) + !this.isArkts12File(importSourceFile) && + this.isArkts12File(currentSourceFile) ); } - static isArkts12File(sourceFile: ts.SourceFile): boolean { - if (!sourceFile?.statements.length) { + isArkts12File(sourceFile: ts.SourceFile): boolean { + if (!sourceFile?.fileName) { return false; } - const statements = sourceFile.statements; - return ( - ts.isExpressionStatement(statements[0]) && - ts.isStringLiteral(statements[0].expression) && - statements[0].expression.getText() === USE_STATIC - ); + if (sourceFile.fileName.endsWith(EXTNAME_D_ETS)) { + return true; + } + return !!this.options.inputFiles?.includes(path.normalize(sourceFile.fileName)); } static removeOrReplaceQuotes(str: string, isReplace: boolean): string { @@ -3808,4 +3815,13 @@ export class TsUtils { forEachNodeInSubtree(targetNode, callback, stopCondition); return found; } + + static typeContainsVoid(typeNode: ts.TypeNode): boolean { + if (ts.isUnionTypeNode(typeNode)) { + return typeNode.types.some((t) => { + return t.kind === ts.SyntaxKind.VoidKeyword; + }); + } + return typeNode.kind === ts.SyntaxKind.VoidKeyword; + } } diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 74a8769931..1f26e36e86 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -21,6 +21,7 @@ export const arkts2Rules: number[] = [ 37, 29, 111, + 134, 137, 139, 140, @@ -69,7 +70,6 @@ export const arkts2Rules: number[] = [ 261, 262, 263, - 264, 265, 266, 267, @@ -78,6 +78,12 @@ export const arkts2Rules: number[] = [ 270, 274, 275, + 281, + 282, + 283, + 284, + 285, + 286, 300, 301, 302, diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTSUtilsAPI.ts b/ets2panda/linter/src/lib/utils/consts/ArkTSUtilsAPI.ts index 8218ffc511..bae5dc65cc 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTSUtilsAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTSUtilsAPI.ts @@ -17,3 +17,5 @@ export const ASON_TEXT = 'ASON'; export const ASON_MODULES = ['@arkts.utils', '@kit.ArkTS']; export const JSON_TEXT = 'JSON'; export const ARKTS_UTILS_TEXT = 'ArkTSUtils'; + +export const ASON_WHITE_SET: Set = new Set(['stringify']); diff --git a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts index 159e986494..b12761975d 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts @@ -25,6 +25,7 @@ export const VALUE_IDENTIFIER = 'value'; export const INDENT_STEP = 2; export const MAKE_OBSERVED = 'makeObserved'; export const ARKUI_STATE_MANAGEMENT = '@ohos.arkui.StateManagement'; +export const NEW_PROP_DECORATOR_SUFFIX = 'Ref'; export enum CustomDecoratorName { Extend = 'Extend', @@ -33,7 +34,7 @@ export enum CustomDecoratorName { AnimatableExtend = 'AnimatableExtend', Memo = 'Memo', Observed = 'Observed', - Layoutable = 'Layoutable' + CustomLayout = 'CustomLayout' } export enum StorageTypeName { @@ -70,7 +71,10 @@ export const skipImportDecoratorName: Set = new Set([ 'Styles', 'Sendable', 'Concurrent', - 'LocalBuilder' + 'LocalBuilder', + 'Prop', + 'StorageProp', + 'LocalStorageProp' ]); export const customLayoutFunctionName: Set = new Set(['onMeasureSize', 'onPlaceChildren']); diff --git a/ets2panda/linter/src/lib/utils/consts/ArkuiImportList.ts b/ets2panda/linter/src/lib/utils/consts/ArkuiImportList.ts index 2a9e201f68..3adcc10ab5 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkuiImportList.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkuiImportList.ts @@ -262,6 +262,7 @@ export const arkuiImportList: Set = new Set([ 'CrownSensitivity', 'CurrentDayStyle', 'Curve', + 'CustomLayout', 'CustomBuilder', 'CustomComponent', 'CustomComponentV2', @@ -687,6 +688,7 @@ export const arkuiImportList: Set = new Set([ 'LocalStorage', 'LocalStorageLink', 'LocalStorageProp', + 'LocalStoragePropRef', 'LocalizedAlignRuleOptions', 'LocalizedAlignment', 'LocalizedBarrierDirection', @@ -1054,6 +1056,7 @@ export const arkuiImportList: Set = new Set([ 'ProgressStyleOptions', 'ProgressType', 'Prop', + 'PropRef', 'ProtectedResourceType', 'Provide', 'ProvideOptions', @@ -1100,6 +1103,7 @@ export const arkuiImportList: Set = new Set([ 'RenderProcessNotRespondingData', 'RenderProcessNotRespondingReason', 'RenderingContextSettings', + 'Repeat', 'RepeatAttribute', 'RepeatItem', 'RepeatMode', @@ -1321,6 +1325,7 @@ export const arkuiImportList: Set = new Set([ 'Storage', 'StorageLink', 'StorageProp', + 'StoragePropRef', 'StyleOptions', 'StyledString', 'StyledStringChangeValue', diff --git a/ets2panda/linter/src/lib/utils/consts/ArraysAPI.ts b/ets2panda/linter/src/lib/utils/consts/ArraysAPI.ts new file mode 100755 index 0000000000..4076fa0f93 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/ArraysAPI.ts @@ -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. + */ + +export const ARRAY_API_LIST = [ + 'length', + 'concat', + 'copyWithin', + 'entries', + 'every', + 'fill', + 'filter', + 'find', + 'findIndex', + 'flat', + 'flatMap', + 'forEach', + 'includes', + 'indexOf', + 'join', + 'keys', + 'lastIndexOf', + 'map', + 'pop', + 'push', + 'reduce', + 'reduceRight', + 'reverse', + 'shift', + 'slice', + 'some', + 'sort', + 'splice', + 'toLocaleString', + 'toString', + 'unshift', + 'values' +]; diff --git a/ets2panda/linter/src/lib/utils/consts/AssociatedInfo.ts b/ets2panda/linter/src/lib/utils/consts/AssociatedInfo.ts new file mode 100644 index 0000000000..2c3409d7ce --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/AssociatedInfo.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 { FaultID } from '../../Problems'; +import { SdkProblem } from './SdkWhitelist'; + +export const globalApiAssociatedInfo: Map = new Map([ + [SdkProblem.DeclWithDuplicateName, FaultID.DuplicateDeclNameFromSdk], + [SdkProblem.LimitedVoidType, FaultID.LimitedVoidTypeFromSdk] +]); diff --git a/ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets b/ets2panda/linter/src/lib/utils/consts/ErrorProp.ts similarity index 85% rename from ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets rename to ets2panda/linter/src/lib/utils/consts/ErrorProp.ts index 04eeeb8969..ce65497062 100644 --- a/ets2panda/linter/test/main/debugger_statememt.ets.migrate.ets +++ b/ets2panda/linter/src/lib/utils/consts/ErrorProp.ts @@ -13,10 +13,4 @@ * limitations under the License. */ -specialAutofixLib.debugger(); - -function a() { - specialAutofixLib.debugger(); -} - -console.log('debugger'); \ No newline at end of file +export const ERROR_PROP_LIST: Set = new Set(['name', 'message', 'stack', 'code']); diff --git a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts index c3566b66db..285a75b407 100644 --- a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts @@ -12,14 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import type * as ts from 'typescript'; -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 LENGTH = 'length'; export const INVOKE = 'invoke'; export const INVOKE_METHOD = 'invokeMethod'; +export const TO_PROMISE = 'toPromise'; +export const IS_INSTANCE_OF = 'isInstanceOf'; export const REFLECT_PROPERTIES = [ 'get', @@ -56,6 +59,8 @@ export const OBJECT_PROPERTIES = [ 'isFrozen', 'isSealed' ]; + +export const USE_STATIC = '\'use static\''; export const OBJECT_LITERAL = 'Object'; export const REFLECT_LITERAL = 'Reflect'; export const NONE = 'none'; @@ -73,3 +78,13 @@ export enum InteropType { LEGACY = '1.0', NONE = 'none' } + +export type IdentifierAndArguments = { + ident: undefined | ts.Identifier; + args: ts.NodeArray | undefined; +}; + +export type IncrementDecrementNodeInfo = { + varAssignText: string; + addOrDecrOperation: ts.BinaryExpression; +}; diff --git a/ets2panda/linter/src/lib/utils/consts/RuntimeCheckAPI.ts b/ets2panda/linter/src/lib/utils/consts/RuntimeCheckAPI.ts index 9fa38ab9fa..738c2b1872 100644 --- a/ets2panda/linter/src/lib/utils/consts/RuntimeCheckAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/RuntimeCheckAPI.ts @@ -17,7 +17,7 @@ import type ts from 'typescript'; export type ArrayAccess = { pos: number; - accessingIdentifier: 'number' | ts.Identifier; + accessingIdentifier: 'number' | ts.Identifier | ts.Expression; arrayIdent: ts.Identifier; }; diff --git a/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.arkts2.json b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.arkts2.json index 3625415854..2a6b56517a 100755 --- a/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.arkts2.json +++ b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.arkts2.json @@ -14,6 +14,16 @@ "limitations under the License." ], "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 56, + "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": 17, "column": 40, diff --git a/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.json b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.json index 8af4f78669..28c397d84b 100755 --- a/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.json +++ b/ets2panda/linter/test/builtin/builtin_symbol_iterator.ets.json @@ -13,5 +13,16 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 56, + "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" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/@ohos.taskpool.ets b/ets2panda/linter/test/concurrent/@ohos.taskpool.ets new file mode 100755 index 0000000000..52a0d01da6 --- /dev/null +++ b/ets2panda/linter/test/concurrent/@ohos.taskpool.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 func = ()=>void +export namespace taskpool{ + export function isConcurrent(param:func):boolean { + return true + } +} +export namespace otherTaskPool{ + export function isConcurrent(param:func):boolean { + return true + } +} diff --git a/ets2panda/linter/test/concurrent/@ohos.taskpool.ets.args.json b/ets2panda/linter/test/concurrent/@ohos.taskpool.ets.args.json new file mode 100755 index 0000000000..0adede204e --- /dev/null +++ b/ets2panda/linter/test/concurrent/@ohos.taskpool.ets.args.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." + ], + "mode": { + } +} diff --git a/ets2panda/linter/test/concurrent/@ohos.taskpool.ets.json b/ets2panda/linter/test/concurrent/@ohos.taskpool.ets.json new file mode 100755 index 0000000000..9f305c86d7 --- /dev/null +++ b/ets2panda/linter/test/concurrent/@ohos.taskpool.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/concurrent/concurrent_sharedarraybuffer1_arkts2.ets b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets new file mode 100755 index 0000000000..a0e9c55367 --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SharedArrayBuffer } from './oh_modules/sharedArrayBuffer' + +let s1 = new SharedArrayBuffer(1) //lib.es2017.sharedmemory.d.ts +s1.slice(0) +type sharedArray = SharedArrayBuffer +let s2: sharedArray; +type mapShare = Map +{ + let s1 = new SharedArrayBuffer(1) //lib.es2017.sharedmemory.d.ts + let s2:sharedArray; +} +function fun6(pa:sharedArray) { + let s1 = new SharedArrayBuffer(1) //lib.es2017.sharedmemory.d.ts + let s2:sharedArray; +} \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.args.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.args.json new file mode 100755 index 0000000000..3318ebbbcf --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_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_sharedarraybuffer1_arkts2.ets.arkts2.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.arkts2.json new file mode 100755 index 0000000000..ccc21ad852 --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.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": 32, + "endLine": 17, + "endColumn": 33, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 10, + "endLine": 18, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 34, + "endLine": 23, + "endColumn": 35, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 34, + "endLine": 27, + "endColumn": 35, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.autofix.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.autofix.json new file mode 100755 index 0000000000..bb890b9c3b --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.autofix.json @@ -0,0 +1,102 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 32, + "endLine": 17, + "endColumn": 33, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 724, + "end": 725, + "replacementText": "1.0", + "line": 17, + "column": 32, + "endLine": 17, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 10, + "endLine": 18, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 769, + "end": 770, + "replacementText": "0.0", + "line": 18, + "column": 10, + "endLine": 18, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 34, + "endLine": 23, + "endColumn": 35, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 917, + "end": 918, + "replacementText": "1.0", + "line": 23, + "column": 34, + "endLine": 23, + "endColumn": 35 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 34, + "endLine": 27, + "endColumn": 35, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1044, + "end": 1045, + "replacementText": "1.0", + "line": 27, + "column": 34, + "endLine": 27, + "endColumn": 35 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.json new file mode 100755 index 0000000000..fae7c2a3fe --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.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/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.migrate.ets b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.migrate.ets new file mode 100755 index 0000000000..9854ff5565 --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.migrate.ets @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SharedArrayBuffer } from './oh_modules/sharedArrayBuffer' + +let s1 = new SharedArrayBuffer(1.0) //lib.es2017.sharedmemory.d.ts +s1.slice(0.0) +type sharedArray = SharedArrayBuffer +let s2: sharedArray; +type mapShare = Map +{ + let s1 = new SharedArrayBuffer(1.0) //lib.es2017.sharedmemory.d.ts + let s2:sharedArray; +} +function fun6(pa:sharedArray) { + let s1 = new SharedArrayBuffer(1.0) //lib.es2017.sharedmemory.d.ts + let s2:sharedArray; +} \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.migrate.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.migrate.json new file mode 100755 index 0000000000..95e6d40d6a --- /dev/null +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer1_arkts2.ets.migrate.json @@ -0,0 +1,3 @@ +{ + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets index d3e0b2ca58..b6c511a7ad 100644 --- a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets @@ -21,4 +21,10 @@ 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 +function foo(atmo: Atomics) {} // NOT ERROR + +class A extends SharedArrayBuffer { + constructor() { + supper(1) + } +} diff --git a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.arkts2.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.arkts2.json index fa8024c8d3..c390c26562 100644 --- a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.arkts2.json +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.arkts2.json @@ -83,6 +83,26 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 26, + "column": 17, + "endLine": 26, + "endColumn": 34, + "problem": "SharedArrayBufferDeprecated", + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 16, + "endLine": 28, + "endColumn": 17, + "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/concurrent/concurrent_sharedarraybuffer_arkts2.ets.autofix.json b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.autofix.json index 01e6621c9d..4eea7766a3 100644 --- a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.autofix.json +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.autofix.json @@ -22,9 +22,9 @@ "problem": "SharedArrayBufferDeprecated", "autofix": [ { - "replacementText": "ArrayBuffer", "start": 624, "end": 641, + "replacementText": "ArrayBuffer", "line": 16, "column": 15, "endLine": 16, @@ -43,9 +43,9 @@ "problem": "SharedArrayBufferDeprecated", "autofix": [ { - "replacementText": "ArrayBuffer", "start": 661, "end": 678, + "replacementText": "ArrayBuffer", "line": 17, "column": 10, "endLine": 17, @@ -64,9 +64,9 @@ "problem": "SharedArrayBufferDeprecated", "autofix": [ { - "replacementText": "ArrayBuffer", "start": 685, "end": 702, + "replacementText": "ArrayBuffer", "line": 17, "column": 34, "endLine": 17, @@ -106,9 +106,9 @@ "problem": "SharedArrayBufferDeprecated", "autofix": [ { - "replacementText": "ArrayBuffer", "start": 737, "end": 754, + "replacementText": "ArrayBuffer", "line": 19, "column": 20, "endLine": 19, @@ -127,9 +127,9 @@ "problem": "SharedArrayBufferDeprecated", "autofix": [ { - "replacementText": "ArrayBuffer", "start": 853, "end": 870, + "replacementText": "ArrayBuffer", "line": 22, "column": 28, "endLine": 22, @@ -160,6 +160,48 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 26, + "column": 17, + "endLine": 26, + "endColumn": 34, + "problem": "SharedArrayBufferDeprecated", + "autofix": [ + { + "start": 945, + "end": 962, + "replacementText": "ArrayBuffer", + "line": 26, + "column": 17, + "endLine": 26, + "endColumn": 34 + } + ], + "suggest": "", + "rule": "SharedArrayBuffer is not supported (arkts-no-need-stdlib-sharedArrayBuffer)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 16, + "endLine": 28, + "endColumn": 17, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1000, + "end": 1001, + "replacementText": "1.0", + "line": 28, + "column": 16, + "endLine": 28, + "endColumn": 17 + } + ], + "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/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.ets b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.ets index 7a393ab10f..b7e398fb0a 100644 --- a/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.ets +++ b/ets2panda/linter/test/concurrent/concurrent_sharedarraybuffer_arkts2.ets.migrate.ets @@ -21,4 +21,10 @@ let newTypeName: NewTypeName // disable use new NewTypeName() let ntn: NewTypeName = new ArrayBuffer(0.0) // ERROR -function foo(atmo: Atomics) {} // NOT ERROR \ No newline at end of file +function foo(atmo: Atomics) {} // NOT ERROR + +class A extends ArrayBuffer { + constructor() { + supper(1.0) + } +} diff --git a/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json index ca28292f8e..428032b2d8 100644 --- a/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json @@ -15,24 +15,14 @@ ], "result": [ { - "line": 23, - "column": 32, - "endLine": 23, - "endColumn": 44, - "problem": "IsConcurrentDeprecated", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 12, + "problem": "LimitedStdLibNoDoncurrentDecorator", "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)", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets new file mode 100755 index 0000000000..2db768e0e8 --- /dev/null +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.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 { taskpool } from '@ohos.taskpool'; +import { taskpool as taskpool2 } from './@ohos.taskpool'; +import { otherTaskPool as taskpool1 } from './@ohos.taskpool'; + +function test1(){ +} +function isConcurrent() {} + +typeof taskpool.isConcurrent() ; //error +function test(){ + taskpool.isConcurrent(test5()) ; //error +} + +console.log(''+taskpool2.isConcurrent(test1)); + +taskpool2.isConcurrent(test1) +taskpool2.isConcurrent(test1) +taskpool2.isConcurrent(isConcurrent) +function test5(){ + taskpool2.isConcurrent(test1) + taskpool2.isConcurrent(test1) + taskpool2.isConcurrent(isConcurrent) +} +class Demo{ + get(){ + return taskpool1.isConcurrent(test); + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.args.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.args.json new file mode 100755 index 0000000000..e2b903f0aa --- /dev/null +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.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_isconcurrent2.ets.arkts2.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.arkts2.json new file mode 100755 index 0000000000..b418f42b21 --- /dev/null +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.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": 15, + "column": 1, + "endLine": 15, + "endColumn": 43, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 17, + "endLine": 23, + "endColumn": 29, + "problem": "IsConcurrentDeprecated", + "suggest": "", + "rule": "isConcurrent is not supported (arkts-limited-stdlib-no-support-isConcurrent)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 12, + "endLine": 25, + "endColumn": 24, + "problem": "IsConcurrentDeprecated", + "suggest": "", + "rule": "isConcurrent is not supported (arkts-limited-stdlib-no-support-isConcurrent)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 25, + "endLine": 25, + "endColumn": 32, + "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/concurrent/no_support_isconcurrent2.ets.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.json new file mode 100755 index 0000000000..b9331d05ba --- /dev/null +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.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/oh_modules/sharedArrayBuffer.ts b/ets2panda/linter/test/concurrent/oh_modules/sharedArrayBuffer.ts new file mode 100755 index 0000000000..cc5c84462f --- /dev/null +++ b/ets2panda/linter/test/concurrent/oh_modules/sharedArrayBuffer.ts @@ -0,0 +1,32 @@ +/* + * 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. + */ +// oh_modules/sharedArrayBuffer.ts +export interface SharedArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + +/** + * Returns a section of an SharedArrayBuffer. + */ + slice(begin: number, end?: number): SharedArrayBuffer; +} +interface SharedArrayBufferConstructor { + readonly prototype: SharedArrayBuffer; + new (byteLength: number): SharedArrayBuffer; +} +export declare var SharedArrayBuffer: SharedArrayBufferConstructor; + diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets b/ets2panda/linter/test/interop/binary_operation_js_obj.ets old mode 100755 new mode 100644 index 29bfa417e5..472ad5669d --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets @@ -12,8 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' -import {foo} from "./binary_operation_js_obj_js" +import {foo,m,n} from "./binary_operation_js_obj_js" let a = foo.a let b = foo.b a + b @@ -21,4 +20,24 @@ a - b a * b a / b a % b -a ** b \ No newline at end of file +a ** b + +m + n +m % n +m ** n + +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; + +foo.a + foo.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 index 3318ebbbcf..b13bb90d5b 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 @@ -1,21 +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" - } -} +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT 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/binary_operation_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json old mode 100755 new mode 100644 index f069ac9eeb..6734ea6018 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.arkts2.json @@ -15,29 +15,19 @@ ], "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, + "line": 15, "column": 1, - "endLine": 16, - "endColumn": 49, + "endLine": 15, + "endColumn": 53, "problem": "InterOpImportJs", "suggest": "", "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { - "line": 17, + "line": 16, "column": 9, - "endLine": 17, + "endLine": 16, "endColumn": 14, "problem": "InteropObjectProperty", "suggest": "", @@ -49,29 +39,29 @@ "column": 9, "endLine": 17, "endColumn": 14, - "problem": "InteropJsObjectUsage", + "problem": "InteropObjectProperty", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { "line": 18, - "column": 9, + "column": 1, "endLine": 18, - "endColumn": 14, - "problem": "InteropObjectProperty", + "endColumn": 2, + "problem": "BinaryOperations", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { "line": 18, - "column": 9, + "column": 5, "endLine": 18, - "endColumn": 14, - "problem": "InteropJsObjectUsage", + "endColumn": 6, + "problem": "BinaryOperations", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -166,8 +156,58 @@ }, { "line": 23, - "column": 5, + "column": 6, + "endLine": 23, + "endColumn": 7, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, "endLine": 23, + "endColumn": 5, + "problem": "ExponentOp", + "suggest": "", + "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 2, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 6, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 2, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, "endColumn": 6, "problem": "BinaryOperations", "suggest": "", @@ -175,9 +215,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 27, "column": 1, - "endLine": 24, + "endLine": 27, "endColumn": 2, "problem": "BinaryOperations", "suggest": "", @@ -185,9 +225,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 27, "column": 6, - "endLine": 24, + "endLine": 27, "endColumn": 7, "problem": "BinaryOperations", "suggest": "", @@ -195,14 +235,164 @@ "severity": "ERROR" }, { - "line": 24, + "line": 27, "column": 3, - "endLine": 24, + "endLine": 27, "endColumn": 5, "problem": "ExponentOp", "suggest": "", "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", "severity": "ERROR" + }, + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 10, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 9, + "endLine": 29, + "endColumn": 10, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 12, + "endLine": 29, + "endColumn": 17, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 17, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 3, + "endLine": 33, + "endColumn": 5, + "problem": "ExponentOp", + "suggest": "", + "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 11, + "endLine": 35, + "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": 35, + "column": 16, + "endLine": 35, + "endColumn": 17, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 22, + "endLine": 35, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 17, + "endLine": 37, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 4, + "endLine": 41, + "endColumn": 6, + "problem": "ExponentOp", + "suggest": "", + "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14, + "problem": "BinaryOperations", + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "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 old mode 100755 new mode 100644 index 18043cd8a0..8bf1b635a6 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json @@ -13,41 +13,31 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ +"result": [ { - "line": 16, + "line": 15, "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, + "endLine": 15, + "endColumn": 53, "problem": "InterOpImportJs", "autofix": [ { - "start": 617, - "end": 665, + "start": 604, + "end": 656, "replacementText": "", - "line": 16, + "line": 15, "column": 1, - "endLine": 16, - "endColumn": 49 + "endLine": 15, + "endColumn": 53 }, { - "start": 665, - "end": 665, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./binary_operation_js_obj_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", - "line": 16, + "start": 656, + "end": 656, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./binary_operation_js_obj_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet m = GeneratedImportVar_1.getPropertyByName('m');\nlet n = GeneratedImportVar_1.getPropertyByName('n');\n", + "line": 15, "column": 1, - "endLine": 16, - "endColumn": 49 + "endLine": 15, + "endColumn": 53 } ], "suggest": "", @@ -55,19 +45,19 @@ "severity": "ERROR" }, { - "line": 17, + "line": 16, "column": 9, - "endLine": 17, + "endLine": 16, "endColumn": 14, "problem": "InteropObjectProperty", "autofix": [ { - "start": 674, - "end": 679, + "start": 665, + "end": 670, "replacementText": "foo.getPropertyByName(\"a\")", - "line": 17, + "line": 16, "column": 9, - "endLine": 17, + "endLine": 16, "endColumn": 14 } ], @@ -80,12 +70,12 @@ "column": 9, "endLine": 17, "endColumn": 14, - "problem": "InteropJsObjectUsage", + "problem": "InteropObjectProperty", "autofix": [ { - "replacementText": "foo.getPropertyByName('a').toNumber()", - "start": 674, - "end": 679, + "start": 679, + "end": 684, + "replacementText": "foo.getPropertyByName(\"b\")", "line": 17, "column": 9, "endLine": 17, @@ -93,49 +83,49 @@ } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { "line": 18, - "column": 9, + "column": 1, "endLine": 18, - "endColumn": 14, - "problem": "InteropObjectProperty", + "endColumn": 2, + "problem": "BinaryOperations", "autofix": [ { - "start": 688, - "end": 693, - "replacementText": "foo.getPropertyByName(\"b\")", + "start": 665, + "end": 670, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", "line": 18, - "column": 9, + "column": 1, "endLine": 18, - "endColumn": 14 + "endColumn": 2 } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { "line": 18, - "column": 9, + "column": 5, "endLine": 18, - "endColumn": 14, - "problem": "InteropJsObjectUsage", + "endColumn": 6, + "problem": "BinaryOperations", "autofix": [ { - "replacementText": "foo.getPropertyByName('b').toNumber()", - "start": 688, - "end": 693, + "start": 679, + "end": 684, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", "line": 18, - "column": 9, + "column": 5, "endLine": 18, - "endColumn": 14 + "endColumn": 6 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { @@ -144,6 +134,17 @@ "endLine": 19, "endColumn": 2, "problem": "BinaryOperations", + "autofix": [ + { + "start": 665, + "end": 670, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 2 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" @@ -154,6 +155,17 @@ "endLine": 19, "endColumn": 6, "problem": "BinaryOperations", + "autofix": [ + { + "start": 679, + "end": 684, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 19, + "column": 5, + "endLine": 19, + "endColumn": 6 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" @@ -164,6 +176,17 @@ "endLine": 20, "endColumn": 2, "problem": "BinaryOperations", + "autofix": [ + { + "start": 665, + "end": 670, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 2 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" @@ -174,6 +197,17 @@ "endLine": 20, "endColumn": 6, "problem": "BinaryOperations", + "autofix": [ + { + "start": 679, + "end": 684, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 6 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" @@ -184,6 +218,17 @@ "endLine": 21, "endColumn": 2, "problem": "BinaryOperations", + "autofix": [ + { + "start": 665, + "end": 670, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 2 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" @@ -194,6 +239,17 @@ "endLine": 21, "endColumn": 6, "problem": "BinaryOperations", + "autofix": [ + { + "start": 679, + "end": 684, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 6 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" @@ -204,6 +260,17 @@ "endLine": 22, "endColumn": 2, "problem": "BinaryOperations", + "autofix": [ + { + "start": 665, + "end": 670, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 2 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" @@ -214,6 +281,17 @@ "endLine": 22, "endColumn": 6, "problem": "BinaryOperations", + "autofix": [ + { + "start": 679, + "end": 684, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 6 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" @@ -224,60 +302,533 @@ "endLine": 23, "endColumn": 2, "problem": "BinaryOperations", + "autofix": [ + { + "start": 665, + "end": 670, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 2 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { "line": 23, - "column": 5, + "column": 6, + "endLine": 23, + "endColumn": 7, + "problem": "BinaryOperations", + "autofix": [ + { + "start": 679, + "end": 684, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 23, + "column": 6, + "endLine": 23, + "endColumn": 7 + } + ], + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, "endLine": 23, + "endColumn": 5, + "problem": "ExponentOp", + "autofix": [ + { + "replacementText": "Math.pow(a, b)", + "start": 715, + "end": 721, + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 5 + } + ], + "suggest": "", + "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 2, + "problem": "BinaryOperations", + "autofix": [ + { + "start": 723, + "end": 724, + "replacementText": "m.toNumber()", + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, "endColumn": 6, "problem": "BinaryOperations", + "autofix": [ + { + "start": 727, + "end": 728, + "replacementText": "n.toNumber()", + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 6 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { - "line": 24, + "line": 26, "column": 1, - "endLine": 24, + "endLine": 26, "endColumn": 2, "problem": "BinaryOperations", + "autofix": [ + { + "start": 729, + "end": 730, + "replacementText": "m.toNumber()", + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 6, + "problem": "BinaryOperations", + "autofix": [ + { + "start": 733, + "end": 734, + "replacementText": "n.toNumber()", + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 6 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { - "line": 24, + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 2, + "problem": "BinaryOperations", + "autofix": [ + { + "start": 735, + "end": 736, + "replacementText": "m.toNumber()", + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 27, "column": 6, - "endLine": 24, + "endLine": 27, "endColumn": 7, "problem": "BinaryOperations", + "autofix": [ + { + "start": 740, + "end": 741, + "replacementText": "n.toNumber()", + "line": 27, + "column": 6, + "endLine": 27, + "endColumn": 7 + } + ], "suggest": "", "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", "severity": "ERROR" }, { - "line": 24, + "line": 27, "column": 3, - "endLine": 24, + "endLine": 27, "endColumn": 5, "problem": "ExponentOp", "autofix": [ { - "replacementText": "Math.pow(a, b)", - "start": 724, - "end": 730, - "line": 24, + "replacementText": "Math.pow(m, n)", + "start": 735, + "end": 741, + "line": 27, + "column": 3, + "endLine": 27, + "endColumn": 5 + } + ], + "suggest": "", + "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 747, + "end": 752, + "replacementText": "x: number = 1", + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 9, + "endLine": 29, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 751, + "end": 752, + "replacementText": "1.0", + "line": 29, + "column": 9, + "endLine": 29, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 12, + "endLine": 29, + "endColumn": 17, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 754, + "end": 759, + "replacementText": "y: number = 2", + "line": 29, + "column": 12, + "endLine": 29, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 17, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 758, + "end": 759, + "replacementText": "2.0", + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 3, + "endLine": 33, + "endColumn": 5, + "problem": "ExponentOp", + "autofix": [ + { + "replacementText": "Math.pow(x, y)", + "start": 782, + "end": 788, + "line": 33, "column": 3, - "endLine": 24, + "endLine": 33, "endColumn": 5 } ], "suggest": "", "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", "severity": "ERROR" + }, + { + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 12, + "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 791, + "end": 791, + "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n a: number;\n b: number;\n}\n", + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 12 + }, + { + "start": 798, + "end": 798, + "replacementText": ": GeneratedObjectLiteralInterface_1", + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 16, + "endLine": 35, + "endColumn": 17, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 806, + "end": 807, + "replacementText": "1.0", + "line": 35, + "column": 16, + "endLine": 35, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 22, + "endLine": 35, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 812, + "end": 813, + "replacementText": "2.0", + "line": 35, + "column": 22, + "endLine": 35, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 822, + "end": 832, + "replacementText": "x2: number = bar.a", + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 17, + "endLine": 37, + "endColumn": 27, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 834, + "end": 844, + "replacementText": "y2: number = bar.b", + "line": 37, + "column": 17, + "endLine": 37, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 4, + "endLine": 41, + "endColumn": 6, + "problem": "ExponentOp", + "autofix": [ + { + "replacementText": "Math.pow(x2, y2)", + "start": 873, + "end": 881, + "line": 41, + "column": 4, + "endLine": 41, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "exponent opartions \"**\" and \"**=\" are disabled (arkts-no-exponent-op)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6, + "problem": "BinaryOperations", + "autofix": [ + { + "start": 884, + "end": 889, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14, + "problem": "BinaryOperations", + "autofix": [ + { + "start": 892, + "end": 897, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Binary operations on js objects (arkts-interop-js2s-binary-op)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 884, + "end": 889, + "replacementText": "foo.getPropertyByName(\"a\")", + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 892, + "end": 897, + "replacementText": "foo.getPropertyByName(\"b\")", + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" } ] } \ 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 index 24e48e6dcb..e28baca176 100755 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.json @@ -15,13 +15,13 @@ ], "result": [ { - "line": 16, - "column": 1, - "endLine": 16, - "endColumn": 49, - "problem": "ImportAfterStatement", + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 12, + "problem": "ObjectLiteralNoContextType", "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "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/interop/binary_operation_js_obj.ets.migrate.ets b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets index 72c3c6c688..f29b91c275 100644 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets @@ -12,9 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' let GeneratedImportVar_1 = ESValue.load('./binary_operation_js_obj_js'); let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let m = GeneratedImportVar_1.getPropertyByName('m'); +let n = GeneratedImportVar_1.getPropertyByName('n'); let a = foo.getPropertyByName("a") let b = foo.getPropertyByName("b") @@ -23,4 +24,28 @@ a - b a * b a / b a % b -Math.pow(a, b) \ No newline at end of file +Math.pow(a, b) + +m.toNumber() + n.toNumber() +m.toNumber() % n.toNumber() +Math.pow(m.toNumber(), n.toNumber()) + +let x: number = 1.0, y: number = 2.0; +x + y; +x - y; +x % y; +Math.pow(x, y); + +interface GeneratedObjectLiteralInterface_1 { + a: number; + b: number; +} +let bar: GeneratedObjectLiteralInterface_1 = { a: 1.0, b: 2.0 }; + +let x2: number = bar.a, y2: number = bar.b; +x2 + y2; +x2 - y2; +x2 % y2; +Math.pow(x2, y2); + +foo.getPropertyByName("a").toNumber() + foo.getPropertyByName("b").toNumber(); \ 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 index 2caa23e507..817c2a9450 100644 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.json @@ -14,11 +14,21 @@ "limitations under the License." ], "result": [ + { + "line": 15, + "column": 5, + "endLine": 15, + "endColumn": 72, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, { "line": 16, "column": 5, "endLine": 16, - "endColumn": 72, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -28,17 +38,17 @@ "line": 17, "column": 5, "endLine": 17, - "endColumn": 56, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 5, - "endLine": 19, - "endColumn": 35, + "endLine": 18, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -55,14 +65,54 @@ "severity": "ERROR" }, { - "line": 26, + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 15, + "problem": "MathPow", + "suggest": "", + "rule": "function \"Math.pow()\" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)", + "severity": "ERROR" + }, + { + "line": 31, "column": 1, - "endLine": 26, + "endLine": 31, + "endColumn": 37, + "problem": "MathPow", + "suggest": "", + "rule": "function \"Math.pow()\" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 1, + "endLine": 37, "endColumn": 15, "problem": "MathPow", "suggest": "", "rule": "function \"Math.pow()\" behavior for ArkTS differs from Typescript version (arkts-math-pow-standard-diff)", "severity": "ERROR" + }, + { + "line": 49, + "column": 1, + "endLine": 49, + "endColumn": 17, + "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/binary_operation_js_obj_js.js b/ets2panda/linter/test/interop/binary_operation_js_obj_js.js index aaf9c1dd4e..c8f9951bda 100755 --- a/ets2panda/linter/test/interop/binary_operation_js_obj_js.js +++ b/ets2panda/linter/test/interop/binary_operation_js_obj_js.js @@ -14,3 +14,5 @@ */ export let foo = {a: 1, b: 2} +export let m = 3 +export let n = 2 \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_function.ets b/ets2panda/linter/test/interop/call_function.ets index b76d862f4a..74665b905c 100644 --- a/ets2panda/linter/test/interop/call_function.ets +++ b/ets2panda/linter/test/interop/call_function.ets @@ -1,19 +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' -import {foo,bar} from "./call_function_js" - -foo() +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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,bar} from "./call_function_js" + +foo() bar(123) \ 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 ed94001123..66335fa504 100644 --- a/ets2panda/linter/test/interop/call_function.ets.arkts2.json +++ b/ets2panda/linter/test/interop/call_function.ets.arkts2.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 16, + "line": 15, "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": 16, - "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 43, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 1, - "endLine": 18, + "endLine": 17, "endColumn": 6, "problem": "CallJSFunction", "suggest": "", @@ -45,9 +35,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 1, - "endLine": 19, + "endLine": 18, "endColumn": 9, "problem": "CallJSFunction", "suggest": "", @@ -55,9 +45,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 5, - "endLine": 19, + "endLine": 18, "endColumn": 8, "problem": "NumericSemantics", "suggest": "", diff --git a/ets2panda/linter/test/interop/call_function.ets.json b/ets2panda/linter/test/interop/call_function.ets.json index 08b4bd7b56..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/call_function.ets.json +++ b/ets2panda/linter/test/interop/call_function.ets.json @@ -13,16 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_object_methods.ets b/ets2panda/linter/test/interop/call_object_methods.ets index ee45f2bcf3..891ae57a57 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets +++ b/ets2panda/linter/test/interop/call_object_methods.ets @@ -12,7 +12,6 @@ * 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.arkts2.json b/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json index d088101b49..92c91ccd5b 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.arkts2.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 16, + "line": 15, "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": 16, - "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 47, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 1, - "endLine": 18, + "endLine": 17, "endColumn": 13, "problem": "InteropCallObjectMethods", "suggest": "", @@ -45,9 +35,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 9, - "endLine": 18, + "endLine": 17, "endColumn": 12, "problem": "NumericSemantics", "suggest": "", 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 85d3430d17..5776d747e9 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json @@ -15,38 +15,28 @@ ], "result": [ { - "line": 16, + "line": 15, "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": 16, - "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 47, "problem": "InterOpImportJs", "autofix": [ { - "start": 617, - "end": 663, + "start": 604, + "end": 650, "replacementText": "", - "line": 16, + "line": 15, "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 47 }, { - "start": 663, - "end": 663, + "start": 650, + "end": 650, "replacementText": "let GeneratedImportVar_1 = ESValue.load('./call_object_methods_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", - "line": 16, + "line": 15, "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 47 } ], @@ -55,36 +45,40 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 1, - "endLine": 18, + "endLine": 17, "endColumn": 13, "problem": "InteropCallObjectMethods", "autofix": [ - { - "start": 665, - "end": 677, - "replacementText": "foo.invokeMethod(\"bar\", ESValue.wrap(123))" - } + { + "start": 652, + "end": 664, + "replacementText": "foo.invokeMethod(\"bar\", ESValue.wrap(123))", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 13 + } ], "suggest": "", "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 9, - "endLine": 18, + "endLine": 17, "endColumn": 12, "problem": "NumericSemantics", "autofix": [ { - "start": 673, - "end": 676, + "start": 660, + "end": 663, "replacementText": "123.0", - "line": 18, + "line": 17, "column": 9, - "endLine": 18, + "endLine": 17, "endColumn": 12 } ], @@ -93,4 +87,4 @@ "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 index 8866623ce5..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.json @@ -13,16 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets index aeed85e300..2d455bda8e 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets +++ b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' let GeneratedImportVar_1 = ESValue.load('./call_object_methods_js'); let foo = GeneratedImportVar_1.getPropertyByName('foo'); diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json index 5399cc769e..4f96146af1 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 16, + "line": 15, "column": 5, - "endLine": 16, + "endLine": 15, "endColumn": 68, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 17, + "line": 16, "column": 5, - "endLine": 17, + "endLine": 16, "endColumn": 56, "problem": "AnyType", "suggest": "", @@ -35,4 +35,4 @@ "severity": "ERROR" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets old mode 100755 new mode 100644 index e1d4d726e4..9d1ec94c56 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets @@ -12,10 +12,14 @@ * 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 + +foo.num++ +++foo.num +foo.num-- +--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 index 3318ebbbcf..571ee6bb76 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 @@ -1,21 +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" - } -} +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT 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/increases_decreases_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json old mode 100755 new mode 100644 index 5e29c71a76..20513d8aad --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.arkts2.json @@ -15,19 +15,9 @@ ], "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, + "line": 15, "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 52, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 17, + "line": 16, "column": 16, - "endLine": 17, + "endLine": 16, "endColumn": 17, "problem": "NumericSemantics", "suggest": "", @@ -45,9 +35,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 5, - "endLine": 18, + "endLine": 17, "endColumn": 14, "problem": "InteropIncrementDecrement", "suggest": "", @@ -55,9 +45,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 5, - "endLine": 18, + "endLine": 17, "endColumn": 12, "problem": "InteropObjectProperty", "suggest": "", @@ -68,10 +58,20 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 12, - "problem": "InteropJsObjectUsage", + "endColumn": 14, + "problem": "InteropIncrementDecrement", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 14, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -86,83 +86,113 @@ }, { "line": 19, - "column": 7, + "column": 5, "endLine": 19, - "endColumn": 14, + "endColumn": 12, "problem": "InteropObjectProperty", "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, + "line": 20, + "column": 5, + "endLine": 20, "endColumn": 14, - "problem": "InteropJsObjectUsage", + "problem": "InteropIncrementDecrement", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { "line": 20, - "column": 5, + "column": 7, "endLine": 20, "endColumn": 14, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 10, "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, + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 8, "problem": "InteropObjectProperty", "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", + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 10, + "problem": "InteropIncrementDecrement", + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10, + "problem": "InteropObjectProperty", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { - "line": 21, - "column": 5, - "endLine": 21, - "endColumn": 14, + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 10, "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, + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 8, "problem": "InteropObjectProperty", "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", + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 10, + "problem": "InteropIncrementDecrement", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "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" } ] -} \ 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 old mode 100755 new mode 100644 index 0654070343..e48a8565b9 --- 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,39 +14,29 @@ "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, + { + "line": 15, "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 52, "problem": "InterOpImportJs", "autofix": [ { - "start": 617, - "end": 668, + "start": 604, + "end": 655, "replacementText": "", - "line": 16, + "line": 15, "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 52 }, { - "start": 668, - "end": 668, + "start": 655, + "end": 655, "replacementText": "let GeneratedImportVar_1 = ESValue.load('./increases_decreases_js_obj_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", - "line": 16, + "line": 15, "column": 1, - "endLine": 16, + "endLine": 15, "endColumn": 52 } ], @@ -55,19 +45,19 @@ "severity": "ERROR" }, { - "line": 17, + "line": 16, "column": 16, - "endLine": 17, + "endLine": 16, "endColumn": 17, "problem": "NumericSemantics", "autofix": [ { - "start": 684, - "end": 685, + "start": 671, + "end": 672, "replacementText": "0.0", - "line": 17, + "line": 16, "column": 16, - "endLine": 17, + "endLine": 16, "endColumn": 17 } ], @@ -76,29 +66,40 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 5, - "endLine": 18, + "endLine": 17, "endColumn": 14, "problem": "InteropIncrementDecrement", + "autofix": [ + { + "replacementText": "a = foo.getPropertyByName(\"num\").toNumber()\nfoo.setPropertyByName(num, a + 1)\na = a + 1\n", + "start": 673, + "end": 686, + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 14 + } + ], "suggest": "", "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 5, - "endLine": 18, + "endLine": 17, "endColumn": 12, "problem": "InteropObjectProperty", "autofix": [ { - "start": 690, - "end": 697, + "start": 677, + "end": 684, "replacementText": "foo.getPropertyByName(\"num\")", - "line": 18, + "line": 17, "column": 5, - "endLine": 18, + "endLine": 17, "endColumn": 12 } ], @@ -110,73 +111,84 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 12, - "problem": "InteropJsObjectUsage", + "endColumn": 14, + "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "foo.getPropertyByName('num').toNumber()", - "start": 690, - "end": 697, + "replacementText": "a = foo.getPropertyByName(\"num\").toNumber()\na = a + 1\nfoo.setPropertyByName(num, a)\n", + "start": 687, + "end": 700, "line": 18, "column": 5, "endLine": 18, - "endColumn": 12 + "endColumn": 14 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { - "line": 19, - "column": 5, - "endLine": 19, + "line": 18, + "column": 7, + "endLine": 18, "endColumn": 14, - "problem": "InteropIncrementDecrement", + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 693, + "end": 700, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 18, + "column": 7, + "endLine": 18, + "endColumn": 14 + } + ], "suggest": "", - "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { "line": 19, - "column": 7, + "column": 5, "endLine": 19, "endColumn": 14, - "problem": "InteropObjectProperty", + "problem": "InteropIncrementDecrement", "autofix": [ { - "start": 706, - "end": 713, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "a = foo.getPropertyByName(\"num\").toNumber()\nfoo.setPropertyByName(num, a - 1)\na = a - 1\n", + "start": 701, + "end": 714, "line": 19, - "column": 7, + "column": 5, "endLine": 19, "endColumn": 14 } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { "line": 19, - "column": 7, + "column": 5, "endLine": 19, - "endColumn": 14, - "problem": "InteropJsObjectUsage", + "endColumn": 12, + "problem": "InteropObjectProperty", "autofix": [ { - "replacementText": "foo.getPropertyByName('num').toNumber()", - "start": 706, - "end": 713, + "start": 705, + "end": 712, + "replacementText": "foo.getPropertyByName(\"num\")", "line": 19, - "column": 7, + "column": 5, "endLine": 19, - "endColumn": 14 + "endColumn": 12 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -185,25 +197,36 @@ "endLine": 20, "endColumn": 14, "problem": "InteropIncrementDecrement", + "autofix": [ + { + "replacementText": "a = foo.getPropertyByName(\"num\").toNumber()\na = a - 1\nfoo.setPropertyByName(num, a)\n", + "start": 715, + "end": 728, + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 14 + } + ], "suggest": "", "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { "line": 20, - "column": 5, + "column": 7, "endLine": 20, - "endColumn": 12, + "endColumn": 14, "problem": "InteropObjectProperty", "autofix": [ { - "start": 718, - "end": 725, + "start": 721, + "end": 728, "replacementText": "foo.getPropertyByName(\"num\")", "line": 20, - "column": 5, + "column": 7, "endLine": 20, - "endColumn": 12 + "endColumn": 14 } ], "suggest": "", @@ -211,51 +234,83 @@ "severity": "ERROR" }, { - "line": 20, - "column": 5, - "endLine": 20, - "endColumn": 12, - "problem": "InteropJsObjectUsage", + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 10, + "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "foo.getPropertyByName('num').toNumber()", - "start": 718, - "end": 725, - "line": 20, - "column": 5, - "endLine": 20, - "endColumn": 12 + "replacementText": "let tmp_1 = foo.getPropertyByName(\"num\").toNumber()\nfoo.setPropertyByName(num, tmp_1 + 1)\ntmp_1 = tmp_1 + 1\n", + "start": 730, + "end": 739, + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 10 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", "severity": "ERROR" }, { - "line": 21, - "column": 5, - "endLine": 21, - "endColumn": 14, + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 8, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 730, + "end": 737, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 8 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 10, "problem": "InteropIncrementDecrement", + "autofix": [ + { + "replacementText": "let tmp_2 = foo.getPropertyByName(\"num\").toNumber()\ntmp_2 = tmp_2 + 1\nfoo.setPropertyByName(num, tmp_2)\n", + "start": 740, + "end": 749, + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 10 + } + ], "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, + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10, "problem": "InteropObjectProperty", "autofix": [ { - "start": 734, - "end": 741, + "start": 742, + "end": 749, "replacementText": "foo.getPropertyByName(\"num\")", - "line": 21, - "column": 7, - "endLine": 21, - "endColumn": 14 + "line": 23, + "column": 3, + "endLine": 23, + "endColumn": 10 } ], "suggest": "", @@ -263,25 +318,88 @@ "severity": "ERROR" }, { - "line": 21, - "column": 7, - "endLine": 21, - "endColumn": 14, - "problem": "InteropJsObjectUsage", + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 10, + "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "foo.getPropertyByName('num').toNumber()", - "start": 734, - "end": 741, - "line": 21, - "column": 7, - "endLine": 21, - "endColumn": 14 + "replacementText": "let tmp_3 = foo.getPropertyByName(\"num\").toNumber()\nfoo.setPropertyByName(num, tmp_3 - 1)\ntmp_3 = tmp_3 - 1\n", + "start": 750, + "end": 759, + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 8, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 750, + "end": 757, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 8 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 10, + "problem": "InteropIncrementDecrement", + "autofix": [ + { + "replacementText": "let tmp_4 = foo.getPropertyByName(\"num\").toNumber()\ntmp_4 = tmp_4 - 1\nfoo.setPropertyByName(num, tmp_4)\n", + "start": 760, + "end": 769, + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 10 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Interop objects can't be incremented or decremented (arkts-interop-js2s-self-addtion-reduction)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 10, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 762, + "end": 769, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" } ] -} \ 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 index cf493da1d6..ca88f857e9 100755 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.json +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.json @@ -13,16 +13,5 @@ "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" - } - ] + "result": [] } \ 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 index 3be959d07a..f022ce0834 100644 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.ets +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.ets @@ -12,12 +12,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' let GeneratedImportVar_1 = ESValue.load('./increases_decreases_js_obj_js'); let foo = GeneratedImportVar_1.getPropertyByName('foo'); let a: number =0.0 -a = foo.getPropertyByName("num")++ -a = ++foo.getPropertyByName("num") -a = foo.getPropertyByName("num")-- -a = --foo.getPropertyByName("num") +a = foo.getPropertyByName("num").toNumber() +foo.setPropertyByName(num, a + 1.0) +a = a + 1.0 + +a = foo.getPropertyByName("num").toNumber() +a = a + 1.0 +foo.setPropertyByName(num, a) + +a = foo.getPropertyByName("num").toNumber() +foo.setPropertyByName(num, a - 1.0) +a = a - 1.0 + +a = foo.getPropertyByName("num").toNumber() +a = a - 1.0 +foo.setPropertyByName(num, a) + + +let tmp_1 = foo.getPropertyByName("num").toNumber() +foo.setPropertyByName(num, tmp_1 + 1.0) +tmp_1 = tmp_1 + 1.0 + +let tmp_2 = foo.getPropertyByName("num").toNumber() +tmp_2 = tmp_2 + 1.0 +foo.setPropertyByName(num, tmp_2) + +let tmp_3 = foo.getPropertyByName("num").toNumber() +foo.setPropertyByName(num, tmp_3 - 1.0) +tmp_3 = tmp_3 - 1.0 + +let tmp_4 = foo.getPropertyByName("num").toNumber() +tmp_4 = tmp_4 - 1.0 +foo.setPropertyByName(num, tmp_4) + 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 index f6439adcf2..0a10b6a69e 100644 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.json +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 16, + "line": 15, "column": 5, - "endLine": 16, + "endLine": 15, "endColumn": 75, "problem": "AnyType", "suggest": "", @@ -25,14 +25,54 @@ "severity": "ERROR" }, { - "line": 17, + "line": 16, "column": 5, - "endLine": 17, + "endLine": 16, "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": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 5, + "endLine": 44, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 5, + "endLine": 48, + "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/interop/instantiated_js_obj.ets b/ets2panda/linter/test/interop/instantiated_js_obj.ets index f24de83f1a..e4208df9fe 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets @@ -13,7 +13,6 @@ * limitations under the License. */ -'use static' import {Foo, Foo1} from "./instantiated_js_obj_js" class A { num: number = 1; 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 d5efb9f32d..f116dfb988 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.arkts2.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 17, + "line": 16, "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, + "endLine": 16, "endColumn": 51, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 19, - "endLine": 19, + "endLine": 18, "endColumn": 20, "problem": "NumericSemantics", "suggest": "", @@ -45,9 +35,9 @@ "severity": "ERROR" }, { - "line": 23, + "line": 22, "column": 1, - "endLine": 23, + "endLine": 22, "endColumn": 13, "problem": "InstantiatedJsOjbect", "suggest": "", @@ -55,9 +45,9 @@ "severity": "ERROR" }, { - "line": 23, + "line": 22, "column": 9, - "endLine": 23, + "endLine": 22, "endColumn": 12, "problem": "NumericSemantics", "suggest": "", @@ -65,9 +55,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 23, "column": 1, - "endLine": 24, + "endLine": 23, "endColumn": 17, "problem": "InstantiatedJsOjbect", "suggest": "", @@ -75,9 +65,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 24, "column": 1, - "endLine": 25, + "endLine": 24, "endColumn": 17, "problem": "InstantiatedJsOjbect", "suggest": "", @@ -85,9 +75,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 1, - "endLine": 27, + "endLine": 26, "endColumn": 15, "problem": "InstantiatedJsOjbect", "suggest": "", @@ -95,9 +85,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 27, "column": 1, - "endLine": 28, + "endLine": 27, "endColumn": 11, "problem": "InstantiatedJsOjbect", "suggest": "", @@ -105,9 +95,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 10, - "endLine": 30, + "endLine": 29, "endColumn": 11, "problem": "NumericSemantics", "suggest": "", @@ -115,9 +105,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 31, "column": 1, - "endLine": 32, + "endLine": 31, "endColumn": 16, "problem": "InstantiatedJsOjbect", "suggest": "", @@ -125,9 +115,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 32, "column": 1, - "endLine": 33, + "endLine": 32, "endColumn": 23, "problem": "InstantiatedJsOjbect", "suggest": "", @@ -135,9 +125,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 32, "column": 10, - "endLine": 33, + "endLine": 32, "endColumn": 13, "problem": "NumericSemantics", "suggest": "", 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 7a22b7b9aa..f9ae170771 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json @@ -15,38 +15,28 @@ ], "result": [ { - "line": 17, + "line": 16, "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, + "endLine": 16, "endColumn": 51, "problem": "InterOpImportJs", "autofix": [ { - "start": 618, - "end": 668, + "start": 605, + "end": 655, "replacementText": "", - "line": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 51 }, { - "start": 668, - "end": 668, + "start": 655, + "end": 655, "replacementText": "let GeneratedImportVar_1 = ESValue.load('./instantiated_js_obj_js');\nlet Foo = GeneratedImportVar_1.getPropertyByName('Foo');\nlet Foo1 = GeneratedImportVar_1.getPropertyByName('Foo1');\n", - "line": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 51 } ], @@ -55,19 +45,19 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 19, - "endLine": 19, + "endLine": 18, "endColumn": 20, "problem": "NumericSemantics", "autofix": [ { - "start": 697, - "end": 698, + "start": 684, + "end": 685, "replacementText": "1.0", - "line": 19, + "line": 18, "column": 19, - "endLine": 19, + "endLine": 18, "endColumn": 20 } ], @@ -76,19 +66,19 @@ "severity": "ERROR" }, { - "line": 23, + "line": 22, "column": 1, - "endLine": 23, + "endLine": 22, "endColumn": 13, "problem": "InstantiatedJsOjbect", "autofix": [ { - "start": 728, - "end": 740, + "start": 715, + "end": 727, "replacementText": "Foo.instantiate(ESValue.wrap(123))", - "line": 23, + "line": 22, "column": 1, - "endLine": 23, + "endLine": 22, "endColumn": 13 } ], @@ -97,19 +87,19 @@ "severity": "ERROR" }, { - "line": 23, + "line": 22, "column": 9, - "endLine": 23, + "endLine": 22, "endColumn": 12, "problem": "NumericSemantics", "autofix": [ { - "start": 736, - "end": 739, + "start": 723, + "end": 726, "replacementText": "123.0", - "line": 23, + "line": 22, "column": 9, - "endLine": 23, + "endLine": 22, "endColumn": 12 } ], @@ -118,19 +108,19 @@ "severity": "ERROR" }, { - "line": 24, + "line": 23, "column": 1, - "endLine": 24, + "endLine": 23, "endColumn": 17, "problem": "InstantiatedJsOjbect", "autofix": [ { - "start": 741, - "end": 757, + "start": 728, + "end": 744, "replacementText": "Foo.instantiate(ESValue.wrap('hello'))", - "line": 24, + "line": 23, "column": 1, - "endLine": 24, + "endLine": 23, "endColumn": 17 } ], @@ -139,19 +129,19 @@ "severity": "ERROR" }, { - "line": 25, + "line": 24, "column": 1, - "endLine": 25, + "endLine": 24, "endColumn": 17, "problem": "InstantiatedJsOjbect", "autofix": [ { - "start": 758, - "end": 774, + "start": 745, + "end": 761, "replacementText": "Foo.instantiate(ESValue.wrap(new A()))", - "line": 25, + "line": 24, "column": 1, - "endLine": 25, + "endLine": 24, "endColumn": 17 } ], @@ -160,19 +150,19 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 1, - "endLine": 27, + "endLine": 26, "endColumn": 15, "problem": "InstantiatedJsOjbect", "autofix": [ { - "start": 795, - "end": 809, + "start": 782, + "end": 796, "replacementText": "Foo.instantiate(ESValue.wrap(a.num))", - "line": 27, + "line": 26, "column": 1, - "endLine": 27, + "endLine": 26, "endColumn": 15 } ], @@ -181,19 +171,19 @@ "severity": "ERROR" }, { - "line": 28, + "line": 27, "column": 1, - "endLine": 28, + "endLine": 27, "endColumn": 11, "problem": "InstantiatedJsOjbect", "autofix": [ { - "start": 810, - "end": 820, + "start": 797, + "end": 807, "replacementText": "Foo.instantiate(ESValue.wrap(a))", - "line": 28, + "line": 27, "column": 1, - "endLine": 28, + "endLine": 27, "endColumn": 11 } ], @@ -202,19 +192,19 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 10, - "endLine": 30, + "endLine": 29, "endColumn": 11, "problem": "NumericSemantics", "autofix": [ { - "start": 856, - "end": 857, + "start": 843, + "end": 844, "replacementText": "1.0", - "line": 30, + "line": 29, "column": 10, - "endLine": 30, + "endLine": 29, "endColumn": 11 } ], @@ -223,19 +213,19 @@ "severity": "ERROR" }, { - "line": 32, + "line": 31, "column": 1, - "endLine": 32, + "endLine": 31, "endColumn": 16, "problem": "InstantiatedJsOjbect", "autofix": [ { - "start": 861, - "end": 876, + "start": 848, + "end": 863, "replacementText": "Foo.instantiate(ESValue.wrap(test()))", - "line": 32, + "line": 31, "column": 1, - "endLine": 32, + "endLine": 31, "endColumn": 16 } ], @@ -244,16 +234,20 @@ "severity": "ERROR" }, { - "line": 33, + "line": 32, "column": 1, - "endLine": 33, + "endLine": 32, "endColumn": 23, "problem": "InstantiatedJsOjbect", "autofix": [ { - "start": 877, - "end": 899, - "replacementText": "Foo1.instantiate(ESValue.wrap(123), ESValue.wrap('hello'))" + "start": 864, + "end": 886, + "replacementText": "Foo1.instantiate(ESValue.wrap(123), ESValue.wrap('hello'))", + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 23 } ], "suggest": "", @@ -261,19 +255,19 @@ "severity": "ERROR" }, { - "line": 33, + "line": 32, "column": 10, - "endLine": 33, + "endLine": 32, "endColumn": 13, "problem": "NumericSemantics", "autofix": [ { - "start": 886, - "end": 889, + "start": 873, + "end": 876, "replacementText": "123.0", - "line": 33, + "line": 32, "column": 10, - "endLine": 33, + "endLine": 32, "endColumn": 13 } ], diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.json index ad8f5eb1ae..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.json @@ -13,16 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets index 06c8b9ee78..b033816ddb 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets @@ -13,7 +13,6 @@ * limitations under the License. */ -'use static' let GeneratedImportVar_1 = ESValue.load('./instantiated_js_obj_js'); let Foo = GeneratedImportVar_1.getPropertyByName('Foo'); let Foo1 = GeneratedImportVar_1.getPropertyByName('Foo1'); diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json index 915dad64c5..2084de8763 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 17, + "line": 16, "column": 5, - "endLine": 17, + "endLine": 16, "endColumn": 68, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 5, - "endLine": 18, + "endLine": 17, "endColumn": 56, "problem": "AnyType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 5, - "endLine": 19, + "endLine": 18, "endColumn": 58, "problem": "AnyType", "suggest": "", @@ -45,4 +45,4 @@ "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 old mode 100755 new mode 100644 index e5fa5c03c7..02426a4318 --- a/ets2panda/linter/test/interop/interop_convert_import.ets +++ b/ets2panda/linter/test/interop/interop_convert_import.ets @@ -1,3 +1,4 @@ +<<<<<<< HEAD /* * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,4 +39,27 @@ return null_val as null === null;// 扫描出 arkts-interop-js2s-convert-js-type // convert type - undefined test_helper.test(() => { return undefined_val as undefined === undefined; // 扫描出 arkts-interop-js2s-convert-js-type - no pass -}, "undefined_val as undefined === undefined"); \ No newline at end of file +}, "undefined_val as undefined === undefined"); +======= +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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, foo2, foo3, foo4} from "./interop_convert_import_js.js" + + 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" +>>>>>>> efeb0a81e (modify use static spec) diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json old mode 100755 new mode 100644 index b6255d07e7..d6f91a557d --- a/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json @@ -1,268 +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": 17, - "column": 2, - "endLine": 17, - "endColumn": 106, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 17, - "column": 2, - "endLine": 17, - "endColumn": 106, - "problem": "InterOpImportJs", - "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 18, - "endLine": 19, - "endColumn": 35, - "problem": "InterOpConvertImport", - "suggest": "", - "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 18, - "endLine": 19, - "endColumn": 25, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "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": 20, - "column": 20, - "endLine": 20, - "endColumn": 41, - "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": 20, - "endLine": 20, - "endColumn": 29, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 20, - "endLine": 20, - "endColumn": 29, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 19, - "endLine": 21, - "endColumn": 38, - "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": 19, - "endLine": 21, - "endColumn": 27, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 19, - "endLine": 21, - "endColumn": 27, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 19, - "endLine": 22, - "endColumn": 38, - "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": 19, - "endLine": 22, - "endColumn": 27, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 19, - "endLine": 22, - "endColumn": 27, - "problem": "InteropJsObjectUsage", - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 9, - "endLine": 25, - "endColumn": 27, - "problem": "InterOpConvertImport", - "suggest": "", - "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 44, - "endLine": 25, - "endColumn": 62, - "problem": "GenericCallNoTypeArgs", - "suggest": "", - "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 54, - "endLine": 25, - "endColumn": 55, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 57, - "endLine": 25, - "endColumn": 58, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 60, - "endLine": 25, - "endColumn": 61, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 9, - "endLine": 30, - "endColumn": 30, - "problem": "InterOpConvertImport", - "suggest": "", - "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 48, - "endLine": 30, - "endColumn": 49, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 50, - "endLine": 30, - "endColumn": 51, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 52, - "endLine": 30, - "endColumn": 53, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 8, - "endLine": 35, - "endColumn": 24, - "problem": "InterOpConvertImport", - "suggest": "", - "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", - "severity": "ERROR" - }, - { - "line": 40, - "column": 8, - "endLine": 40, - "endColumn": 34, - "problem": "InterOpConvertImport", - "suggest": "", - "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", - "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": 2, + "endLine": 18, + "endColumn": 106, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 2, + "endLine": 18, + "endColumn": 106, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 18, + "endLine": 20, + "endColumn": 35, + "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": 18, + "endLine": 20, + "endColumn": 25, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 20, + "endLine": 21, + "endColumn": 41, + "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": 20, + "endLine": 21, + "endColumn": 29, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 19, + "endLine": 22, + "endColumn": 38, + "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": 19, + "endLine": 22, + "endColumn": 27, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 19, + "endLine": 23, + "endColumn": 38, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 19, + "endLine": 23, + "endColumn": 27, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 9, + "endLine": 26, + "endColumn": 27, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 44, + "endLine": 26, + "endColumn": 62, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 54, + "endLine": 26, + "endColumn": 55, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 57, + "endLine": 26, + "endColumn": 58, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 60, + "endLine": 26, + "endColumn": 61, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 9, + "endLine": 31, + "endColumn": 30, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 48, + "endLine": 31, + "endColumn": 49, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 50, + "endLine": 31, + "endColumn": 51, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 52, + "endLine": 31, + "endColumn": 53, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 8, + "endLine": 36, + "endColumn": 24, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 8, + "endLine": 41, + "endColumn": 34, + "problem": "InterOpConvertImport", + "suggest": "", + "rule": "Casting interop JS objects to primitive types is not allowed (arkts-interop-js2s-convert-js-type)", + "severity": "ERROR" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.autofix.json b/ets2panda/linter/test/interop/interop_convert_import.ets.autofix.json index 5aca1b631b..b49b275bb5 100644 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.autofix.json @@ -13,11 +13,11 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], -"result": [ + "result": [ { - "line": 17, + "line": 18, "column": 2, - "endLine": 17, + "endLine": 18, "endColumn": 106, "problem": "ImportAfterStatement", "suggest": "", @@ -25,28 +25,28 @@ "severity": "ERROR" }, { - "line": 17, + "line": 18, "column": 2, - "endLine": 17, + "endLine": 18, "endColumn": 106, "problem": "InterOpImportJs", "autofix": [ { - "start": 636, - "end": 740, + "start": 649, + "end": 753, "replacementText": "", - "line": 17, + "line": 18, "column": 2, - "endLine": 17, + "endLine": 18, "endColumn": 106 }, { - "start": 740, - "end": 740, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_convert_import_js.js');\r\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\r\nlet foo2 = GeneratedImportVar_1.getPropertyByName('foo2');\r\nlet foo3 = GeneratedImportVar_1.getPropertyByName('foo3');\r\nlet foo4 = GeneratedImportVar_1.getPropertyByName('foo4');\r\nlet array_val = GeneratedImportVar_1.getPropertyByName('array_val');\r\nlet null_val = GeneratedImportVar_1.getPropertyByName('null_val');\r\nlet undefined_val = GeneratedImportVar_1.getPropertyByName('undefined_val');\r\n", - "line": 17, + "start": 753, + "end": 753, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_convert_import_js.js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet foo2 = GeneratedImportVar_1.getPropertyByName('foo2');\nlet foo3 = GeneratedImportVar_1.getPropertyByName('foo3');\nlet foo4 = GeneratedImportVar_1.getPropertyByName('foo4');\nlet array_val = GeneratedImportVar_1.getPropertyByName('array_val');\nlet null_val = GeneratedImportVar_1.getPropertyByName('null_val');\nlet undefined_val = GeneratedImportVar_1.getPropertyByName('undefined_val');\n", + "line": 18, "column": 2, - "endLine": 17, + "endLine": 18, "endColumn": 106 } ], @@ -55,19 +55,19 @@ "severity": "ERROR" }, { - "line": 19, + "line": 20, "column": 18, - "endLine": 19, + "endLine": 20, "endColumn": 35, "problem": "InterOpConvertImport", "autofix": [ { - "start": 761, - "end": 778, + "start": 774, + "end": 791, "replacementText": "foo.getPropertyByName(\"num\").toNumber()", - "line": 19, + "line": 20, "column": 18, - "endLine": 19, + "endLine": 20, "endColumn": 35 } ], @@ -76,19 +76,19 @@ "severity": "ERROR" }, { - "line": 19, + "line": 20, "column": 18, - "endLine": 19, + "endLine": 20, "endColumn": 25, "problem": "InteropObjectProperty", "autofix": [ { - "start": 761, - "end": 768, + "start": 774, + "end": 781, "replacementText": "foo.getPropertyByName(\"num\")", - "line": 19, + "line": 20, "column": 18, - "endLine": 19, + "endLine": 20, "endColumn": 25 } ], @@ -97,40 +97,19 @@ "severity": "ERROR" }, { - "line": 19, - "column": 18, - "endLine": 19, - "endColumn": 25, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo.getPropertyByName('num')", - "start": 761, - "end": 768, - "line": 19, - "column": 18, - "endLine": 19, - "endColumn": 25 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 20, + "line": 21, "column": 20, - "endLine": 20, + "endLine": 21, "endColumn": 41, "problem": "InterOpConvertImport", "autofix": [ { - "start": 799, - "end": 820, + "start": 812, + "end": 833, "replacementText": "foo2.getPropertyByName(\"bool\").toBoolean()", - "line": 20, + "line": 21, "column": 20, - "endLine": 20, + "endLine": 21, "endColumn": 41 } ], @@ -139,19 +118,19 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 20, - "endLine": 20, + "endLine": 21, "endColumn": 29, "problem": "InteropObjectProperty", "autofix": [ { - "start": 799, - "end": 808, + "start": 812, + "end": 821, "replacementText": "foo2.getPropertyByName(\"bool\")", - "line": 20, + "line": 21, "column": 20, - "endLine": 20, + "endLine": 21, "endColumn": 29 } ], @@ -160,40 +139,19 @@ "severity": "ERROR" }, { - "line": 20, - "column": 20, - "endLine": 20, - "endColumn": 29, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo2.getPropertyByName('bool').toBoolean()", - "start": 799, - "end": 808, - "line": 20, - "column": 20, - "endLine": 20, - "endColumn": 29 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 21, + "line": 22, "column": 19, - "endLine": 21, + "endLine": 22, "endColumn": 38, "problem": "InterOpConvertImport", "autofix": [ { - "start": 840, - "end": 859, + "start": 853, + "end": 872, "replacementText": "foo3.getPropertyByName(\"str\").toString()", - "line": 21, + "line": 22, "column": 19, - "endLine": 21, + "endLine": 22, "endColumn": 38 } ], @@ -202,19 +160,19 @@ "severity": "ERROR" }, { - "line": 21, + "line": 22, "column": 19, - "endLine": 21, + "endLine": 22, "endColumn": 27, "problem": "InteropObjectProperty", "autofix": [ { - "start": 840, - "end": 848, + "start": 853, + "end": 861, "replacementText": "foo3.getPropertyByName(\"str\")", - "line": 21, + "line": 22, "column": 19, - "endLine": 21, + "endLine": 22, "endColumn": 27 } ], @@ -223,40 +181,19 @@ "severity": "ERROR" }, { - "line": 21, - "column": 19, - "endLine": 21, - "endColumn": 27, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo3.getPropertyByName('str').toString()", - "start": 840, - "end": 848, - "line": 21, - "column": 19, - "endLine": 21, - "endColumn": 27 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 22, + "line": 23, "column": 19, - "endLine": 22, + "endLine": 23, "endColumn": 38, "problem": "InterOpConvertImport", "autofix": [ { - "start": 879, - "end": 898, + "start": 892, + "end": 911, "replacementText": "foo4.getPropertyByName(\"big\").toBigInt()", - "line": 22, + "line": 23, "column": 19, - "endLine": 22, + "endLine": 23, "endColumn": 38 } ], @@ -265,19 +202,19 @@ "severity": "ERROR" }, { - "line": 22, + "line": 23, "column": 19, - "endLine": 22, + "endLine": 23, "endColumn": 27, "problem": "InteropObjectProperty", "autofix": [ { - "start": 879, - "end": 887, + "start": 892, + "end": 900, "replacementText": "foo4.getPropertyByName(\"big\")", - "line": 22, + "line": 23, "column": 19, - "endLine": 22, + "endLine": 23, "endColumn": 27 } ], @@ -286,30 +223,9 @@ "severity": "ERROR" }, { - "line": 22, - "column": 19, - "endLine": 22, - "endColumn": 27, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo4.getPropertyByName('big')", - "start": 879, - "end": 887, - "line": 22, - "column": 19, - "endLine": 22, - "endColumn": 27 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 25, + "line": 26, "column": 9, - "endLine": 25, + "endLine": 26, "endColumn": 27, "problem": "InterOpConvertImport", "suggest": "", @@ -317,9 +233,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 44, - "endLine": 25, + "endLine": 26, "endColumn": 62, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -327,19 +243,19 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 54, - "endLine": 25, + "endLine": 26, "endColumn": 55, "problem": "NumericSemantics", "autofix": [ { - "start": 981, - "end": 982, + "start": 994, + "end": 995, "replacementText": "1.0", - "line": 25, + "line": 26, "column": 54, - "endLine": 25, + "endLine": 26, "endColumn": 55 } ], @@ -348,19 +264,19 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 57, - "endLine": 25, + "endLine": 26, "endColumn": 58, "problem": "NumericSemantics", "autofix": [ { - "start": 984, - "end": 985, + "start": 997, + "end": 998, "replacementText": "2.0", - "line": 25, + "line": 26, "column": 57, - "endLine": 25, + "endLine": 26, "endColumn": 58 } ], @@ -369,19 +285,19 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 60, - "endLine": 25, + "endLine": 26, "endColumn": 61, "problem": "NumericSemantics", "autofix": [ { - "start": 987, - "end": 988, + "start": 1000, + "end": 1001, "replacementText": "3.0", - "line": 25, + "line": 26, "column": 60, - "endLine": 25, + "endLine": 26, "endColumn": 61 } ], @@ -390,9 +306,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 31, "column": 9, - "endLine": 30, + "endLine": 31, "endColumn": 30, "problem": "InterOpConvertImport", "suggest": "", @@ -400,19 +316,19 @@ "severity": "ERROR" }, { - "line": 30, + "line": 31, "column": 48, - "endLine": 30, + "endLine": 31, "endColumn": 49, "problem": "NumericSemantics", "autofix": [ { - "start": 1195, - "end": 1196, + "start": 1208, + "end": 1209, "replacementText": "1.0", - "line": 30, + "line": 31, "column": 48, - "endLine": 30, + "endLine": 31, "endColumn": 49 } ], @@ -421,19 +337,19 @@ "severity": "ERROR" }, { - "line": 30, + "line": 31, "column": 50, - "endLine": 30, + "endLine": 31, "endColumn": 51, "problem": "NumericSemantics", "autofix": [ { - "start": 1197, - "end": 1198, + "start": 1210, + "end": 1211, "replacementText": "2.0", - "line": 30, + "line": 31, "column": 50, - "endLine": 30, + "endLine": 31, "endColumn": 51 } ], @@ -442,19 +358,19 @@ "severity": "ERROR" }, { - "line": 30, + "line": 31, "column": 52, - "endLine": 30, + "endLine": 31, "endColumn": 53, "problem": "NumericSemantics", "autofix": [ { - "start": 1199, - "end": 1200, + "start": 1212, + "end": 1213, "replacementText": "3.0", - "line": 30, + "line": 31, "column": 52, - "endLine": 30, + "endLine": 31, "endColumn": 53 } ], @@ -463,9 +379,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 36, "column": 8, - "endLine": 35, + "endLine": 36, "endColumn": 24, "problem": "InterOpConvertImport", "suggest": "", @@ -473,9 +389,9 @@ "severity": "ERROR" }, { - "line": 40, + "line": 41, "column": 8, - "endLine": 40, + "endLine": 41, "endColumn": 34, "problem": "InterOpConvertImport", "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.json b/ets2panda/linter/test/interop/interop_convert_import.ets.json index ac2dfbe6f8..5a3f5938e4 100755 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.json @@ -1,28 +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": 106, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "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": 2, + "endLine": 18, + "endColumn": 106, + "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.ets.migrate.ets b/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.ets index a1c78f19fe..1e107cf338 100644 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.ets @@ -1,3 +1,54 @@ +<<<<<<< HEAD +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 = ESValue.load('./interop_convert_import_js.js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let foo2 = GeneratedImportVar_1.getPropertyByName('foo2'); +let foo3 = GeneratedImportVar_1.getPropertyByName('foo3'); +let foo4 = GeneratedImportVar_1.getPropertyByName('foo4'); +let array_val = GeneratedImportVar_1.getPropertyByName('array_val'); +let null_val = GeneratedImportVar_1.getPropertyByName('null_val'); +let undefined_val = GeneratedImportVar_1.getPropertyByName('undefined_val'); + + + let a: number = foo.getPropertyByName("num").toNumber() + let a1: boolean = foo2.getPropertyByName("bool").toBoolean() + let a2: string = foo3.getPropertyByName("str").toString() + let a3: bigint = foo4.getPropertyByName("big").toBigInt() + +test_helper.test(() => { +return (array_val as Array).toString() === new Array(1.0, 2.0, 3.0).toString();// 扫描出 arkts-interop-js2s-convert-js-type - no pass +}, "array_val as Array === [1, 2, 3]"); + +// convert type - Array +test_helper.test(() => { +return (array_val as number[]).toString() === [1.0,2.0,3.0].toString();// 扫描出 arkts-interop-js2s-convert-js-type - no pass +}, "array_val as Array === [1, 2, 3]"); + +// convert type - null +test_helper.test(() => { +return null_val as null === null;// 扫描出 arkts-interop-js2s-convert-js-type - no pass +}, "null_val as null === null"); + +// convert type - undefined +test_helper.test(() => { +return undefined_val as undefined === undefined; // 扫描出 arkts-interop-js2s-convert-js-type - no pass +}, "undefined_val as undefined === undefined"); +======= /* * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,38 +63,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - 'use static' - - let GeneratedImportVar_1 = ESValue.load('./interop_convert_import_js.js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); -let foo2 = GeneratedImportVar_1.getPropertyByName('foo2'); -let foo3 = GeneratedImportVar_1.getPropertyByName('foo3'); -let foo4 = GeneratedImportVar_1.getPropertyByName('foo4'); -let array_val = GeneratedImportVar_1.getPropertyByName('array_val'); -let null_val = GeneratedImportVar_1.getPropertyByName('null_val'); -let undefined_val = GeneratedImportVar_1.getPropertyByName('undefined_val'); - - - let a: number = foo.getPropertyByName("num").toNumber() - let a1: boolean = foo2.getPropertyByName("bool").toBoolean() - let a2: string = foo3.getPropertyByName("str").toString() - let a3: bigint = foo4.getPropertyByName("big").toBigInt() - -test_helper.test(() => { -return (array_val as Array).toString() === new Array(1.0, 2.0, 3.0).toString();// 扫描出 arkts-interop-js2s-convert-js-type - no pass -}, "array_val as Array === [1, 2, 3]"); - -// convert type - Array -test_helper.test(() => { -return (array_val as number[]).toString() === [1.0,2.0,3.0].toString();// 扫描出 arkts-interop-js2s-convert-js-type - no pass -}, "array_val as Array === [1, 2, 3]"); -// convert type - null -test_helper.test(() => { -return null_val as null === null;// 扫描出 arkts-interop-js2s-convert-js-type - no pass -}, "null_val as null === null"); + import {foo, foo2, foo3, foo4} from "./interop_convert_import_js.js" -// convert type - undefined -test_helper.test(() => { -return undefined_val as undefined === undefined; // 扫描出 arkts-interop-js2s-convert-js-type - no pass -}, "undefined_val as undefined === undefined"); \ 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" +>>>>>>> efeb0a81e (modify use static spec) diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.json b/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.json index 85e135ecca..a49b70a952 100644 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.json @@ -14,21 +14,11 @@ "limitations under the License." ], "result": [ - { - "line": 17, - "column": 6, - "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, + "column": 6, "endLine": 18, - "endColumn": 56, + "endColumn": 75, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +28,7 @@ "line": 19, "column": 5, "endLine": 19, - "endColumn": 58, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +58,7 @@ "line": 22, "column": 5, "endLine": 22, - "endColumn": 68, + "endColumn": 58, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -78,7 +68,7 @@ "line": 23, "column": 5, "endLine": 23, - "endColumn": 66, + "endColumn": 68, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -88,6 +78,16 @@ "line": 24, "column": 5, "endLine": 24, + "endColumn": 66, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, "endColumn": 76, "problem": "AnyType", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 34, "column": 44, - "endLine": 33, + "endLine": 34, "endColumn": 68, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 43, + "line": 44, "column": 8, - "endLine": 43, + "endLine": 44, "endColumn": 24, "problem": "InterOpConvertImport", "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets b/ets2panda/linter/test/interop/interop_equality_judgment.ets index 7fe09978d3..65ce20fddc 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets @@ -13,7 +13,6 @@ * limitations under the License. */ -'use static' import {a, b} from "./interop_equality_judgment_js" a == b a != b 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 916e1b51ca..920de865a7 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.arkts2.json @@ -15,23 +15,23 @@ ], "result": [ { - "line": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 52, - "problem": "ImportAfterStatement", + "problem": "InterOpImportJs", "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { "line": 17, "column": 1, "endLine": 17, - "endColumn": 52, - "problem": "InterOpImportJs", + "endColumn": 7, + "problem": "InteropEqualityJudgment", "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", "severity": "ERROR" }, { @@ -48,7 +48,7 @@ "line": 19, "column": 1, "endLine": 19, - "endColumn": 7, + "endColumn": 8, "problem": "InteropEqualityJudgment", "suggest": "", "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", @@ -63,16 +63,6 @@ "suggest": "", "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-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-interop-js2s-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 index c198972221..7145a50507 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json @@ -15,31 +15,29 @@ ], "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": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 52, "problem": "InterOpImportJs", "autofix": [ { - "start": 618, - "end": 669, - "replacementText": "" + "start": 605, + "end": 656, + "replacementText": "", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 52 }, { - "start": 669, - "end": 669, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_equality_judgment_js');\nlet a = GeneratedImportVar_1.getPropertyByName('a');\nlet b = GeneratedImportVar_1.getPropertyByName('b');\n" + "start": 656, + "end": 656, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_equality_judgment_js');\nlet a = GeneratedImportVar_1.getPropertyByName('a');\nlet b = GeneratedImportVar_1.getPropertyByName('b');\n", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 52 } ], "suggest": "", @@ -47,16 +45,20 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 1, - "endLine": 18, + "endLine": 17, "endColumn": 7, "problem": "InteropEqualityJudgment", "autofix": [ { - "start": 670, - "end": 676, - "replacementText": "a.areEqual(b)" + "start": 657, + "end": 663, + "replacementText": "a.areEqual(b)", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 7 } ], "suggest": "", @@ -64,16 +66,20 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 1, - "endLine": 19, + "endLine": 18, "endColumn": 7, "problem": "InteropEqualityJudgment", "autofix": [ { - "start": 677, - "end": 683, - "replacementText": "!a.areEqual(b)" + "start": 664, + "end": 670, + "replacementText": "!a.areEqual(b)", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 7 } ], "suggest": "", @@ -81,16 +87,20 @@ "severity": "ERROR" }, { - "line": 20, + "line": 19, "column": 1, - "endLine": 20, + "endLine": 19, "endColumn": 8, "problem": "InteropEqualityJudgment", "autofix": [ { - "start": 684, - "end": 691, - "replacementText": "a.areStrictlyEqual(b)" + "start": 671, + "end": 678, + "replacementText": "a.areStrictlyEqual(b)", + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 8 } ], "suggest": "", @@ -98,16 +108,20 @@ "severity": "ERROR" }, { - "line": 21, + "line": 20, "column": 1, - "endLine": 21, + "endLine": 20, "endColumn": 8, "problem": "InteropEqualityJudgment", "autofix": [ { - "start": 692, - "end": 699, - "replacementText": "!a.areStrictlyEqual(b)" + "start": 679, + "end": 686, + "replacementText": "!a.areStrictlyEqual(b)", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 8 } ], "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.json index e48cf9a99b..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.json @@ -13,16 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets index 8bbbd750c9..796cf7f898 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets @@ -13,7 +13,6 @@ * limitations under the License. */ -'use static' let GeneratedImportVar_1 = ESValue.load('./interop_equality_judgment_js'); let a = GeneratedImportVar_1.getPropertyByName('a'); let b = GeneratedImportVar_1.getPropertyByName('b'); diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json index a3c218b7b2..c3d33e531c 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 17, + "line": 16, "column": 5, - "endLine": 17, + "endLine": 16, "endColumn": 74, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 5, - "endLine": 18, + "endLine": 17, "endColumn": 52, "problem": "AnyType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 5, - "endLine": 19, + "endLine": 18, "endColumn": 52, "problem": "AnyType", "suggest": "", @@ -45,4 +45,4 @@ "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 index 4e6b76262c..e729a7c2c3 100644 --- a/ets2panda/linter/test/interop/interop_export_js_rules.ets +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' import { ff1 } from "./interop_import_js_rules_js" 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 index 4fc44d8a3c..1f92c538cd 100644 --- a/ets2panda/linter/test/interop/interop_export_js_rules.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.arkts2.json @@ -1,88 +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", - "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" - }, - { - "line": 27, - "column": 1, - "endLine": 27, - "endColumn": 57, - "problem": "InteropArkTs1ObjectExport", - "suggest": "", - "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 59, - "problem": "InteropJsObjectExport", - "suggest": "", - "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", - "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": 1, + "endLine": 16, + "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": 13, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 51, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 57, + "problem": "InteropArkTs1ObjectExport", + "suggest": "", + "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 57, + "problem": "InteropArkTs1ObjectExport", + "suggest": "", + "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 57, + "problem": "InteropArkTs1ObjectExport", + "suggest": "", + "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 59, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets.json b/ets2panda/linter/test/interop/interop_export_js_rules.ets.json index 91f5b61ed1..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/interop_export_js_rules.ets.json +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.json @@ -1,28 +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": [ - { - "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" - } - ] -} + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES 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/interop_import_js.ets b/ets2panda/linter/test/interop/interop_import_js.ets old mode 100755 new mode 100644 index 3325f1bdd9..337d1600c6 --- a/ets2panda/linter/test/interop/interop_import_js.ets +++ b/ets2panda/linter/test/interop/interop_import_js.ets @@ -13,7 +13,6 @@ * 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"; 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 17f26fd8dc..7d56ee5afd 100755 --- a/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.arkts2.json @@ -15,13 +15,13 @@ ], "result": [ { - "line": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 38, - "problem": "ImportAfterStatement", + "problem": "InterOpImportJs", "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { @@ -38,17 +38,7 @@ "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, + "endColumn": 64, "problem": "InterOpImportJs", "suggest": "", "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", @@ -58,17 +48,7 @@ "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, + "endColumn": 44, "problem": "InterOpImportJs", "suggest": "", "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", @@ -78,17 +58,7 @@ "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, + "endColumn": 57, "problem": "InterOpImportJs", "suggest": "", "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", @@ -98,17 +68,7 @@ "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, + "endColumn": 53, "problem": "InterOpImportJs", "suggest": "", "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", @@ -118,36 +78,6 @@ "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-interop-js2s-import-js)", - "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": "", 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 295af0943a..bda0908dba 100755 --- a/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json @@ -15,31 +15,29 @@ ], "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, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 38, "problem": "InterOpImportJs", "autofix": [ { - "start": 619, - "end": 656, - "replacementText": "" + "start": 606, + "end": 643, + "replacementText": "", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 38 }, { - "start": 971, - "end": 971, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('../main/js_lib');\nlet Cjs = GeneratedImportVar_1.getPropertyByName('Cjs');\n" + "start": 958, + "end": 958, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('../main/js_lib');\nlet Cjs = GeneratedImportVar_1.getPropertyByName('Cjs');\n", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 38 } ], "suggest": "", @@ -47,31 +45,29 @@ "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, + "line": 17, "column": 1, - "endLine": 18, + "endLine": 17, "endColumn": 38, "problem": "InterOpImportJs", "autofix": [ { - "start": 657, - "end": 694, - "replacementText": "" + "start": 644, + "end": 681, + "replacementText": "", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 38 }, { - "start": 971, - "end": 971, - "replacementText": "let GeneratedImportVar_2 = ESValue.load('../main/js_lib');\nlet fjs = GeneratedImportVar_2.getPropertyByName('fjs');\n" + "start": 958, + "end": 958, + "replacementText": "let GeneratedImportVar_2 = ESValue.load('../main/js_lib');\nlet fjs = GeneratedImportVar_2.getPropertyByName('fjs');\n", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 38 } ], "suggest": "", @@ -79,31 +75,29 @@ "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, + "line": 18, "column": 1, - "endLine": 19, + "endLine": 18, "endColumn": 64, "problem": "InterOpImportJs", "autofix": [ { - "start": 695, - "end": 758, - "replacementText": "" + "start": 682, + "end": 745, + "replacementText": "", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 64 }, { - "start": 971, - "end": 971, - "replacementText": "let GeneratedImportVar_3 = ESValue.load('./jsfiles/preview_import_js');\nlet CPreview = GeneratedImportVar_3.getPropertyByName('CPreview');\nlet bar = GeneratedImportVar_3.getPropertyByName('bar');\nlet foo = GeneratedImportVar_3.getPropertyByName('foo');\n" + "start": 958, + "end": 958, + "replacementText": "let GeneratedImportVar_3 = ESValue.load('./jsfiles/preview_import_js');\nlet CPreview = GeneratedImportVar_3.getPropertyByName('CPreview');\nlet bar = GeneratedImportVar_3.getPropertyByName('bar');\nlet foo = GeneratedImportVar_3.getPropertyByName('foo');\n", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 64 } ], "suggest": "", @@ -111,31 +105,29 @@ "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, + "line": 19, "column": 1, - "endLine": 20, + "endLine": 19, "endColumn": 44, "problem": "InterOpImportJs", "autofix": [ { - "start": 759, - "end": 802, - "replacementText": "" + "start": 746, + "end": 789, + "replacementText": "", + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 44 }, { - "start": 971, - "end": 971, - "replacementText": "let GeneratedImportVar_4 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_4.getPropertyByName('aaa');\n" + "start": 958, + "end": 958, + "replacementText": "let GeneratedImportVar_4 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_4.getPropertyByName('aaa');\n", + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 44 } ], "suggest": "", @@ -143,31 +135,29 @@ "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, + "line": 20, "column": 1, - "endLine": 21, + "endLine": 20, "endColumn": 57, "problem": "InterOpImportJs", "autofix": [ { - "start": 803, - "end": 859, - "replacementText": "" + "start": 790, + "end": 846, + "replacementText": "", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 57 }, { - "start": 971, - "end": 971, - "replacementText": "let GeneratedImportVar_5 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_5.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_5.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_5.getPropertyByName('Dog');\n" + "start": 958, + "end": 958, + "replacementText": "let GeneratedImportVar_5 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_5.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_5.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_5.getPropertyByName('Dog');\n", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 57 } ], "suggest": "", @@ -175,31 +165,29 @@ "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, + "line": 21, "column": 1, - "endLine": 22, + "endLine": 21, "endColumn": 53, "problem": "InterOpImportJs", "autofix": [ { - "start": 860, - "end": 912, - "replacementText": "" + "start": 847, + "end": 899, + "replacementText": "", + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 53 }, { - "start": 971, - "end": 971, - "replacementText": "let GeneratedImportVar_6 = ESValue.load('./interop_import_js_js');\n" + "start": 958, + "end": 958, + "replacementText": "let GeneratedImportVar_6 = ESValue.load('./interop_import_js_js');\n", + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 53 } ], "suggest": "", @@ -207,31 +195,29 @@ "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, + "line": 22, "column": 1, - "endLine": 23, + "endLine": 22, "endColumn": 59, "problem": "InterOpImportJs", "autofix": [ { - "start": 913, - "end": 971, - "replacementText": "" + "start": 900, + "end": 958, + "replacementText": "", + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 59 }, { - "start": 971, - "end": 971, - "replacementText": "let GeneratedImportVar_7 = ESValue.load('./interop_import_js_js');\nlet Wiki = GeneratedImportVar_7.getPropertyByName('Wiki');\nlet Doge = GeneratedImportVar_7.getPropertyByName('Dog');\n" + "start": 958, + "end": 958, + "replacementText": "let GeneratedImportVar_7 = ESValue.load('./interop_import_js_js');\nlet Wiki = GeneratedImportVar_7.getPropertyByName('Wiki');\nlet Doge = GeneratedImportVar_7.getPropertyByName('Dog');\n", + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 59 } ], "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.json b/ets2panda/linter/test/interop/interop_import_js.ets.json index c75509e775..ca88f857e9 100755 --- a/ets2panda/linter/test/interop/interop_import_js.ets.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.json @@ -13,76 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets index 4aa7a4bbf1..80f88726e3 100644 --- a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets @@ -13,7 +13,6 @@ * limitations under the License. */ -'use static' diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json index 625afb93e1..c422eb1668 100644 --- a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json @@ -14,11 +14,21 @@ "limitations under the License." ], "result": [ + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 66, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, { "line": 23, "column": 5, "endLine": 23, - "endColumn": 66, + "endColumn": 58, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -28,7 +38,7 @@ "line": 24, "column": 5, "endLine": 24, - "endColumn": 58, + "endColumn": 57, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +48,7 @@ "line": 25, "column": 5, "endLine": 25, - "endColumn": 57, + "endColumn": 66, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +68,7 @@ "line": 27, "column": 5, "endLine": 27, - "endColumn": 66, + "endColumn": 58, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +78,7 @@ "line": 28, "column": 5, "endLine": 28, - "endColumn": 58, + "endColumn": 62, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -78,7 +88,7 @@ "line": 29, "column": 5, "endLine": 29, - "endColumn": 62, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -88,7 +98,7 @@ "line": 30, "column": 5, "endLine": 30, - "endColumn": 56, + "endColumn": 66, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -98,7 +108,7 @@ "line": 31, "column": 5, "endLine": 31, - "endColumn": 66, + "endColumn": 58, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -108,7 +118,7 @@ "line": 32, "column": 5, "endLine": 32, - "endColumn": 58, + "endColumn": 71, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -118,7 +128,7 @@ "line": 33, "column": 5, "endLine": 33, - "endColumn": 71, + "endColumn": 66, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -128,7 +138,7 @@ "line": 34, "column": 5, "endLine": 34, - "endColumn": 66, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -148,7 +158,7 @@ "line": 36, "column": 5, "endLine": 36, - "endColumn": 56, + "endColumn": 58, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -158,7 +168,7 @@ "line": 37, "column": 5, "endLine": 37, - "endColumn": 58, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -168,7 +178,7 @@ "line": 38, "column": 5, "endLine": 38, - "endColumn": 56, + "endColumn": 58, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -178,16 +188,6 @@ "line": 39, "column": 5, "endLine": 39, - "endColumn": 58, - "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": "", @@ -195,4 +195,4 @@ "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 496fe91c55..bc81463101 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets @@ -13,7 +13,6 @@ * limitations under the License. */ -'use static' import {foo, m, n} from "./interop_import_js_compare_js" let a = foo.a 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 index e2b903f0aa..571ee6bb76 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets.args.json +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.args.json @@ -1,5 +1,5 @@ { - "copyright": [ + "copyright": [ "Copyright (c) 2025 Huawei Device Co., Ltd.", "Licensed under the Apache License, Version 2.0 (the 'License');", "you may not use this file except in compliance with the License.", @@ -12,8 +12,10 @@ "WITHOUT 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 + ], + "mode": { + "arkts2": "", + "autofix": "--arkts-2", + "migrate": "--arkts-2" + } +} 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 4ce217d61e..620252abbf 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 @@ -15,19 +15,9 @@ ], "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, + "line": 17, "column": 1, - "endLine": 18, + "endLine": 17, "endColumn": 57, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 9, - "endLine": 19, + "endLine": 18, "endColumn": 14, "problem": "InteropObjectProperty", "suggest": "", @@ -49,29 +39,29 @@ "column": 9, "endLine": 19, "endColumn": 14, - "problem": "InteropJsObjectUsage", + "problem": "InteropObjectProperty", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { "line": 20, - "column": 9, + "column": 1, "endLine": 20, - "endColumn": 14, - "problem": "InteropObjectProperty", + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { "line": 20, - "column": 9, + "column": 5, "endLine": 20, - "endColumn": 14, - "problem": "InteropJsObjectUsage", + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", "severity": "ERROR" }, { @@ -106,9 +96,9 @@ }, { "line": 22, - "column": 5, + "column": 6, "endLine": 22, - "endColumn": 6, + "endColumn": 7, "problem": "InterOpImportJsDataCompare", "suggest": "", "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", @@ -136,28 +126,8 @@ }, { "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-interop-js2s-compare-js-data)", - "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-interop-js2s-compare-js-data)", - "severity": "ERROR" - }, - { - "line": 25, "column": 5, - "endLine": 25, + "endLine": 24, "endColumn": 6, "problem": "NumericSemantics", "suggest": "", @@ -165,9 +135,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 1, - "endLine": 27, + "endLine": 26, "endColumn": 2, "problem": "InterOpImportJsDataCompare", "suggest": "", @@ -175,9 +145,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 5, - "endLine": 27, + "endLine": 26, "endColumn": 6, "problem": "InterOpImportJsDataCompare", "suggest": "", @@ -185,9 +155,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 27, "column": 5, - "endLine": 28, + "endLine": 27, "endColumn": 6, "problem": "NumericSemantics", "suggest": "", @@ -195,9 +165,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 5, - "endLine": 30, + "endLine": 29, "endColumn": 10, "problem": "NumericSemantics", "suggest": "", @@ -205,9 +175,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 9, - "endLine": 30, + "endLine": 29, "endColumn": 10, "problem": "NumericSemantics", "suggest": "", @@ -215,9 +185,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 12, - "endLine": 30, + "endLine": 29, "endColumn": 17, "problem": "NumericSemantics", "suggest": "", @@ -225,9 +195,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 16, - "endLine": 30, + "endLine": 29, "endColumn": 17, "problem": "NumericSemantics", "suggest": "", @@ -235,9 +205,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 35, "column": 11, - "endLine": 36, + "endLine": 35, "endColumn": 12, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -245,9 +215,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 35, "column": 16, - "endLine": 36, + "endLine": 35, "endColumn": 17, "problem": "NumericSemantics", "suggest": "", @@ -255,9 +225,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 35, "column": 22, - "endLine": 36, + "endLine": 35, "endColumn": 23, "problem": "NumericSemantics", "suggest": "", @@ -265,9 +235,9 @@ "severity": "ERROR" }, { - "line": 38, + "line": 37, "column": 5, - "endLine": 38, + "endLine": 37, "endColumn": 15, "problem": "NumericSemantics", "suggest": "", @@ -275,9 +245,9 @@ "severity": "ERROR" }, { - "line": 38, + "line": 37, "column": 17, - "endLine": 38, + "endLine": 37, "endColumn": 27, "problem": "NumericSemantics", "suggest": "", @@ -285,9 +255,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 43, "column": 1, - "endLine": 44, + "endLine": 43, "endColumn": 6, "problem": "InterOpImportJsDataCompare", "suggest": "", @@ -295,9 +265,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 43, "column": 9, - "endLine": 44, + "endLine": 43, "endColumn": 14, "problem": "InterOpImportJsDataCompare", "suggest": "", @@ -305,9 +275,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 43, "column": 1, - "endLine": 44, + "endLine": 43, "endColumn": 6, "problem": "InteropObjectProperty", "suggest": "", @@ -315,34 +285,14 @@ "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, + "line": 43, "column": 9, - "endLine": 44, + "endLine": 43, "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" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.autofix.json new file mode 100644 index 0000000000..2b90e5d9f0 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.autofix.json @@ -0,0 +1,624 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 57, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 607, + "end": 663, + "replacementText": "", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 57 + }, + { + "start": 663, + "end": 663, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_compare_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet m = GeneratedImportVar_1.getPropertyByName('m');\nlet n = GeneratedImportVar_1.getPropertyByName('n');\n", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 57 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 9, + "endLine": 18, + "endColumn": 14, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 672, + "end": 677, + "replacementText": "foo.getPropertyByName(\"a\")", + "line": 18, + "column": 9, + "endLine": 18, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 9, + "endLine": 19, + "endColumn": 14, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 686, + "end": 691, + "replacementText": "foo.getPropertyByName(\"b\")", + "line": 19, + "column": 9, + "endLine": 19, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 672, + "end": 677, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 686, + "end": 691, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 672, + "end": 677, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 686, + "end": 691, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 672, + "end": 677, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 6, + "endLine": 22, + "endColumn": 7, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 686, + "end": 691, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 22, + "column": 6, + "endLine": 22, + "endColumn": 7 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 672, + "end": 677, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 6, + "endLine": 23, + "endColumn": 7, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 686, + "end": 691, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 23, + "column": 6, + "endLine": 23, + "endColumn": 7 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 6, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 722, + "end": 723, + "replacementText": "1.0", + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 2, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 725, + "end": 726, + "replacementText": "m.toNumber()", + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 729, + "end": 730, + "replacementText": "n.toNumber()", + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 6, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 735, + "end": 736, + "replacementText": "1.0", + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 742, + "end": 747, + "replacementText": "x: number = 1", + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 9, + "endLine": 29, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 746, + "end": 747, + "replacementText": "1.0", + "line": 29, + "column": 9, + "endLine": 29, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 12, + "endLine": 29, + "endColumn": 17, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 749, + "end": 754, + "replacementText": "y: number = 2", + "line": 29, + "column": 12, + "endLine": 29, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 17, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 753, + "end": 754, + "replacementText": "2.0", + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 12, + "problem": "ObjectLiteralNoContextType", + "autofix": [ + { + "start": 787, + "end": 787, + "replacementText": "interface GeneratedObjectLiteralInterface_1 {\n a: number;\n b: number;\n}\n", + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 12 + }, + { + "start": 794, + "end": 794, + "replacementText": ": GeneratedObjectLiteralInterface_1", + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 16, + "endLine": 35, + "endColumn": 17, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 802, + "end": 803, + "replacementText": "1.0", + "line": 35, + "column": 16, + "endLine": 35, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 22, + "endLine": 35, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 808, + "end": 809, + "replacementText": "2.0", + "line": 35, + "column": 22, + "endLine": 35, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 818, + "end": 828, + "replacementText": "x2: number = bar.a", + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 17, + "endLine": 37, + "endColumn": 27, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 830, + "end": 840, + "replacementText": "y2: number = bar.b", + "line": 37, + "column": 17, + "endLine": 37, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 881, + "end": 886, + "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 889, + "end": 894, + "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 881, + "end": 886, + "replacementText": "foo.getPropertyByName(\"a\")", + "line": 43, + "column": 1, + "endLine": 43, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 889, + "end": 894, + "replacementText": "foo.getPropertyByName(\"b\")", + "line": 43, + "column": 9, + "endLine": 43, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "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 index 25d2c46ecd..e28baca176 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets.json +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.json @@ -15,19 +15,9 @@ ], "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, + "line": 35, "column": 11, - "endLine": 36, + "endLine": 35, "endColumn": 12, "problem": "ObjectLiteralNoContextType", "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.ets b/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.ets new file mode 100644 index 0000000000..76633c942c --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.ets @@ -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. + */ + + +let GeneratedImportVar_1 = ESValue.load('./interop_import_js_compare_js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let m = GeneratedImportVar_1.getPropertyByName('m'); +let n = GeneratedImportVar_1.getPropertyByName('n'); + +let a = foo.getPropertyByName("a") +let b = foo.getPropertyByName("b") +a > b +a < b +a >= b +a <= b +a = 1.0 + +m.toNumber() > n.toNumber() +m = 1.0 + +let x: number = 1.0, y: number = 2.0; +x > y; +x < y; +x >= y; +x <= y; + +interface GeneratedObjectLiteralInterface_1 { + a: number; + b: number; +} +let bar: GeneratedObjectLiteralInterface_1 = { a: 1.0, b: 2.0 }; + +let x2: number = bar.a, y2: number = bar.b; +x2 > y2; +x2 < y2; +x2 >= y2; +x2 <= y2; + +foo.getPropertyByName("a").toNumber() > foo.getPropertyByName("b").toNumber(); \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.json new file mode 100644 index 0000000000..0ccdec1005 --- /dev/null +++ b/ets2panda/linter/test/interop/interop_import_js_compare.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": 17, + "column": 5, + "endLine": 17, + "endColumn": 74, + "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": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "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": 22, + "column": 5, + "endLine": 22, + "endColumn": 35, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "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/interop/interop_import_js_index.ets b/ets2panda/linter/test/interop/interop_import_js_index.ets index daf1403ab2..a4ffabe660 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets @@ -12,9 +12,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -'use static' +import { ff3 } from "./interop_import_js_rules_js" import {foo} from "./interop_import_js_index_js" let arr = foo.arr arr[1] -arr[3] = 4 \ No newline at end of file +arr[3] = 4 + +let arr1 = ff3.arr +let len = arr1.length as number +for (let i = 0; i < arr1.length; ++i) { + console.log(arr1[i]+''); //error + let x = arr1[i] //error + arr1[i] = 0 //error + console.log(arr1[i]+''); //error +} + +for (let element of arr1) { //error + if (element == 8) { + console.log("hi"); + } +} \ 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 01e50a4c69..aa54c2f0ca 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 @@ -1,19 +1,33 @@ { + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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, + "line": 15, "column": 1, - "endLine": 17, - "endColumn": 49, - "problem": "ImportAfterStatement", + "endLine": 15, + "endColumn": 51, + "problem": "InterOpImportJs", "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { - "line": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 49, "problem": "InterOpImportJs", "suggest": "", @@ -21,9 +35,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 11, - "endLine": 18, + "endLine": 17, "endColumn": 18, "problem": "InteropObjectProperty", "suggest": "", @@ -32,12 +46,22 @@ }, { "line": 18, - "column": 11, + "column": 1, "endLine": 18, - "endColumn": 18, - "problem": "InteropJsObjectUsage", + "endColumn": 7, + "problem": "RuntimeArrayCheck", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 7, + "problem": "InterOpImportJsIndex", + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" }, { @@ -54,61 +78,181 @@ "line": 19, "column": 1, "endLine": 19, - "endColumn": 7, - "problem": "InteropJsObjectTraverseJsInstance", + "endColumn": 11, + "problem": "InterOpImportJsIndex", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" }, { "line": 19, - "column": 1, + "column": 10, "endLine": 19, - "endColumn": 7, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 12, + "endLine": 21, + "endColumn": 19, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 22, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "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": 23, + "column": 14, + "endLine": 23, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 21, + "endLine": 23, + "endColumn": 32, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 17, + "endLine": 24, + "endColumn": 24, + "problem": "InteropJsObjectTraverseJsInstance", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 17, + "endLine": 24, + "endColumn": 24, "problem": "InterOpImportJsIndex", "suggest": "", "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" }, { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 7, - "problem": "RuntimeArrayCheck", + "line": 25, + "column": 13, + "endLine": 25, + "endColumn": 20, + "problem": "InteropJsObjectTraverseJsInstance", "suggest": "", - "rule": "Array bound not checked. (arkts-runtime-array-check)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", "severity": "ERROR" }, { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 7, + "line": 25, + "column": 13, + "endLine": 25, + "endColumn": 20, + "problem": "InterOpImportJsIndex", + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 12, "problem": "InteropJsObjectTraverseJsInstance", "suggest": "", "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", "severity": "ERROR" }, { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 11, + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 16, "problem": "InterOpImportJsIndex", "suggest": "", "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" }, { - "line": 20, - "column": 10, - "endLine": 20, - "endColumn": 11, + "line": 26, + "column": 15, + "endLine": 26, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 17, + "endLine": 27, + "endColumn": 24, + "problem": "InteropJsObjectTraverseJsInstance", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 17, + "endLine": 27, + "endColumn": 24, + "problem": "InterOpImportJsIndex", + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 1, + "endLine": 34, + "endColumn": 2, + "problem": "InteropJsObjectTraverseJsInstance", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 18, + "endLine": 31, + "endColumn": 19, "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_index.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.autofix.json index f5e605ca86..c9d2b8aee7 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 @@ -15,35 +15,59 @@ ], "result": [ { - "line": 17, + "line": 15, "column": 1, - "endLine": 17, - "endColumn": 49, - "problem": "ImportAfterStatement", + "endLine": 15, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 604, + "end": 654, + "replacementText": "", + "line": 15, + "column": 1, + "endLine": 15, + "endColumn": 51 + }, + { + "start": 703, + "end": 703, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_rules_js');\nlet ff3 = GeneratedImportVar_1.getPropertyByName('ff3');\n", + "line": 15, + "column": 1, + "endLine": 15, + "endColumn": 51 + } + ], "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", "severity": "ERROR" }, { - "line": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 49, "problem": "InterOpImportJs", "autofix": [ { - "start": 619, - "end": 667, + "start": 655, + "end": 703, "replacementText": "", - "line": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 49 }, { - "start": 667, - "end": 667, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_index_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n" + "start": 703, + "end": 703, + "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_index_js');\nlet foo = GeneratedImportVar_2.getPropertyByName('foo');\n", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 49 } ], "suggest": "", @@ -51,19 +75,19 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 11, - "endLine": 18, + "endLine": 17, "endColumn": 18, "problem": "InteropObjectProperty", "autofix": [ { - "start": 678, - "end": 685, + "start": 714, + "end": 721, "replacementText": "foo.getPropertyByName(\"arr\")", - "line": 18, + "line": 17, "column": 11, - "endLine": 18, + "endLine": 17, "endColumn": 18 } ], @@ -73,23 +97,33 @@ }, { "line": 18, - "column": 11, + "column": 1, "endLine": 18, - "endColumn": 18, - "problem": "InteropJsObjectUsage", + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 7, + "problem": "InterOpImportJsIndex", "autofix": [ { - "replacementText": "foo.getPropertyByName('arr')", - "start": 678, - "end": 685, + "start": 722, + "end": 728, + "replacementText": "arr.getPropertyByIndex(1)", "line": 18, - "column": 11, + "column": 1, "endLine": 18, - "endColumn": 18 + "endColumn": 7 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" }, { @@ -106,38 +140,185 @@ "line": 19, "column": 1, "endLine": 19, - "endColumn": 7, - "problem": "InteropJsObjectTraverseJsInstance", + "endColumn": 11, + "problem": "InterOpImportJsIndex", "autofix": [ { - "replacementText": "arr.getPropertyByIndex(1).toNumber()", - "start": 686, - "end": 692, + "start": 729, + "end": 739, + "replacementText": "arr.setPropertyByIndex(3, ESValue.wrap(4))", "line": 19, "column": 1, "endLine": 19, - "endColumn": 7 + "endColumn": 11 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", "severity": "ERROR" }, { "line": 19, - "column": 1, + "column": 10, "endLine": 19, - "endColumn": 7, - "problem": "InterOpImportJsIndex", + "endColumn": 11, + "problem": "NumericSemantics", "autofix": [ { - "start": 686, - "end": 692, - "replacementText": "arr.getPropertyByIndex(1)", + "start": 738, + "end": 739, + "replacementText": "4.0", "line": 19, - "column": 1, + "column": 10, "endLine": 19, - "endColumn": 7 + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 12, + "endLine": 21, + "endColumn": 19, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 752, + "end": 759, + "replacementText": "ff3.getPropertyByName(\"arr\")", + "line": 21, + "column": 12, + "endLine": 21, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 22, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 770, + "end": 781, + "replacementText": "arr1.getPropertyByName(\"length\")", + "line": 22, + "column": 11, + "endLine": 22, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 10, + "endLine": 23, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 801, + "end": 806, + "replacementText": "i: number = 0", + "line": 23, + "column": 10, + "endLine": 23, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 14, + "endLine": 23, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 805, + "end": 806, + "replacementText": "0.0", + "line": 23, + "column": 14, + "endLine": 23, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 21, + "endLine": 23, + "endColumn": 32, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 812, + "end": 823, + "replacementText": "arr1.getPropertyByName(\"length\")", + "line": 23, + "column": 21, + "endLine": 23, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 17, + "endLine": 24, + "endColumn": 24, + "problem": "InteropJsObjectTraverseJsInstance", + "autofix": [ + { + "replacementText": "arr1.getPropertyByIndex(i).toNumber()", + "start": 848, + "end": 855, + "line": 24, + "column": 17, + "endLine": 24, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 17, + "endLine": 24, + "endColumn": 24, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 848, + "end": 855, + "replacementText": "arr1.getPropertyByIndex(i)", + "line": 24, + "column": 17, + "endLine": 24, + "endColumn": 24 } ], "suggest": "", @@ -145,30 +326,62 @@ "severity": "ERROR" }, { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 7, - "problem": "RuntimeArrayCheck", + "line": 25, + "column": 13, + "endLine": 25, + "endColumn": 20, + "problem": "InteropJsObjectTraverseJsInstance", + "autofix": [ + { + "replacementText": "arr1.getPropertyByIndex(i).toNumber()", + "start": 882, + "end": 889, + "line": 25, + "column": 13, + "endLine": 25, + "endColumn": 20 + } + ], "suggest": "", - "rule": "Array bound not checked. (arkts-runtime-array-check)", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", "severity": "ERROR" }, { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 7, + "line": 25, + "column": 13, + "endLine": 25, + "endColumn": 20, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 882, + "end": 889, + "replacementText": "arr1.getPropertyByIndex(i)", + "line": 25, + "column": 13, + "endLine": 25, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 12, "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { - "replacementText": "arr.setPropertyByIndex(3, ESValue.wrap(4))", - "start": 693, - "end": 703, - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 7 + "replacementText": "arr1.setPropertyByIndex(i, ESValue.wrap(0 //error\n))", + "start": 903, + "end": 914, + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 12 } ], "suggest": "", @@ -176,16 +389,20 @@ "severity": "ERROR" }, { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 11, + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 16, "problem": "InterOpImportJsIndex", "autofix": [ { - "start": 693, - "end": 703, - "replacementText": "arr.setPropertyByIndex(3, ESValue.wrap(4))" + "start": 903, + "end": 914, + "replacementText": "arr1.setPropertyByIndex(i, ESValue.wrap(0))", + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 16 } ], "suggest": "", @@ -193,20 +410,93 @@ "severity": "ERROR" }, { - "line": 20, - "column": 10, - "endLine": 20, - "endColumn": 11, + "line": 26, + "column": 15, + "endLine": 26, + "endColumn": 16, "problem": "NumericSemantics", "autofix": [ { - "start": 702, - "end": 703, - "replacementText": "4.0", - "line": 20, - "column": 10, - "endLine": 20, - "endColumn": 11 + "start": 913, + "end": 914, + "replacementText": "0.0", + "line": 26, + "column": 15, + "endLine": 26, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 17, + "endLine": 27, + "endColumn": 24, + "problem": "InteropJsObjectTraverseJsInstance", + "autofix": [ + { + "replacementText": "arr1.getPropertyByIndex(i).toNumber()", + "start": 940, + "end": 947, + "line": 27, + "column": 17, + "endLine": 27, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 17, + "endLine": 27, + "endColumn": 24, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 940, + "end": 947, + "replacementText": "arr1.getPropertyByIndex(i)", + "line": 27, + "column": 17, + "endLine": 27, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 1, + "endLine": 34, + "endColumn": 2, + "problem": "InteropJsObjectTraverseJsInstance", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 18, + "endLine": 31, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1019, + "end": 1020, + "replacementText": "8.0", + "line": 31, + "column": 18, + "endLine": 31, + "endColumn": 19 } ], "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_import_js_index.ets.json b/ets2panda/linter/test/interop/interop_import_js_index.ets.json index 5619e69d78..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.json +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.json @@ -13,16 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file 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 index 65d9325e8b..8e707c2f67 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.ets @@ -12,11 +12,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -'use static' -let GeneratedImportVar_1 = ESValue.load('./interop_import_js_index_js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); + +let GeneratedImportVar_2 = ESValue.load('./interop_import_js_index_js'); +let foo = GeneratedImportVar_2.getPropertyByName('foo'); +let GeneratedImportVar_1 = ESValue.load('./interop_import_js_rules_js'); +let ff3 = GeneratedImportVar_1.getPropertyByName('ff3'); let arr = foo.getPropertyByName("arr") -arr.getPropertyByIndex(1.0).toNumber() -arr.setPropertyByIndex(3.0, ESValue.wrap(4.0)) \ No newline at end of file +arr.getPropertyByIndex(1.0) +arr.setPropertyByIndex(3.0, ESValue.wrap(4.0)) + +let arr1 = ff3.getPropertyByName("arr") +let len: number = arr1.getPropertyByName("length") as number +for (let i: number = 0.0; i < arr1.getPropertyByName("length"); ++i) { + console.log(arr1.getPropertyByIndex(i).toNumber()+''); //error + let x = arr1.getPropertyByIndex(i).toNumber() //error + arr1.setPropertyByIndex(i, ESValue.wrap(0.0 //error +)) //error + console.log(arr1.getPropertyByIndex(i).toNumber()+''); //error +} + +for (let element of arr1) { //error + if (element == 8.0) { + console.log("hi"); + } +} \ 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 index 957ef0239d..526bcedf9d 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.json @@ -14,11 +14,21 @@ "limitations under the License." ], "result": [ + { + "line": 16, + "column": 5, + "endLine": 16, + "endColumn": 72, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, { "line": 17, "column": 5, "endLine": 17, - "endColumn": 72, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -28,6 +38,16 @@ "line": 18, "column": 5, "endLine": 18, + "endColumn": 72, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 5, + "endLine": 19, "endColumn": 56, "problem": "AnyType", "suggest": "", @@ -35,14 +55,44 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 5, - "endLine": 20, + "endLine": 21, "endColumn": 39, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 40, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 9, + "endLine": 29, + "endColumn": 50, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 10, + "endLine": 35, + "endColumn": 17, + "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 d7e3b52fca..d4c110abcf 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets @@ -28,6 +28,7 @@ import { handle } from "./interop_import_js_rules_js" import { expand } from "./interop_import_js_rules_js" import { orange } from "./interop_import_js_rules_js" + if (foo.isGood) {} if (ff1.f1 > 18) { @@ -65,17 +66,27 @@ handle(lambda) class X{a = 1; b= 2; c= 3} expand(new X()) // ERROR expand-static + class Y { str: string = 'str'; bool: boolean = false; } + let testY: Y = { str: "hello", bool: false, } + expand(testY); expand({x: '1', y: "hello", z: false}); + let flag = false; if (orange.isVegetable1 === 123) { flag = true } + +for (let element of arr) { + if (element == 8) { + console.log("hi"); + } +} 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 299b2732c8..abe1b7d5c8 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 @@ -195,9 +195,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 32, "column": 5, - "endLine": 31, + "endLine": 32, "endColumn": 15, "problem": "InteropObjectProperty", "suggest": "", @@ -205,9 +205,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 32, "column": 5, - "endLine": 31, + "endLine": 32, "endColumn": 15, "problem": "InteropJsObjectConditionJudgment", "suggest": "", @@ -215,9 +215,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 34, "column": 5, - "endLine": 33, + "endLine": 34, "endColumn": 11, "problem": "InterOpImportJsDataCompare", "suggest": "", @@ -225,9 +225,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 34, "column": 5, - "endLine": 33, + "endLine": 34, "endColumn": 11, "problem": "InteropObjectProperty", "suggest": "", @@ -235,9 +235,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 34, "column": 5, - "endLine": 33, + "endLine": 34, "endColumn": 11, "problem": "InteropJsObjectConditionJudgment", "suggest": "", @@ -245,9 +245,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 34, "column": 14, - "endLine": 33, + "endLine": 34, "endColumn": 16, "problem": "NumericSemantics", "suggest": "", @@ -255,9 +255,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 38, "column": 1, - "endLine": 37, + "endLine": 38, "endColumn": 21, "problem": "InteropJsObjectInheritance", "suggest": "", @@ -265,9 +265,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 42, "column": 1, - "endLine": 41, + "endLine": 42, "endColumn": 21, "problem": "InteropJsObjectInheritance", "suggest": "", @@ -275,19 +275,19 @@ "severity": "ERROR" }, { - "line": 44, + "line": 45, "column": 3, - "endLine": 44, + "endLine": 45, "endColumn": 8, "problem": "InteropJSFunctionInvoke", "suggest": "", - "rule": "Trying to catch JS errors is not permitted (arkts-interop-js2s-js-exception)", + "rule": "ArkTS1.2 cannot catch a non Error instance thrown from JS code (arkts-interop-js2s-js-exception)", "severity": "ERROR" }, { - "line": 44, + "line": 45, "column": 3, - "endLine": 44, + "endLine": 45, "endColumn": 8, "problem": "CallJSFunction", "suggest": "", @@ -295,19 +295,9 @@ "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, + "line": 50, "column": 11, - "endLine": 49, + "endLine": 50, "endColumn": 18, "problem": "InteropObjectProperty", "suggest": "", @@ -315,39 +305,19 @@ "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": 50, + "line": 51, "column": 11, - "endLine": 50, + "endLine": 51, "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", + "problem": "InteropObjectProperty", "suggest": "", - "rule": "Array bound not checked. (arkts-runtime-array-check)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { - "line": 51, + "line": 52, "column": 10, - "endLine": 51, + "endLine": 52, "endColumn": 15, "problem": "NumericSemantics", "suggest": "", @@ -355,9 +325,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 52, "column": 14, - "endLine": 51, + "endLine": 52, "endColumn": 15, "problem": "NumericSemantics", "suggest": "", @@ -365,9 +335,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 11, - "endLine": 52, + "endLine": 53, "endColumn": 17, "problem": "RuntimeArrayCheck", "suggest": "", @@ -375,9 +345,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 11, - "endLine": 52, + "endLine": 53, "endColumn": 17, "problem": "InteropJsObjectTraverseJsInstance", "suggest": "", @@ -385,9 +355,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 11, - "endLine": 52, + "endLine": 53, "endColumn": 17, "problem": "InterOpImportJsIndex", "suggest": "", @@ -395,9 +365,19 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 3, - "endLine": 53, + "endLine": 54, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 3, + "endLine": 54, "endColumn": 9, "problem": "InteropJsObjectTraverseJsInstance", "suggest": "", @@ -405,9 +385,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 3, - "endLine": 53, + "endLine": 54, "endColumn": 13, "problem": "InterOpImportJsIndex", "suggest": "", @@ -415,9 +395,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 12, - "endLine": 53, + "endLine": 54, "endColumn": 13, "problem": "NumericSemantics", "suggest": "", @@ -425,19 +405,19 @@ "severity": "ERROR" }, { - "line": 63, + "line": 64, "column": 8, - "endLine": 63, + "endLine": 64, "endColumn": 12, "problem": "InteropJsObjectCallStaticFunc", "suggest": "", "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", - "severity": "ERROR" + "severity": "WARNING" }, { - "line": 63, + "line": 64, "column": 1, - "endLine": 63, + "endLine": 64, "endColumn": 13, "problem": "CallJSFunction", "suggest": "", @@ -445,19 +425,19 @@ "severity": "ERROR" }, { - "line": 64, + "line": 65, "column": 8, - "endLine": 64, + "endLine": 65, "endColumn": 14, "problem": "InteropJsObjectCallStaticFunc", "suggest": "", "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", - "severity": "ERROR" + "severity": "WARNING" }, { - "line": 64, + "line": 65, "column": 1, - "endLine": 64, + "endLine": 65, "endColumn": 15, "problem": "CallJSFunction", "suggest": "", @@ -465,9 +445,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 67, "column": 9, - "endLine": 66, + "endLine": 67, "endColumn": 15, "problem": "NumericSemantics", "suggest": "", @@ -475,9 +455,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 67, "column": 13, - "endLine": 66, + "endLine": 67, "endColumn": 14, "problem": "NumericSemantics", "suggest": "", @@ -485,9 +465,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 67, "column": 16, - "endLine": 66, + "endLine": 67, "endColumn": 21, "problem": "NumericSemantics", "suggest": "", @@ -495,9 +475,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 67, "column": 19, - "endLine": 66, + "endLine": 67, "endColumn": 20, "problem": "NumericSemantics", "suggest": "", @@ -505,9 +485,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 67, "column": 22, - "endLine": 66, + "endLine": 67, "endColumn": 26, "problem": "NumericSemantics", "suggest": "", @@ -515,9 +495,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 67, "column": 25, - "endLine": 66, + "endLine": 67, "endColumn": 26, "problem": "NumericSemantics", "suggest": "", @@ -525,9 +505,9 @@ "severity": "ERROR" }, { - "line": 67, + "line": 68, "column": 8, - "endLine": 67, + "endLine": 68, "endColumn": 15, "problem": "InteropJsObjectExpandStaticInstance", "suggest": "", @@ -535,9 +515,9 @@ "severity": "ERROR" }, { - "line": 67, + "line": 68, "column": 1, - "endLine": 67, + "endLine": 68, "endColumn": 16, "problem": "CallJSFunction", "suggest": "", @@ -545,9 +525,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 80, "column": 8, - "endLine": 76, + "endLine": 80, "endColumn": 13, "problem": "InteropJsObjectExpandStaticInstance", "suggest": "", @@ -555,9 +535,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 80, "column": 1, - "endLine": 76, + "endLine": 80, "endColumn": 14, "problem": "CallJSFunction", "suggest": "", @@ -565,9 +545,9 @@ "severity": "ERROR" }, { - "line": 77, + "line": 81, "column": 8, - "endLine": 77, + "endLine": 81, "endColumn": 38, "problem": "InteropJsObjectExpandStaticInstance", "suggest": "", @@ -575,9 +555,9 @@ "severity": "ERROR" }, { - "line": 77, + "line": 81, "column": 1, - "endLine": 77, + "endLine": 81, "endColumn": 39, "problem": "CallJSFunction", "suggest": "", @@ -585,9 +565,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 84, "column": 5, - "endLine": 79, + "endLine": 84, "endColumn": 32, "problem": "InteropEqualityJudgment", "suggest": "", @@ -595,9 +575,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 84, "column": 5, - "endLine": 79, + "endLine": 84, "endColumn": 24, "problem": "InteropObjectProperty", "suggest": "", @@ -605,24 +585,34 @@ "severity": "ERROR" }, { - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 24, - "problem": "InteropJsObjectUsage", + "line": 84, + "column": 29, + "endLine": 84, + "endColumn": 32, + "problem": "NumericSemantics", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 79, - "column": 29, - "endLine": 79, - "endColumn": 32, + "line": 88, + "column": 1, + "endLine": 92, + "endColumn": 2, + "problem": "InteropJsObjectTraverseJsInstance", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 18, + "endLine": 89, + "endColumn": 19, "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_rules.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.autofix.json index 4e7f1b6c7a..b44bc6c370 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 @@ -1,1149 +1,1139 @@ { - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR 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": [ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ { - "start": 619, - "end": 669, - "replacementText": "", - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 51 + "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" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_1 = ESValue.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": 17, + "column": 1, + "endLine": 17, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 619, + "end": 669, + "replacementText": "", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 51 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_1 = ESValue.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" + }, { - "start": 670, - "end": 725, - "replacementText": "", - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 56 + "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" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_2 = ESValue.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": 18, + "column": 1, + "endLine": 18, + "endColumn": 56, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 670, + "end": 725, + "replacementText": "", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 56 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_2 = ESValue.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" + }, { - "start": 727, - "end": 775, - "replacementText": "", - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 49 + "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" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_3 = ESValue.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": 20, + "column": 1, + "endLine": 20, + "endColumn": 49, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 727, + "end": 775, + "replacementText": "", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 49 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_3 = ESValue.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" + }, { - "start": 776, - "end": 824, - "replacementText": "", - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 49 + "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" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_4 = ESValue.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": 21, + "column": 1, + "endLine": 21, + "endColumn": 49, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 776, + "end": 824, + "replacementText": "", + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 49 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_4 = ESValue.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" + }, { - "start": 826, - "end": 876, - "replacementText": "", - "line": 23, - "column": 1, - "endLine": 23, - "endColumn": 51 + "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" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_5 = ESValue.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": 23, + "column": 1, + "endLine": 23, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 826, + "end": 876, + "replacementText": "", + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 51 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_5 = ESValue.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" + }, { - "start": 878, - "end": 928, - "replacementText": "", - "line": 25, - "column": 1, - "endLine": 25, - "endColumn": 51 + "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" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_6 = ESValue.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": 25, + "column": 1, + "endLine": 25, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 878, + "end": 928, + "replacementText": "", + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 51 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_6 = ESValue.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" + }, { - "start": 930, - "end": 983, - "replacementText": "", - "line": 27, - "column": 1, - "endLine": 27, - "endColumn": 54 + "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" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_7 = ESValue.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": 27, + "column": 1, + "endLine": 27, + "endColumn": 54, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 930, + "end": 983, + "replacementText": "", + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 54 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_7 = ESValue.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" + }, { - "start": 985, - "end": 1038, - "replacementText": "", - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 54 + "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" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_8 = ESValue.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": 30, - "column": 1, - "endLine": 30, - "endColumn": 54, - "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": 54, - "problem": "InterOpImportJs", - "autofix": [ + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 985, + "end": 1038, + "replacementText": "", + "line": 29, + "column": 1, + "endLine": 29, + "endColumn": 54 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_8 = ESValue.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" + }, { - "start": 1039, - "end": 1092, - "replacementText": "", - "line": 30, - "column": 1, - "endLine": 30, - "endColumn": 54 + "line": 30, + "column": 1, + "endLine": 30, + "endColumn": 54, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" }, { - "start": 1092, - "end": 1092, - "replacementText": "let GeneratedImportVar_9 = ESValue.load('./interop_import_js_rules_js');\nlet orange = GeneratedImportVar_9.getPropertyByName('orange');\n", - "line": 30, - "column": 1, - "endLine": 30, - "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": 30, + "column": 1, + "endLine": 30, + "endColumn": 54, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 1039, + "end": 1092, + "replacementText": "", + "line": 30, + "column": 1, + "endLine": 30, + "endColumn": 54 + }, + { + "start": 1092, + "end": 1092, + "replacementText": "let GeneratedImportVar_9 = ESValue.load('./interop_import_js_rules_js');\nlet orange = GeneratedImportVar_9.getPropertyByName('orange');\n", + "line": 30, + "column": 1, + "endLine": 30, + "endColumn": 54 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, { - "start": 1097, - "end": 1107, - "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": 32, + "column": 5, + "endLine": 32, + "endColumn": 15, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1098, + "end": 1108, + "replacementText": "foo.getPropertyByName(\"isGood\")", + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, { - "replacementText": "foo.getPropertyByName('isGood').toBoolean()", - "start": 1097, - "end": 1107, - "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": 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": [ + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 15, + "problem": "InteropJsObjectConditionJudgment", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('isGood').toBoolean()", + "start": 1098, + "end": 1108, + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + }, { - "start": 1117, - "end": 1123, - "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": [ + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 11, + "problem": "InterOpImportJsDataCompare", + "autofix": [ + { + "start": 1118, + "end": 1124, + "replacementText": "ff1.getPropertyByName(\"f1\").toNumber()", + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Importing data directly from the \"JS\" module for comparison is not supported (arkts-interop-js2s-compare-js-data)", + "severity": "ERROR" + }, { - "replacementText": "ff1.getPropertyByName('f1').toNumber()", - "start": 1117, - "end": 1123, - "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": 14, - "endLine": 33, - "endColumn": 16, - "problem": "NumericSemantics", - "autofix": [ + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 11, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1118, + "end": 1124, + "replacementText": "ff1.getPropertyByName(\"f1\")", + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, { - "start": 1126, - "end": 1128, - "replacementText": "18.0", - "line": 33, - "column": 14, - "endLine": 33, - "endColumn": 16 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "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": "CallJSFunction", - "autofix": [ + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 11, + "problem": "InteropJsObjectConditionJudgment", + "autofix": [ + { + "replacementText": "ff1.getPropertyByName('f1').toNumber()", + "start": 1118, + "end": 1124, + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + }, { - "start": 1288, - "end": 1293, - "replacementText": "ff4.invoke()", - "line": 44, - "column": 3, - "endLine": 44, - "endColumn": 8 - } - ], - "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": [ + "line": 34, + "column": 14, + "endLine": 34, + "endColumn": 16, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1127, + "end": 1129, + "replacementText": "18.0", + "line": 34, + "column": 14, + "endLine": 34, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { - "start": 1343, - "end": 1350, - "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": [ + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 21, + "problem": "InteropJsObjectInheritance", + "suggest": "", + "rule": "Direct inheritance of interop JS classes is not supported (arkts-interop-js2s-inherit-js-class)", + "severity": "ERROR" + }, { - "replacementText": "ff3.getPropertyByName('arr')", - "start": 1343, - "end": 1350, - "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": 50, - "column": 11, - "endLine": 50, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "autofix": [ + "line": 42, + "column": 1, + "endLine": 42, + "endColumn": 21, + "problem": "InteropJsObjectInheritance", + "suggest": "", + "rule": "Direct inheritance of interop JS classes is not supported (arkts-interop-js2s-inherit-js-class)", + "severity": "ERROR" + }, { - "replacementText": "arr.getPropertyByName('length').toNumber()", - "start": 1361, - "end": 1381, - "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": [ + "line": 45, + "column": 3, + "endLine": 45, + "endColumn": 8, + "problem": "InteropJSFunctionInvoke", + "suggest": "", + "rule": "ArkTS1.2 cannot catch a non Error instance thrown from JS code (arkts-interop-js2s-js-exception)", + "severity": "ERROR" + }, { - "start": 1391, - "end": 1396, - "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": 51, - "column": 14, - "endLine": 51, - "endColumn": 15, - "problem": "NumericSemantics", - "autofix": [ + "line": 45, + "column": 3, + "endLine": 45, + "endColumn": 8, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 1289, + "end": 1294, + "replacementText": "ff4.invoke()", + "line": 45, + "column": 3, + "endLine": 45, + "endColumn": 8 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, { - "start": 1395, - "end": 1396, - "replacementText": "0.0", - "line": 51, - "column": 14, - "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": "RuntimeArrayCheck", - "suggest": "", - "rule": "Array bound not checked. (arkts-runtime-array-check)", - "severity": "ERROR" - }, - { - "line": 52, - "column": 11, - "endLine": 52, - "endColumn": 17, - "problem": "InteropJsObjectTraverseJsInstance", - "autofix": [ + "line": 50, + "column": 11, + "endLine": 50, + "endColumn": 18, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1344, + "end": 1351, + "replacementText": "ff3.getPropertyByName(\"arr\")", + "line": 50, + "column": 11, + "endLine": 50, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, { - "replacementText": "arr.getPropertyByIndex(i).toNumber()", - "start": 1424, - "end": 1430, - "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": [ + "line": 51, + "column": 11, + "endLine": 51, + "endColumn": 21, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1362, + "end": 1372, + "replacementText": "arr.getPropertyByName(\"length\")", + "line": 51, + "column": 11, + "endLine": 51, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, { - "start": 1424, - "end": 1430, - "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": [ + "line": 52, + "column": 10, + "endLine": 52, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1392, + "end": 1397, + "replacementText": "i: number = 0", + "line": 52, + "column": 10, + "endLine": 52, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { - "replacementText": "arr.setPropertyByIndex(i, ESValue.wrap(0))", - "start": 1433, - "end": 1443, - "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": [ + "line": 52, + "column": 14, + "endLine": 52, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1396, + "end": 1397, + "replacementText": "0.0", + "line": 52, + "column": 14, + "endLine": 52, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { - "start": 1433, - "end": 1443, - "replacementText": "arr.setPropertyByIndex(i, ESValue.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": 53, - "column": 12, - "endLine": 53, - "endColumn": 13, - "problem": "NumericSemantics", - "autofix": [ + "line": 53, + "column": 11, + "endLine": 53, + "endColumn": 17, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { - "start": 1442, - "end": 1443, - "replacementText": "0.0", - "line": 53, - "column": 12, - "endLine": 53, - "endColumn": 13 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 63, - "column": 8, - "endLine": 63, - "endColumn": 12, - "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", - "autofix": [ + "line": 53, + "column": 11, + "endLine": 53, + "endColumn": 17, + "problem": "InteropJsObjectTraverseJsInstance", + "autofix": [ + { + "replacementText": "arr.getPropertyByIndex(i).toNumber()", + "start": 1425, + "end": 1431, + "line": 53, + "column": 11, + "endLine": 53, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, { - "start": 1544, - "end": 1556, - "replacementText": "handle.invoke(ESValue.wrap(foo2))", - "line": 63, - "column": 1, - "endLine": 63, - "endColumn": 13 - } - ], - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", - "severity": "ERROR" - }, - { - "line": 64, - "column": 8, - "endLine": 64, - "endColumn": 14, - "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", - "autofix": [ + "line": 53, + "column": 11, + "endLine": 53, + "endColumn": 17, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 1425, + "end": 1431, + "replacementText": "arr.getPropertyByIndex(i)", + "line": 53, + "column": 11, + "endLine": 53, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, { - "start": 1557, - "end": 1571, - "replacementText": "handle.invoke(ESValue.wrap(lambda))", - "line": 64, - "column": 1, - "endLine": 64, - "endColumn": 15 - } - ], - "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": [ + "line": 54, + "column": 3, + "endLine": 54, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { - "start": 1581, - "end": 1587, - "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": 13, - "endLine": 66, - "endColumn": 14, - "problem": "NumericSemantics", - "autofix": [ + "line": 54, + "column": 3, + "endLine": 54, + "endColumn": 9, + "problem": "InteropJsObjectTraverseJsInstance", + "autofix": [ + { + "replacementText": "arr.setPropertyByIndex(i, ESValue.wrap(0))", + "start": 1434, + "end": 1444, + "line": 54, + "column": 3, + "endLine": 54, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, { - "start": 1585, - "end": 1586, - "replacementText": "1.0", - "line": 66, - "column": 13, - "endLine": 66, - "endColumn": 14 - } - ], - "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": [ + "line": 54, + "column": 3, + "endLine": 54, + "endColumn": 13, + "problem": "InterOpImportJsIndex", + "autofix": [ + { + "start": 1434, + "end": 1444, + "replacementText": "arr.setPropertyByIndex(i, ESValue.wrap(0))", + "line": 54, + "column": 3, + "endLine": 54, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Interop objects can't be indexed directly (arkts-interop-js2s-access-js-index)", + "severity": "ERROR" + }, { - "start": 1588, - "end": 1593, - "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": 19, - "endLine": 66, - "endColumn": 20, - "problem": "NumericSemantics", - "autofix": [ + "line": 54, + "column": 12, + "endLine": 54, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1443, + "end": 1444, + "replacementText": "0.0", + "line": 54, + "column": 12, + "endLine": 54, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { - "start": 1591, - "end": 1592, - "replacementText": "2.0", - "line": 66, - "column": 19, - "endLine": 66, - "endColumn": 20 - } - ], - "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": [ + "line": 64, + "column": 8, + "endLine": 64, + "endColumn": 12, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "WARNING" + }, { - "start": 1594, - "end": 1598, - "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": 66, - "column": 25, - "endLine": 66, - "endColumn": 26, - "problem": "NumericSemantics", - "autofix": [ + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 13, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 1545, + "end": 1557, + "replacementText": "handle.invoke(ESValue.wrap(foo2))", + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, { - "start": 1597, - "end": 1598, - "replacementText": "3.0", - "line": 66, - "column": 25, - "endLine": 66, - "endColumn": 26 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 67, - "column": 8, - "endLine": 67, - "endColumn": 15, - "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", - "autofix": [ + "line": 65, + "column": 8, + "endLine": 65, + "endColumn": 14, + "problem": "InteropJsObjectCallStaticFunc", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-call-static-function)", + "severity": "WARNING" + }, { - "start": 1600, - "end": 1615, - "replacementText": "expand.invoke(ESValue.wrap(new X()))", - "line": 67, - "column": 1, - "endLine": 67, - "endColumn": 16 - } - ], - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", - "severity": "ERROR" - }, - { - "line": 76, - "column": 8, - "endLine": 76, - "endColumn": 13, - "problem": "InteropJsObjectExpandStaticInstance", - "suggest": "", - "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-expand-static-instance)", - "severity": "ERROR" - }, - { - "line": 76, - "column": 1, - "endLine": 76, - "endColumn": 14, - "problem": "CallJSFunction", - "autofix": [ + "line": 65, + "column": 1, + "endLine": 65, + "endColumn": 15, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 1558, + "end": 1572, + "replacementText": "handle.invoke(ESValue.wrap(lambda))", + "line": 65, + "column": 1, + "endLine": 65, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, { - "start": 1749, - "end": 1762, - "replacementText": "expand.invoke(ESValue.wrap(testY))", - "line": 76, - "column": 1, - "endLine": 76, - "endColumn": 14 - } - ], - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", - "severity": "ERROR" - }, - { - "line": 77, - "column": 8, - "endLine": 77, - "endColumn": 38, - "problem": "InteropJsObjectExpandStaticInstance", - "suggest": "", - "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-expand-static-instance)", - "severity": "ERROR" - }, - { - "line": 77, - "column": 1, - "endLine": 77, - "endColumn": 39, - "problem": "CallJSFunction", - "autofix": [ + "line": 67, + "column": 9, + "endLine": 67, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1582, + "end": 1588, + "replacementText": "a: number = 1;", + "line": 67, + "column": 9, + "endLine": 67, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { - "start": 1764, - "end": 1802, - "replacementText": "expand.invoke(ESValue.wrap({x: '1', y: \"hello\", z: false}))", - "line": 77, - "column": 1, - "endLine": 77, - "endColumn": 39 - } - ], - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", - "severity": "ERROR" - }, - { - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 32, - "problem": "InteropEqualityJudgment", - "autofix": [ + "line": 67, + "column": 13, + "endLine": 67, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1586, + "end": 1587, + "replacementText": "1.0", + "line": 67, + "column": 13, + "endLine": 67, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { - "start": 1826, - "end": 1853, - "replacementText": "orange.isVegetable1.areStrictlyEqual(123)", - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 32 - } - ], - "suggest": "", - "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", - "severity": "ERROR" - }, - { - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 24, - "problem": "InteropObjectProperty", - "autofix": [ + "line": 67, + "column": 16, + "endLine": 67, + "endColumn": 21, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1589, + "end": 1594, + "replacementText": "b: number = 2;", + "line": 67, + "column": 16, + "endLine": 67, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { - "start": 1826, - "end": 1845, - "replacementText": "orange.getPropertyByName(\"isVegetable1\")", - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 24 - } - ], - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "severity": "ERROR" - }, - { - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 24, - "problem": "InteropJsObjectUsage", - "autofix": [ + "line": 67, + "column": 19, + "endLine": 67, + "endColumn": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1592, + "end": 1593, + "replacementText": "2.0", + "line": 67, + "column": 19, + "endLine": 67, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { - "replacementText": "orange.getPropertyByName('isVegetable1').toNumber()", - "start": 1826, - "end": 1845, - "line": 79, - "column": 5, - "endLine": 79, - "endColumn": 24 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 79, - "column": 29, - "endLine": 79, - "endColumn": 32, - "problem": "NumericSemantics", - "autofix": [ + "line": 67, + "column": 22, + "endLine": 67, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1595, + "end": 1599, + "replacementText": "c: number = 3;", + "line": 67, + "column": 22, + "endLine": 67, + "endColumn": 26 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 25, + "endLine": 67, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1598, + "end": 1599, + "replacementText": "3.0", + "line": 67, + "column": 25, + "endLine": 67, + "endColumn": 26 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 8, + "endLine": 68, + "endColumn": 15, + "problem": "InteropJsObjectExpandStaticInstance", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-expand-static-instance)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 1, + "endLine": 68, + "endColumn": 16, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 1601, + "end": 1616, + "replacementText": "expand.invoke(ESValue.wrap(new X()))", + "line": 68, + "column": 1, + "endLine": 68, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 8, + "endLine": 80, + "endColumn": 13, + "problem": "InteropJsObjectExpandStaticInstance", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-expand-static-instance)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 1, + "endLine": 80, + "endColumn": 14, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 1753, + "end": 1766, + "replacementText": "expand.invoke(ESValue.wrap(testY))", + "line": 80, + "column": 1, + "endLine": 80, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 8, + "endLine": 81, + "endColumn": 38, + "problem": "InteropJsObjectExpandStaticInstance", + "suggest": "", + "rule": "Direct usage of interop JS functions is not supported (arkts-interop-js2s-js-expand-static-instance)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 39, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 1768, + "end": 1806, + "replacementText": "expand.invoke(ESValue.wrap({x: '1', y: \"hello\", z: false}))", + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 39 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 5, + "endLine": 84, + "endColumn": 32, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 1831, + "end": 1858, + "replacementText": "orange.isVegetable1.areStrictlyEqual(123)", + "line": 84, + "column": 5, + "endLine": 84, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 5, + "endLine": 84, + "endColumn": 24, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1831, + "end": 1850, + "replacementText": "orange.getPropertyByName(\"isVegetable1\")", + "line": 84, + "column": 5, + "endLine": 84, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 29, + "endLine": 84, + "endColumn": 32, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1855, + "end": 1858, + "replacementText": "123.0", + "line": 84, + "column": 29, + "endLine": 84, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 1, + "endLine": 92, + "endColumn": 2, + "problem": "InteropJsObjectTraverseJsInstance", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-traverse-js-instance)", + "severity": "ERROR" + }, { - "start": 1850, - "end": 1853, - "replacementText": "123.0", - "line": 79, - "column": 29, - "endLine": 79, - "endColumn": 32 + "line": 89, + "column": 18, + "endLine": 89, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1921, + "end": 1922, + "replacementText": "8.0", + "line": 89, + "column": 18, + "endLine": 89, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" } - ], - "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_rules.ets.json b/ets2panda/linter/test/interop/interop_import_js_rules.ets.json index 097539546e..ab212bc3f3 100644 --- a/ets2panda/linter/test/interop/interop_import_js_rules.ets.json +++ b/ets2panda/linter/test/interop/interop_import_js_rules.ets.json @@ -1,18 +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." - ], + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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, diff --git a/ets2panda/linter/test/interop/interop_import_typeof_js.ets b/ets2panda/linter/test/interop/interop_import_typeof_js.ets old mode 100755 new mode 100644 index 3c4c0728f9..b8941c7ac5 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets @@ -12,8 +12,7 @@ * 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'; 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 old mode 100755 new mode 100644 index 07bd210812..e1fc6d18dd --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.arkts2.json @@ -1,488 +1,438 @@ { - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR 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": 17, - "column": 1, - "endLine": 17, - "endColumn": 69, - "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": 54, - "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": "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": 55, - "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": "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": 15, - "problem": "InterOpImportJsForTypeOf", - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "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-interop-js2s-call-js-func)", - "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-js2s-typeof-js-type)", - "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-js2s-typeof-js-type)", - "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-js2s-typeof-js-type)", - "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-js2s-typeof-js-type)", - "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-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 8, - "endLine": 28, - "endColumn": 17, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "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": 29, - "column": 1, - "endLine": 29, - "endColumn": 12, - "problem": "InterOpImportJsForTypeOf", - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 11, - "endLine": 30, - "endColumn": 20, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "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": 32, - "column": 23, - "endLine": 32, - "endColumn": 35, - "problem": "InstantiatedJsOjbect", - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "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-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 8, - "endLine": 33, - "endColumn": 20, - "problem": "InstantiatedJsOjbect", - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 21, - "endLine": 35, - "endColumn": 33, - "problem": "InstantiatedJsOjbect", - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "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-interop-js2s-call-js-method)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 10, - "endLine": 43, - "endColumn": 28, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 24, - "endLine": 43, - "endColumn": 27, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 3, - "endLine": 45, - "endColumn": 22, - "problem": "InterOpImportJsForTypeOf", - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 10, - "endLine": 45, - "endColumn": 22, - "problem": "InstantiatedJsOjbect", - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "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": 48, - "column": 35, - "endLine": 48, - "endColumn": 38, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "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-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 62, - "column": 12, - "endLine": 62, - "endColumn": 21, - "problem": "InteropObjectProperty", - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "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": 66, - "column": 28, - "endLine": 66, - "endColumn": 47, - "problem": "InterOpImportJsForTypeOf", - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 66, - "column": 35, - "endLine": 66, - "endColumn": 47, - "problem": "InstantiatedJsOjbect", - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "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-js2s-typeof-js-type)", - "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-js2s-typeof-js-type)", - "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-interop-js2s-create-js-instance)", - "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-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 8, - "endLine": 72, - "endColumn": 20, - "problem": "InstantiatedJsOjbect", - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "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-js2s-typeof-js-type)", - "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" - }, - { - "line": 73, - "column": 8, - "endLine": 73, - "endColumn": 20, - "problem": "InstantiatedJsOjbect", - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 28, - "endLine": 73, - "endColumn": 30, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "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": 1, + "endLine": 16, + "endColumn": 69, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 54, + "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": 55, + "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": 15, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 11, + "endLine": 21, + "endColumn": 18, + "problem": "CallJSFunction", + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 11, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 19, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 8, + "endLine": 24, + "endColumn": 19, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 20, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 20, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 12, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 17, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 8, + "endLine": 27, + "endColumn": 17, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 12, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 11, + "endLine": 29, + "endColumn": 20, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 23, + "endLine": 31, + "endColumn": 35, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 20, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 8, + "endLine": 32, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 21, + "endLine": 34, + "endColumn": 33, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 22, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 12, + "endLine": 36, + "endColumn": 28, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 10, + "endLine": 42, + "endColumn": 28, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 24, + "endLine": 42, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 22, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 10, + "endLine": 44, + "endColumn": 22, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 21, + "endLine": 47, + "endColumn": 39, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 35, + "endLine": 47, + "endColumn": 38, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 7, + "endLine": 49, + "endColumn": 13, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 21, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 12, + "endLine": 61, + "endColumn": 21, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 28, + "endLine": 65, + "endColumn": 47, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 35, + "endLine": 65, + "endColumn": 47, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 1, + "endLine": 69, + "endColumn": 13, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 25, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 25, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 30, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 31, + "problem": "InterOpImportJsForTypeOf", + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 31, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 28, + "endLine": 72, + "endColumn": 30, + "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_typeof_js.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json old mode 100755 new mode 100644 index e913452998..a080a8877d --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json @@ -1,933 +1,861 @@ { - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR 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": 17, - "column": 1, - "endLine": 17, - "endColumn": 69, - "problem": "InterOpImportJs", - "autofix": [ - { - "start": 618, - "end": 686, - "replacementText": "", - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 69 - }, - { - "start": 795, - "end": 795, - "replacementText": "let GeneratedImportVar_1 = ESValue.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", - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 69 - } - ], - "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", - "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": 18, - "column": 1, - "endLine": 18, - "endColumn": 54, - "problem": "InterOpImportJs", - "autofix": [ - { - "start": 687, - "end": 740, - "replacementText": "", - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 54 - }, - { - "start": 795, - "end": 795, - "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_js');\nlet Doge = GeneratedImportVar_2.getPropertyByName('Dog');\n", - "line": 18, - "column": 1, - "endLine": 18, - "endColumn": 54 - } - ], - "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", - "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": 19, - "column": 1, - "endLine": 19, - "endColumn": 55, - "problem": "InterOpImportJs", - "autofix": [ - { - "start": 741, - "end": 795, - "replacementText": "", - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 55 - }, - { - "start": 795, - "end": 795, - "replacementText": "let GeneratedImportVar_3 = ESValue.load('./interop_import_js_js');\nlet wiki = GeneratedImportVar_3.getPropertyByName('Wiki');\n", - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 55 - } - ], - "suggest": "", - "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", - "severity": "ERROR" - }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 15, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 797, - "end": 811, - "replacementText": "myAaa.invoke().typeOf()", - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 15 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 11, - "endLine": 22, - "endColumn": 18, - "problem": "CallJSFunction", - "autofix": [ - { - "start": 831, - "end": 838, - "replacementText": "myAaa.invoke()", - "line": 22, - "column": 11, - "endLine": 22, - "endColumn": 18 - } - ], - "suggest": "", - "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 11, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 852, - "end": 862, - "replacementText": "Dog.typeOf()", - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 11 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 1, - "endLine": 25, - "endColumn": 19, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 872, - "end": 890, - "replacementText": "Dog.invoke(ESValue.wrap('doge')).typeOf()", - "line": 25, - "column": 1, - "endLine": 25, - "endColumn": 19 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "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": 900, - "end": 919, - "replacementText": "Doge.invoke(ESValue.wrap('doge')).typeOf()", - "line": 26, - "column": 1, - "endLine": 26, - "endColumn": 20 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "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": 929, - "end": 940, - "replacementText": "Wiki.typeOf()", - "line": 27, - "column": 1, - "endLine": 27, - "endColumn": 12 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 17, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 949, - "end": 965, - "replacementText": "Wiki.getPropertyByName('name').typeOf()", - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 17 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 8, - "endLine": 28, - "endColumn": 17, - "problem": "InteropObjectProperty", - "autofix": [ - { - "start": 956, - "end": 965, - "replacementText": "Wiki.getPropertyByName(\"name\")", - "line": 28, - "column": 8, - "endLine": 28, - "endColumn": 17 - } - ], - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 8, - "endLine": 28, - "endColumn": 17, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "Wiki.getPropertyByName('name').toString()", - "start": 956, - "end": 965, - "line": 28, - "column": 8, - "endLine": 28, - "endColumn": 17 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 12, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 974, - "end": 985, - "replacementText": "wiki.typeOf()", - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 12 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 11, - "endLine": 30, - "endColumn": 20, - "problem": "InteropObjectProperty", - "autofix": [ - { - "start": 1004, - "end": 1013, - "replacementText": "wiki.getPropertyByName(\"name\")", - "line": 30, - "column": 11, - "endLine": 30, - "endColumn": 20 - } - ], - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "severity": "ERROR" - }, - { - "line": 30, - "column": 11, - "endLine": 30, - "endColumn": 20, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "wiki.getPropertyByName('name').toString()", - "start": 1004, - "end": 1013, - "line": 30, - "column": 11, - "endLine": 30, - "endColumn": 20 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 32, - "column": 23, - "endLine": 32, - "endColumn": 35, - "problem": "InstantiatedJsOjbect", - "autofix": [ - { - "start": 1048, - "end": 1060, - "replacementText": "ClassA.instantiate()", - "line": 32, - "column": 23, - "endLine": 32, - "endColumn": 35 - } - ], - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 1, - "endLine": 33, - "endColumn": 20, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 1061, - "end": 1080, - "replacementText": "ClassA.instantiate().typeOf()", - "line": 33, - "column": 1, - "endLine": 33, - "endColumn": 20 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 8, - "endLine": 33, - "endColumn": 20, - "problem": "InstantiatedJsOjbect", - "autofix": [ - { - "start": 1068, - "end": 1080, - "replacementText": "ClassA.instantiate()", - "line": 33, - "column": 8, - "endLine": 33, - "endColumn": 20 - } - ], - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 35, - "column": 21, - "endLine": 35, - "endColumn": 33, - "problem": "InstantiatedJsOjbect", - "autofix": [ - { - "start": 1124, - "end": 1136, - "replacementText": "Person.instantiate()", - "line": 35, - "column": 21, - "endLine": 35, - "endColumn": 33 - } - ], - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 37, - "column": 12, - "endLine": 37, - "endColumn": 28, - "problem": "InteropCallObjectMethods", - "autofix": [ - { - "start": 1171, - "end": 1187, - "replacementText": "person.invokeMethod(\"getName\")", - "line": 37, - "column": 12, - "endLine": 37, - "endColumn": 28 - } - ], - "suggest": "", - "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 10, - "endLine": 43, - "endColumn": 28, - "problem": "LimitedVoidType", - "suggest": "", - "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", - "severity": "ERROR" - }, - { - "line": 43, - "column": 24, - "endLine": 43, - "endColumn": 27, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1312, - "end": 1315, - "replacementText": "111.0", - "line": 43, - "column": 24, - "endLine": 43, - "endColumn": 27 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 3, - "endLine": 45, - "endColumn": 22, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 1337, - "end": 1356, - "replacementText": "Person.instantiate().typeOf()", - "line": 45, - "column": 3, - "endLine": 45, - "endColumn": 22 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 45, - "column": 10, - "endLine": 45, - "endColumn": 22, - "problem": "InstantiatedJsOjbect", - "autofix": [ - { - "start": 1344, - "end": 1356, - "replacementText": "Person.instantiate()", - "line": 45, - "column": 10, - "endLine": 45, - "endColumn": 22 - } - ], - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "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": 48, - "column": 35, - "endLine": 48, - "endColumn": 38, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1403, - "end": 1406, - "replacementText": "111.0", - "line": 48, - "column": 35, - "endLine": 48, - "endColumn": 38 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "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": 1713, - "end": 1729, - "replacementText": "wiki.getPropertyByName('name').typeOf()", - "line": 62, - "column": 5, - "endLine": 62, - "endColumn": 21 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 62, - "column": 12, - "endLine": 62, - "endColumn": 21, - "problem": "InteropObjectProperty", - "autofix": [ - { - "start": 1720, - "end": 1729, - "replacementText": "wiki.getPropertyByName(\"name\")", - "line": 62, - "column": 12, - "endLine": 62, - "endColumn": 21 - } - ], - "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", - "severity": "ERROR" - }, - { - "line": 62, - "column": 12, - "endLine": 62, - "endColumn": 21, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "wiki.getPropertyByName('name').toString()", - "start": 1720, - "end": 1729, - "line": 62, - "column": 12, - "endLine": 62, - "endColumn": 21 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 66, - "column": 28, - "endLine": 66, - "endColumn": 47, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 1818, - "end": 1837, - "replacementText": "ClassA.instantiate().typeOf()", - "line": 66, - "column": 28, - "endLine": 66, - "endColumn": 47 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 66, - "column": 35, - "endLine": 66, - "endColumn": 47, - "problem": "InstantiatedJsOjbect", - "autofix": [ - { - "start": 1825, - "end": 1837, - "replacementText": "ClassA.instantiate()", - "line": 66, - "column": 35, - "endLine": 66, - "endColumn": 47 - } - ], - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 70, - "column": 1, - "endLine": 70, - "endColumn": 13, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 1858, - "end": 1870, - "replacementText": "myAaa.typeOf()", - "line": 70, - "column": 1, - "endLine": 70, - "endColumn": 13 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 1, - "endLine": 71, - "endColumn": 25, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 1880, - "end": 1904, - "replacementText": "Person.instantiate().getPropertyByName('name').typeOf()", - "line": 71, - "column": 1, - "endLine": 71, - "endColumn": 25 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 71, - "column": 8, - "endLine": 71, - "endColumn": 25, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "new Person().getPropertyByName('name').toString()", - "start": 1887, - "end": 1904, - "line": 71, - "column": 8, - "endLine": 71, - "endColumn": 25 - } - ], - "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": 1887, - "end": 1899, - "replacementText": "Person.instantiate()", - "line": 71, - "column": 8, - "endLine": 71, - "endColumn": 20 - } - ], - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 1, - "endLine": 72, - "endColumn": 30, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 1914, - "end": 1943, - "replacementText": "Person.instantiate().getPropertyByName('getName').invoke().typeOf()", - "line": 72, - "column": 1, - "endLine": 72, - "endColumn": 30 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "severity": "ERROR" - }, - { - "line": 72, - "column": 8, - "endLine": 72, - "endColumn": 20, - "problem": "InstantiatedJsOjbect", - "autofix": [ - { - "start": 1921, - "end": 1933, - "replacementText": "Person.instantiate()", - "line": 72, - "column": 8, - "endLine": 72, - "endColumn": 20 - } - ], - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 1, - "endLine": 73, - "endColumn": 31, - "problem": "InterOpImportJsForTypeOf", - "autofix": [ - { - "start": 1952, - "end": 1982, - "replacementText": "Person.instantiate().getPropertyByName('setAge').invoke(ESValue.wrap(22)).typeOf()", - "line": 73, - "column": 1, - "endLine": 73, - "endColumn": 31 - } - ], - "suggest": "", - "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", - "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" - }, - { - "line": 73, - "column": 8, - "endLine": 73, - "endColumn": 20, - "problem": "InstantiatedJsOjbect", - "autofix": [ - { - "start": 1959, - "end": 1971, - "replacementText": "Person.instantiate()", - "line": 73, - "column": 8, - "endLine": 73, - "endColumn": 20 - } - ], - "suggest": "", - "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", - "severity": "ERROR" - }, - { - "line": 73, - "column": 28, - "endLine": 73, - "endColumn": 30, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1979, - "end": 1981, - "replacementText": "22.0", - "line": 73, - "column": 28, - "endLine": 73, - "endColumn": 30 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "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": 1, + "endLine": 16, + "endColumn": 69, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 606, + "end": 674, + "replacementText": "", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 69 + }, + { + "start": 783, + "end": 783, + "replacementText": "let GeneratedImportVar_1 = ESValue.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", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 69 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 54, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 675, + "end": 728, + "replacementText": "", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 54 + }, + { + "start": 783, + "end": 783, + "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_js');\nlet Doge = GeneratedImportVar_2.getPropertyByName('Dog');\n", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 54 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 55, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 729, + "end": 783, + "replacementText": "", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 55 + }, + { + "start": 783, + "end": 783, + "replacementText": "let GeneratedImportVar_3 = ESValue.load('./interop_import_js_js');\nlet wiki = GeneratedImportVar_3.getPropertyByName('Wiki');\n", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 55 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 15, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 785, + "end": 799, + "replacementText": "myAaa.invoke().typeOf()", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 11, + "endLine": 21, + "endColumn": 18, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 819, + "end": 826, + "replacementText": "myAaa.invoke()", + "line": 21, + "column": 11, + "endLine": 21, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 11, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 840, + "end": 850, + "replacementText": "Dog.typeOf()", + "line": 23, + "column": 1, + "endLine": 23, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 19, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 860, + "end": 878, + "replacementText": "Dog.invoke(ESValue.wrap('doge')).typeOf()", + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 8, + "endLine": 24, + "endColumn": 19, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 20, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 888, + "end": 907, + "replacementText": "Doge.invoke(ESValue.wrap('doge')).typeOf()", + "line": 25, + "column": 1, + "endLine": 25, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 8, + "endLine": 25, + "endColumn": 20, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 12, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 917, + "end": 928, + "replacementText": "Wiki.typeOf()", + "line": 26, + "column": 1, + "endLine": 26, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 17, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 937, + "end": 953, + "replacementText": "Wiki.getPropertyByName('name').typeOf()", + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 8, + "endLine": 27, + "endColumn": 17, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 944, + "end": 953, + "replacementText": "Wiki.getPropertyByName(\"name\")", + "line": 27, + "column": 8, + "endLine": 27, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 12, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 962, + "end": 973, + "replacementText": "wiki.typeOf()", + "line": 28, + "column": 1, + "endLine": 28, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 11, + "endLine": 29, + "endColumn": 20, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 992, + "end": 1001, + "replacementText": "wiki.getPropertyByName(\"name\")", + "line": 29, + "column": 11, + "endLine": 29, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 23, + "endLine": 31, + "endColumn": 35, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1036, + "end": 1048, + "replacementText": "ClassA.instantiate()", + "line": 31, + "column": 23, + "endLine": 31, + "endColumn": 35 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 20, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1049, + "end": 1068, + "replacementText": "ClassA.instantiate().typeOf()", + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 8, + "endLine": 32, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1056, + "end": 1068, + "replacementText": "ClassA.instantiate()", + "line": 32, + "column": 8, + "endLine": 32, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 21, + "endLine": 34, + "endColumn": 33, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1112, + "end": 1124, + "replacementText": "Person.instantiate()", + "line": 34, + "column": 21, + "endLine": 34, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 22, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1136, + "end": 1147, + "replacementText": "person.getPropertyByName(\"name\")", + "line": 35, + "column": 11, + "endLine": 35, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 12, + "endLine": 36, + "endColumn": 28, + "problem": "InteropCallObjectMethods", + "autofix": [ + { + "start": 1159, + "end": 1175, + "replacementText": "person.invokeMethod(\"getName\")", + "line": 36, + "column": 12, + "endLine": 36, + "endColumn": 28 + } + ], + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 10, + "endLine": 42, + "endColumn": 28, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 24, + "endLine": 42, + "endColumn": 27, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1300, + "end": 1303, + "replacementText": "111.0", + "line": 42, + "column": 24, + "endLine": 42, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 22, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1325, + "end": 1344, + "replacementText": "Person.instantiate().typeOf()", + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 10, + "endLine": 44, + "endColumn": 22, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1332, + "end": 1344, + "replacementText": "Person.instantiate()", + "line": 44, + "column": 10, + "endLine": 44, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 21, + "endLine": 47, + "endColumn": 39, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 35, + "endLine": 47, + "endColumn": 38, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1391, + "end": 1394, + "replacementText": "111.0", + "line": 47, + "column": 35, + "endLine": 47, + "endColumn": 38 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 7, + "endLine": 49, + "endColumn": 13, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 21, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1701, + "end": 1717, + "replacementText": "wiki.getPropertyByName('name').typeOf()", + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 12, + "endLine": 61, + "endColumn": 21, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1708, + "end": 1717, + "replacementText": "wiki.getPropertyByName(\"name\")", + "line": 61, + "column": 12, + "endLine": 61, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 28, + "endLine": 65, + "endColumn": 47, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1806, + "end": 1825, + "replacementText": "ClassA.instantiate().typeOf()", + "line": 65, + "column": 28, + "endLine": 65, + "endColumn": 47 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 35, + "endLine": 65, + "endColumn": 47, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1813, + "end": 1825, + "replacementText": "ClassA.instantiate()", + "line": 65, + "column": 35, + "endLine": 65, + "endColumn": 47 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 1, + "endLine": 69, + "endColumn": 13, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1846, + "end": 1858, + "replacementText": "myAaa.typeOf()", + "line": 69, + "column": 1, + "endLine": 69, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 25, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1868, + "end": 1892, + "replacementText": "Person.instantiate().getPropertyByName('name').typeOf()", + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 25 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 25, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1875, + "end": 1892, + "replacementText": "new Person().getPropertyByName(\"name\")", + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 25 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1875, + "end": 1887, + "replacementText": "Person.instantiate()", + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 30, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1902, + "end": 1931, + "replacementText": "Person.instantiate().invokeMethod(\"getName\").typeOf()", + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 30 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1909, + "end": 1921, + "replacementText": "Person.instantiate()", + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 31, + "problem": "InterOpImportJsForTypeOf", + "autofix": [ + { + "start": 1940, + "end": 1970, + "replacementText": "Person.instantiate().invokeMethod(\"setAge\", ESValue.wrap(22)).typeOf()", + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 31 + } + ], + "suggest": "", + "rule": "The \"typeof\" expression can't be used with interop JS objects (arkts-interop-js2s-typeof-js-type)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 31, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 20, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1947, + "end": 1959, + "replacementText": "Person.instantiate()", + "line": 72, + "column": 8, + "endLine": 72, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 28, + "endLine": 72, + "endColumn": 30, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1967, + "end": 1969, + "replacementText": "22.0", + "line": 72, + "column": 28, + "endLine": 72, + "endColumn": 30 + } + ], + "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_typeof_js.ets.json b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.json index b61974a218..ca88f857e9 100755 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.json @@ -13,36 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file 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 index c5dde90dd5..197a8577ce 100644 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.ets @@ -12,8 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -'use static' + let GeneratedImportVar_3 = ESValue.load('./interop_import_js_js'); @@ -43,7 +42,7 @@ const aClass:ClassA = ClassA.instantiate() ClassA.instantiate().typeOf() //error typeof aClass; let person:Person = Person.instantiate(); -let name =person.name +let name =person.getPropertyByName("name") let name2 =person.invokeMethod("getName") function getPersonInfo(){ typeof person; @@ -79,5 +78,5 @@ class Object { myAaa.typeOf(); //error Person.instantiate().getPropertyByName('name').typeOf() //error -Person.instantiate().getPropertyByName('getName').invoke().typeOf() //error -Person.instantiate().getPropertyByName('setAge').invoke(ESValue.wrap(22.0)).typeOf() //error +Person.instantiate().invokeMethod("getName").typeOf() //error +Person.instantiate().invokeMethod("setAge", ESValue.wrap(22.0)).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 index 983fb8071b..f709470eef 100644 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.json @@ -1,168 +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": 66, - "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": 66, - "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": 66, - "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": 25, - "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": 22, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 47, - "column": 5, - "endLine": 47, - "endColumn": 42, - "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" - } - ] -} + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 66, + "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" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 66, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 66, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 62, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 62, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 25, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 5, + "endLine": 39, + "endColumn": 41, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 43, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 5, + "endLine": 46, + "endColumn": 42, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 7, + "endLine": 59, + "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 b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets old mode 100755 new mode 100644 index 3f72e3cf20..3aa24611b1 --- a/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets +++ b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets @@ -12,12 +12,52 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' -import {foo, person} from "./interop_not_have_property_js" +'use static' +import { foo, person, TestHelper, Machine, User, Person, Employee } from "./interop_not_have_property_js" foo.name foo.name = "456" person.age = 23 person.male = [2, 3] -foo.age = 12 \ No newline at end of file +foo.age = 12 +if (foo.name = "456") { print("true") } + +let a = new foo() +a.age = 12 + +let test_helper = new TestHelper("TEST_INSTANTIATE_JS_OBJECT"); +test_helper.test(() => { + let machine = new Machine(); + return machine.name === "machine"; // arkts-interop-js2s-access-js-prop +}, "machine.name === 'machine'"); + +test_helper.test(() => { + let user = new User("Bob"); + return user.id === "Bob"; // arkts-interop-js2s-access-js-prop +}, "user.id === 'Bob'"); + +test_helper.test(() => { +let user = new User(10); +return user.id === 10;// arkts-interop-js2s-access-js-prop +}, "user.id === 10"); + +test_helper.test(() => { + let user = new User(123n); + return user.id === 123n; // arkts-interop-js2s-access-js-prop +}, "user.id === 123n"); + +test_helper.test(() => { + let user = new User(true); + return user.id === true;// arkts-interop-js2s-access-js-prop +}, "user.id === true"); + +test_helper.test(() => { + let machine = new Person("John", 10); + return machine.name === "machine"; // arkts-interop-js2s-access-js-prop +}, "machine.name === 'machine'"); + +test_helper.test(() => { + let employee = new Employee(); + return employee.name === "employee"; // arkts-interop-js2s-access-js-prop +}, "employee.name === 'employee'"); \ 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 old mode 100755 new mode 100644 index ce2c2d2d38..18802c22d5 --- 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 @@ -18,7 +18,7 @@ "line": 17, "column": 1, "endLine": 17, - "endColumn": 59, + "endColumn": 106, "problem": "ImportAfterStatement", "suggest": "", "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", @@ -28,7 +28,7 @@ "line": 17, "column": 1, "endLine": 17, - "endColumn": 59, + "endColumn": 106, "problem": "InterOpImportJs", "suggest": "", "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", @@ -44,16 +44,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "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": 20, "column": 1, @@ -64,16 +54,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "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": 21, "column": 1, @@ -84,16 +64,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "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": 14, @@ -114,16 +84,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "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": 16, @@ -156,23 +116,393 @@ }, { "line": 23, - "column": 1, + "column": 11, "endLine": 23, - "endColumn": 8, - "problem": "InteropJsObjectUsage", + "endColumn": 13, + "problem": "NumericSemantics", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 23, - "column": 11, - "endLine": 23, + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 21, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, "endColumn": 13, + "problem": "InteropJsObjectConditionJudgment", + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 18, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 9, + "endLine": 26, + "endColumn": 18, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 11, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 9, + "endLine": 27, + "endColumn": 11, "problem": "NumericSemantics", "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 29, + "column": 19, + "endLine": 29, + "endColumn": 63, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 1, + "endLine": 33, + "endColumn": 33, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 19, + "endLine": 31, + "endColumn": 32, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 12, + "endLine": 32, + "endColumn": 38, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 12, + "endLine": 32, + "endColumn": 24, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 1, + "endLine": 38, + "endColumn": 24, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 16, + "endLine": 36, + "endColumn": 31, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 29, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 19, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 1, + "endLine": 43, + "endColumn": 21, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 12, + "endLine": 41, + "endColumn": 24, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 21, + "endLine": 41, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 8, + "endLine": 42, + "endColumn": 22, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 8, + "endLine": 42, + "endColumn": 15, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 20, + "endLine": 42, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 1, + "endLine": 48, + "endColumn": 23, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 16, + "endLine": 46, + "endColumn": 30, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 12, + "endLine": 47, + "endColumn": 28, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 12, + "endLine": 47, + "endColumn": 19, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 1, + "endLine": 53, + "endColumn": 23, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 16, + "endLine": 51, + "endColumn": 30, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 12, + "endLine": 52, + "endColumn": 28, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 12, + "endLine": 52, + "endColumn": 19, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 1, + "endLine": 58, + "endColumn": 33, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 19, + "endLine": 56, + "endColumn": 41, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 38, + "endLine": 56, + "endColumn": 40, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 12, + "endLine": 57, + "endColumn": 38, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 12, + "endLine": 57, + "endColumn": 24, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 63, + "endColumn": 35, + "problem": "InteropCallObjectMethods", + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 20, + "endLine": 61, + "endColumn": 34, + "problem": "InstantiatedJsOjbect", + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 40, + "problem": "InteropEqualityJudgment", + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 25, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "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 old mode 100755 new mode 100644 index 0c4beba4af..d66995a3c6 --- 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 @@ -18,7 +18,7 @@ "line": 17, "column": 1, "endLine": 17, - "endColumn": 59, + "endColumn": 106, "problem": "ImportAfterStatement", "suggest": "", "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", @@ -28,26 +28,26 @@ "line": 17, "column": 1, "endLine": 17, - "endColumn": 59, + "endColumn": 106, "problem": "InterOpImportJs", "autofix": [ { "start": 618, - "end": 676, + "end": 723, "replacementText": "", "line": 17, "column": 1, "endLine": 17, - "endColumn": 59 + "endColumn": 106 }, { - "start": 676, - "end": 676, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_not_have_property_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet person = GeneratedImportVar_1.getPropertyByName('person');\n", + "start": 723, + "end": 723, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_not_have_property_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet person = GeneratedImportVar_1.getPropertyByName('person');\nlet TestHelper = GeneratedImportVar_1.getPropertyByName('TestHelper');\nlet Machine = GeneratedImportVar_1.getPropertyByName('Machine');\nlet User = GeneratedImportVar_1.getPropertyByName('User');\nlet Person = GeneratedImportVar_1.getPropertyByName('Person');\nlet Employee = GeneratedImportVar_1.getPropertyByName('Employee');\n", "line": 17, "column": 1, "endLine": 17, - "endColumn": 59 + "endColumn": 106 } ], "suggest": "", @@ -62,8 +62,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 678, - "end": 686, + "start": 725, + "end": 733, "replacementText": "foo.getPropertyByName(\"name\")", "line": 19, "column": 1, @@ -75,27 +75,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, - { - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 9, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo.getPropertyByName('name').toString()", - "start": 678, - "end": 686, - "line": 19, - "column": 1, - "endLine": 19, - "endColumn": 9 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, { "line": 20, "column": 1, @@ -104,8 +83,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 687, - "end": 703, + "start": 734, + "end": 750, "replacementText": "foo.setPropertyByName(\"name\", ESValue.wrap(\"456\"))", "line": 20, "column": 1, @@ -117,27 +96,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, - { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 9, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo.getPropertyByName('name').toString()", - "start": 687, - "end": 695, - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 9 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, { "line": 21, "column": 1, @@ -146,8 +104,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 704, - "end": 719, + "start": 751, + "end": 766, "replacementText": "person.setPropertyByName(\"age\", ESValue.wrap(23))", "line": 21, "column": 1, @@ -159,27 +117,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, - { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 11, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "person.getPropertyByName('age').toNumber()", - "start": 704, - "end": 714, - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 11 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, { "line": 21, "column": 14, @@ -188,8 +125,8 @@ "problem": "NumericSemantics", "autofix": [ { - "start": 717, - "end": 719, + "start": 764, + "end": 766, "replacementText": "23.0", "line": 21, "column": 14, @@ -209,8 +146,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 720, - "end": 740, + "start": 767, + "end": 787, "replacementText": "person.setPropertyByName(\"male\", ESValue.wrap([2, 3]))", "line": 22, "column": 1, @@ -222,27 +159,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, - { - "line": 22, - "column": 1, - "endLine": 22, - "endColumn": 12, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "person.getPropertyByName('male')", - "start": 720, - "end": 731, - "line": 22, - "column": 1, - "endLine": 22, - "endColumn": 12 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, { "line": 22, "column": 16, @@ -251,8 +167,8 @@ "problem": "NumericSemantics", "autofix": [ { - "start": 735, - "end": 736, + "start": 782, + "end": 783, "replacementText": "2.0", "line": 22, "column": 16, @@ -272,8 +188,8 @@ "problem": "NumericSemantics", "autofix": [ { - "start": 738, - "end": 739, + "start": 785, + "end": 786, "replacementText": "3.0", "line": 22, "column": 19, @@ -293,8 +209,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 741, - "end": 753, + "start": 788, + "end": 800, "replacementText": "foo.setPropertyByName(\"age\", ESValue.wrap(12))", "line": 23, "column": 1, @@ -308,45 +224,811 @@ }, { "line": 23, - "column": 1, + "column": 11, "endLine": 23, - "endColumn": 8, - "problem": "InteropJsObjectUsage", + "endColumn": 13, + "problem": "NumericSemantics", "autofix": [ { - "replacementText": "foo.getPropertyByName('age')", - "start": 741, - "end": 748, + "start": 798, + "end": 800, + "replacementText": "12.0", "line": 23, - "column": 1, + "column": 11, "endLine": 23, - "endColumn": 8 + "endColumn": 13 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 23, - "column": 11, - "endLine": 23, + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 21, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 805, + "end": 821, + "replacementText": "foo.setPropertyByName(\"name\", ESValue.wrap(\"456\"))", + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, "endColumn": 13, + "problem": "InteropJsObjectConditionJudgment", + "autofix": [ + { + "replacementText": "foo.getPropertyByName('name').toString()", + "start": 805, + "end": 813, + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 18, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 9, + "endLine": 26, + "endColumn": 18, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 850, + "end": 859, + "replacementText": "foo.instantiate()", + "line": 26, + "column": 9, + "endLine": 26, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 11, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 860, + "end": 870, + "replacementText": "a.setPropertyByName(\"age\", ESValue.wrap(12))", + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 9, + "endLine": 27, + "endColumn": 11, "problem": "NumericSemantics", "autofix": [ { - "start": 751, - "end": 753, + "start": 868, + "end": 870, "replacementText": "12.0", - "line": 23, - "column": 11, - "endLine": 23, - "endColumn": 13 + "line": 27, + "column": 9, + "endLine": 27, + "endColumn": 11 } ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 29, + "column": 19, + "endLine": 29, + "endColumn": 63, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 890, + "end": 934, + "replacementText": "TestHelper.instantiate(ESValue.wrap(\"TEST_INSTANTIATE_JS_OBJECT\"))", + "line": 29, + "column": 19, + "endLine": 29, + "endColumn": 63 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 1, + "endLine": 33, + "endColumn": 33, + "problem": "InteropCallObjectMethods", + "autofix": [ + { + "start": 936, + "end": 1102, + "replacementText": "test_helper.invokeMethod(\"test\", ESValue.wrap(() => {\n let machine = new Machine();\n return machine.name === \"machine\"; // arkts-interop-js2s-access-js-prop\n}), ESValue.wrap(\"machine.name === 'machine'\"))", + "line": 30, + "column": 1, + "endLine": 33, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 19, + "endLine": 31, + "endColumn": 32, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 979, + "end": 992, + "replacementText": "Machine.instantiate()", + "line": 31, + "column": 19, + "endLine": 31, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 12, + "endLine": 32, + "endColumn": 38, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 1005, + "end": 1031, + "replacementText": "machine.name.areStrictlyEqual(\"machine\")", + "line": 32, + "column": 12, + "endLine": 32, + "endColumn": 38 + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 12, + "endLine": 32, + "endColumn": 24, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1005, + "end": 1017, + "replacementText": "machine.getPropertyByName(\"name\")", + "line": 32, + "column": 12, + "endLine": 32, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 1, + "endLine": 38, + "endColumn": 24, + "problem": "InteropCallObjectMethods", + "autofix": [ + { + "start": 1105, + "end": 1252, + "replacementText": "test_helper.invokeMethod(\"test\", ESValue.wrap(() => {\n let user = new User(\"Bob\");\n return user.id === \"Bob\"; // arkts-interop-js2s-access-js-prop\n}), ESValue.wrap(\"user.id === 'Bob'\"))", + "line": 35, + "column": 1, + "endLine": 38, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 16, + "endLine": 36, + "endColumn": 31, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1145, + "end": 1160, + "replacementText": "User.instantiate(ESValue.wrap(\"Bob\"))", + "line": 36, + "column": 16, + "endLine": 36, + "endColumn": 31 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 29, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 1173, + "end": 1190, + "replacementText": "user.id.areStrictlyEqual(\"Bob\")", + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 29 + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 19, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1173, + "end": 1180, + "replacementText": "user.getPropertyByName(\"id\")", + "line": 37, + "column": 12, + "endLine": 37, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 1, + "endLine": 43, + "endColumn": 21, + "problem": "InteropCallObjectMethods", + "autofix": [ + { + "start": 1255, + "end": 1384, + "replacementText": "test_helper.invokeMethod(\"test\", ESValue.wrap(() => {\nlet user = new User(10);\nreturn user.id === 10;// arkts-interop-js2s-access-js-prop\n}), ESValue.wrap(\"user.id === 10\"))", + "line": 40, + "column": 1, + "endLine": 43, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 12, + "endLine": 41, + "endColumn": 24, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1291, + "end": 1303, + "replacementText": "User.instantiate(ESValue.wrap(10))", + "line": 41, + "column": 12, + "endLine": 41, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 21, + "endLine": 41, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1300, + "end": 1302, + "replacementText": "10.0", + "line": 41, + "column": 21, + "endLine": 41, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 8, + "endLine": 42, + "endColumn": 22, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 1312, + "end": 1326, + "replacementText": "user.id.areStrictlyEqual(10)", + "line": 42, + "column": 8, + "endLine": 42, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 8, + "endLine": 42, + "endColumn": 15, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1312, + "end": 1319, + "replacementText": "user.getPropertyByName(\"id\")", + "line": 42, + "column": 8, + "endLine": 42, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 20, + "endLine": 42, + "endColumn": 22, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1324, + "end": 1326, + "replacementText": "10.0", + "line": 42, + "column": 20, + "endLine": 42, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 1, + "endLine": 48, + "endColumn": 23, + "problem": "InteropCallObjectMethods", + "autofix": [ + { + "start": 1387, + "end": 1531, + "replacementText": "test_helper.invokeMethod(\"test\", ESValue.wrap(() => {\n let user = new User(123n);\n return user.id === 123n; // arkts-interop-js2s-access-js-prop\n}), ESValue.wrap(\"user.id === 123n\"))", + "line": 45, + "column": 1, + "endLine": 48, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 16, + "endLine": 46, + "endColumn": 30, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1427, + "end": 1441, + "replacementText": "User.instantiate(ESValue.wrap(123n))", + "line": 46, + "column": 16, + "endLine": 46, + "endColumn": 30 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 12, + "endLine": 47, + "endColumn": 28, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 1454, + "end": 1470, + "replacementText": "user.id.areStrictlyEqual(123n)", + "line": 47, + "column": 12, + "endLine": 47, + "endColumn": 28 + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 12, + "endLine": 47, + "endColumn": 19, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1454, + "end": 1461, + "replacementText": "user.getPropertyByName(\"id\")", + "line": 47, + "column": 12, + "endLine": 47, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 1, + "endLine": 53, + "endColumn": 23, + "problem": "InteropCallObjectMethods", + "autofix": [ + { + "start": 1534, + "end": 1677, + "replacementText": "test_helper.invokeMethod(\"test\", ESValue.wrap(() => {\n let user = new User(true);\n return user.id === true;// arkts-interop-js2s-access-js-prop\n}), ESValue.wrap(\"user.id === true\"))", + "line": 50, + "column": 1, + "endLine": 53, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 16, + "endLine": 51, + "endColumn": 30, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1574, + "end": 1588, + "replacementText": "User.instantiate(ESValue.wrap(true))", + "line": 51, + "column": 16, + "endLine": 51, + "endColumn": 30 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 12, + "endLine": 52, + "endColumn": 28, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 1601, + "end": 1617, + "replacementText": "user.id.areStrictlyEqual(true)", + "line": 52, + "column": 12, + "endLine": 52, + "endColumn": 28 + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 12, + "endLine": 52, + "endColumn": 19, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1601, + "end": 1608, + "replacementText": "user.getPropertyByName(\"id\")", + "line": 52, + "column": 12, + "endLine": 52, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 1, + "endLine": 58, + "endColumn": 33, + "problem": "InteropCallObjectMethods", + "autofix": [ + { + "start": 1680, + "end": 1855, + "replacementText": "test_helper.invokeMethod(\"test\", ESValue.wrap(() => {\n let machine = new Person(\"John\", 10);\n return machine.name === \"machine\"; // arkts-interop-js2s-access-js-prop\n}), ESValue.wrap(\"machine.name === 'machine'\"))", + "line": 55, + "column": 1, + "endLine": 58, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 19, + "endLine": 56, + "endColumn": 41, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1723, + "end": 1745, + "replacementText": "Person.instantiate(ESValue.wrap(\"John\"), ESValue.wrap(10))", + "line": 56, + "column": 19, + "endLine": 56, + "endColumn": 41 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 38, + "endLine": 56, + "endColumn": 40, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1742, + "end": 1744, + "replacementText": "10.0", + "line": 56, + "column": 38, + "endLine": 56, + "endColumn": 40 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 12, + "endLine": 57, + "endColumn": 38, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 1758, + "end": 1784, + "replacementText": "machine.name.areStrictlyEqual(\"machine\")", + "line": 57, + "column": 12, + "endLine": 57, + "endColumn": 38 + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 12, + "endLine": 57, + "endColumn": 24, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1758, + "end": 1770, + "replacementText": "machine.getPropertyByName(\"name\")", + "line": 57, + "column": 12, + "endLine": 57, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 1, + "endLine": 63, + "endColumn": 35, + "problem": "InteropCallObjectMethods", + "autofix": [ + { + "start": 1858, + "end": 2030, + "replacementText": "test_helper.invokeMethod(\"test\", ESValue.wrap(() => {\n let employee = new Employee();\n return employee.name === \"employee\"; // arkts-interop-js2s-access-js-prop\n}), ESValue.wrap(\"employee.name === 'employee'\"))", + "line": 60, + "column": 1, + "endLine": 63, + "endColumn": 35 + } + ], + "suggest": "", + "rule": "Calling methods of JS Object directly in interop is not allowed (arkts-interop-js2s-call-js-method)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 20, + "endLine": 61, + "endColumn": 34, + "problem": "InstantiatedJsOjbect", + "autofix": [ + { + "start": 1902, + "end": 1916, + "replacementText": "Employee.instantiate()", + "line": 61, + "column": 20, + "endLine": 61, + "endColumn": 34 + } + ], + "suggest": "", + "rule": "ArkTS directly instantiated JS objects is not supported (arkts-interop-js2s-create-js-instance)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 40, + "problem": "InteropEqualityJudgment", + "autofix": [ + { + "start": 1929, + "end": 1957, + "replacementText": "employee.name.areStrictlyEqual(\"employee\")", + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 40 + } + ], + "suggest": "", + "rule": "\"JS\" objects can't be used directly as operands of the equality operators (arkts-interop-js2s-equality-judgment)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 25, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1929, + "end": 1942, + "replacementText": "employee.getPropertyByName(\"name\")", + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 25 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "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 838a0500a5..e96c8ee4d2 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 @@ -18,11 +18,21 @@ "line": 17, "column": 1, "endLine": 17, - "endColumn": 59, + "endColumn": 106, "problem": "ImportAfterStatement", "suggest": "", "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "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/interop/interop_not_have_property_arkts2.ets.migrate.ets b/ets2panda/linter/test/interop/interop_not_have_property_arkts2.ets.migrate.ets index 586868511b..b5185b29e4 100644 --- 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 @@ -12,15 +12,60 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' +'use static' let GeneratedImportVar_1 = ESValue.load('./interop_not_have_property_js'); let foo = GeneratedImportVar_1.getPropertyByName('foo'); let person = GeneratedImportVar_1.getPropertyByName('person'); +let TestHelper = GeneratedImportVar_1.getPropertyByName('TestHelper'); +let Machine = GeneratedImportVar_1.getPropertyByName('Machine'); +let User = GeneratedImportVar_1.getPropertyByName('User'); +let Person = GeneratedImportVar_1.getPropertyByName('Person'); +let Employee = GeneratedImportVar_1.getPropertyByName('Employee'); foo.getPropertyByName("name") foo.setPropertyByName("name", ESValue.wrap("456")) person.setPropertyByName("age", ESValue.wrap(23.0)) person.setPropertyByName("male", ESValue.wrap([2.0, 3.0])) -foo.setPropertyByName("age", ESValue.wrap(12.0)) \ No newline at end of file +foo.setPropertyByName("age", ESValue.wrap(12.0)) +if (foo.setPropertyByName("name", ESValue.wrap("456"))) { print("true") } + +let a = foo.instantiate() +a.setPropertyByName("age", ESValue.wrap(12.0)) + +let test_helper = TestHelper.instantiate(ESValue.wrap("TEST_INSTANTIATE_JS_OBJECT")); +test_helper.invokeMethod("test", ESValue.wrap(() => { + let machine = new Machine(); + return machine.name === "machine"; // arkts-interop-js2s-access-js-prop +}), ESValue.wrap("machine.name === 'machine'")); + +test_helper.invokeMethod("test", ESValue.wrap(() => { + let user = new User("Bob"); + return user.id === "Bob"; // arkts-interop-js2s-access-js-prop +}), ESValue.wrap("user.id === 'Bob'")); + +test_helper.invokeMethod("test", ESValue.wrap(() => { +let user = new User(10.0); +return user.id === 10.0;// arkts-interop-js2s-access-js-prop +}), ESValue.wrap("user.id === 10")); + +test_helper.invokeMethod("test", ESValue.wrap(() => { + let user = new User(123n); + return user.id === 123n; // arkts-interop-js2s-access-js-prop +}), ESValue.wrap("user.id === 123n")); + +test_helper.invokeMethod("test", ESValue.wrap(() => { + let user = new User(true); + return user.id === true;// arkts-interop-js2s-access-js-prop +}), ESValue.wrap("user.id === true")); + +test_helper.invokeMethod("test", ESValue.wrap(() => { + let machine = new Person("John", 10.0); + return machine.name === "machine"; // arkts-interop-js2s-access-js-prop +}), ESValue.wrap("machine.name === 'machine'")); + +test_helper.invokeMethod("test", ESValue.wrap(() => { + let employee = new Employee(); + return employee.name === "employee"; // arkts-interop-js2s-access-js-prop +}), ESValue.wrap("employee.name === 'employee'")); \ 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 index 17bc19346a..540b5557d4 100644 --- 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 @@ -43,6 +43,216 @@ "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 70, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 64, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 5, + "endLine": 23, + "endColumn": 62, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 66, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 5, + "endLine": 34, + "endColumn": 26, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 85, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 9, + "endLine": 39, + "endColumn": 32, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 23, + "endLine": 39, + "endColumn": 30, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 9, + "endLine": 44, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 20, + "endLine": 44, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 5, + "endLine": 49, + "endColumn": 26, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 16, + "endLine": 49, + "endColumn": 20, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 9, + "endLine": 54, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 20, + "endLine": 54, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 9, + "endLine": 59, + "endColumn": 30, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 20, + "endLine": 59, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 9, + "endLine": 64, + "endColumn": 43, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 23, + "endLine": 64, + "endColumn": 29, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 9, + "endLine": 69, + "endColumn": 34, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 24, + "endLine": 69, + "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/interop/interop_not_have_property_js.js b/ets2panda/linter/test/interop/interop_not_have_property_js.js index cd3b2ad79c..45b2953a2c 100755 --- a/ets2panda/linter/test/interop/interop_not_have_property_js.js +++ b/ets2panda/linter/test/interop/interop_not_have_property_js.js @@ -13,4 +13,61 @@ * limitations under the License. */ export let foo = {name: "123"} -export let person = {age: 12, male: [1, 2, 3]} \ No newline at end of file +export let person = {age: 12, male: [1, 2, 3]} +export class TestHelper { + constructor(testName) { + this.testName = testName; + this.passed = 0; + this.failed = 0; + } + + test(testFunction, description) { + const result = testFunction(); + if (result) { + this.passed++; + console.log(`[PASS] ${this.testName}: ${description}`); + } else { + this.failed++; + console.error(`[FAIL] ${this.testName}: ${description}`); + } + } + + getStats() { + return { + passed: this.passed, + failed: this.failed, + total: this.passed + this.failed + }; + } + + printSummary() { + const stats = this.getStats(); + } +} + +export class Machine { + name = "machine"; +} + +export class User { + id; + constructor(a){ + this.id = a; + } +} + +export class Person { + name; + age; + constructor(a, b){ + this.name = a; + this.age = b; + } +} + +export class Employee { + name; + constructor(a = "employee"){ + this.name = a; + } +} \ 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 old mode 100755 new mode 100644 index 1049aac0f0..8c41ae4182 --- a/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets +++ b/ets2panda/linter/test/interop/interop_not_have_property_num_arkts2.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' import {foo} from "./interop_property_num_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 old mode 100755 new mode 100644 index 414d9f7721..ccb4943134 --- 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 @@ -15,19 +15,9 @@ ], "result": [ { - "line": 17, + "line": 16, "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, + "endLine": 16, "endColumn": 46, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 1, - "endLine": 19, + "endLine": 18, "endColumn": 9, "problem": "InteropNoHaveNum", "suggest": "", @@ -45,23 +35,33 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 2, - "endLine": 19, + "endLine": 18, "endColumn": 9, "problem": "InteropObjectProperty", "suggest": "", "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, { "line": 19, "column": 2, "endLine": 19, "endColumn": 9, - "problem": "InteropJsObjectUsage", + "problem": "InteropObjectProperty", "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -84,16 +84,6 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "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": 21, "column": 1, @@ -114,21 +104,11 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "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": 22, "column": 1, "endLine": 22, - "endColumn": 9, + "endColumn": 11, "problem": "InteropNoHaveNum", "suggest": "", "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", @@ -136,24 +116,14 @@ }, { "line": 22, - "column": 2, + "column": 3, "endLine": 22, - "endColumn": 9, + "endColumn": 10, "problem": "InteropObjectProperty", "suggest": "", "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "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": 23, "column": 1, @@ -174,16 +144,6 @@ "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": 24, "column": 1, @@ -204,16 +164,6 @@ "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": 25, "column": 1, @@ -233,46 +183,6 @@ "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": 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" } ] } \ 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 old mode 100755 new mode 100644 index 4452cefcfd..c638dec23e --- 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 @@ -15,35 +15,29 @@ ], "result": [ { - "line": 17, + "line": 16, "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, + "endLine": 16, "endColumn": 46, "problem": "InterOpImportJs", "autofix": [ { - "start": 618, - "end": 663, + "start": 605, + "end": 650, "replacementText": "", - "line": 17, + "line": 16, "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 46 }, { - "start": 663, - "end": 663, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_property_num_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n" + "start": 650, + "end": 650, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_property_num_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 46 } ], "suggest": "", @@ -51,19 +45,19 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 1, - "endLine": 19, + "endLine": 18, "endColumn": 9, "problem": "InteropNoHaveNum", "autofix": [ { - "start": 666, - "end": 673, + "start": 653, + "end": 660, "replacementText": "foo.getPropertyByName(\"num\").toNumber()", - "line": 19, + "line": 18, "column": 1, - "endLine": 19, + "endLine": 18, "endColumn": 9 } ], @@ -72,19 +66,19 @@ "severity": "ERROR" }, { - "line": 19, + "line": 18, "column": 2, - "endLine": 19, + "endLine": 18, "endColumn": 9, "problem": "InteropObjectProperty", "autofix": [ { - "start": 666, - "end": 673, + "start": 653, + "end": 660, "replacementText": "foo.getPropertyByName(\"num\")", - "line": 19, + "line": 18, "column": 2, - "endLine": 19, + "endLine": 18, "endColumn": 9 } ], @@ -94,65 +88,65 @@ }, { "line": 19, - "column": 2, + "column": 1, "endLine": 19, "endColumn": 9, - "problem": "InteropJsObjectUsage", + "problem": "InteropNoHaveNum", "autofix": [ { - "replacementText": "foo.getPropertyByName('num').toNumber()", - "start": 666, - "end": 673, + "start": 663, + "end": 670, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()", "line": 19, - "column": 2, + "column": 1, "endLine": 19, "endColumn": 9 } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { - "line": 20, - "column": 1, - "endLine": 20, + "line": 19, + "column": 2, + "endLine": 19, "endColumn": 9, - "problem": "InteropNoHaveNum", + "problem": "InteropObjectProperty", "autofix": [ { - "start": 676, - "end": 683, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", - "line": 20, - "column": 1, - "endLine": 20, + "start": 663, + "end": 670, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 19, + "column": 2, + "endLine": 19, "endColumn": 9 } ], "suggest": "", - "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { "line": 20, - "column": 2, + "column": 1, "endLine": 20, "endColumn": 9, - "problem": "InteropObjectProperty", + "problem": "InteropNoHaveNum", "autofix": [ { - "start": 676, - "end": 683, - "replacementText": "foo.getPropertyByName(\"num\")", + "start": 673, + "end": 680, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()", "line": 20, - "column": 2, + "column": 1, "endLine": 20, "endColumn": 9 } ], "suggest": "", - "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", "severity": "ERROR" }, { @@ -160,12 +154,12 @@ "column": 2, "endLine": 20, "endColumn": 9, - "problem": "InteropJsObjectUsage", + "problem": "InteropObjectProperty", "autofix": [ { - "replacementText": "foo.getPropertyByName('num').toNumber()", - "start": 676, - "end": 683, + "start": 673, + "end": 680, + "replacementText": "foo.getPropertyByName(\"num\")", "line": 20, "column": 2, "endLine": 20, @@ -173,7 +167,7 @@ } ], "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, { @@ -184,8 +178,8 @@ "problem": "InteropNoHaveNum", "autofix": [ { - "start": 686, - "end": 693, + "start": 683, + "end": 690, "replacementText": "foo.getPropertyByName(\"num\").toNumber()", "line": 21, "column": 1, @@ -205,8 +199,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 686, - "end": 693, + "start": 683, + "end": 690, "replacementText": "foo.getPropertyByName(\"num\")", "line": 21, "column": 2, @@ -218,42 +212,21 @@ "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, - { - "line": 21, - "column": 2, - "endLine": 21, - "endColumn": 9, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo.getPropertyByName('num').toNumber()", - "start": 686, - "end": 693, - "line": 21, - "column": 2, - "endLine": 21, - "endColumn": 9 - } - ], - "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": 9, + "endColumn": 11, "problem": "InteropNoHaveNum", "autofix": [ { - "start": 696, - "end": 703, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "start": 693, + "end": 702, + "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", "line": 22, "column": 1, "endLine": 22, - "endColumn": 9 + "endColumn": 11 } ], "suggest": "", @@ -262,46 +235,25 @@ }, { "line": 22, - "column": 2, + "column": 3, "endLine": 22, - "endColumn": 9, + "endColumn": 10, "problem": "InteropObjectProperty", "autofix": [ { - "start": 696, - "end": 703, + "start": 694, + "end": 701, "replacementText": "foo.getPropertyByName(\"num\")", "line": 22, - "column": 2, + "column": 3, "endLine": 22, - "endColumn": 9 + "endColumn": 10 } ], "suggest": "", "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", "severity": "ERROR" }, - { - "line": 22, - "column": 2, - "endLine": 22, - "endColumn": 9, - "problem": "InteropJsObjectUsage", - "autofix": [ - { - "replacementText": "foo.getPropertyByName('num').toNumber()", - "start": 696, - "end": 703, - "line": 22, - "column": 2, - "endLine": 22, - "endColumn": 9 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, { "line": 23, "column": 1, @@ -310,8 +262,8 @@ "problem": "InteropNoHaveNum", "autofix": [ { - "start": 706, - "end": 715, + "start": 705, + "end": 714, "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", "line": 23, "column": 1, @@ -331,8 +283,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 707, - "end": 714, + "start": 706, + "end": 713, "replacementText": "foo.getPropertyByName(\"num\")", "line": 23, "column": 3, @@ -344,27 +296,6 @@ "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, - "line": 23, - "column": 3, - "endLine": 23, - "endColumn": 10 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, { "line": 24, "column": 1, @@ -373,8 +304,8 @@ "problem": "InteropNoHaveNum", "autofix": [ { - "start": 718, - "end": 727, + "start": 717, + "end": 726, "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", "line": 24, "column": 1, @@ -394,8 +325,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 719, - "end": 726, + "start": 718, + "end": 725, "replacementText": "foo.getPropertyByName(\"num\")", "line": 24, "column": 3, @@ -407,27 +338,6 @@ "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, - "line": 24, - "column": 3, - "endLine": 24, - "endColumn": 10 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, { "line": 25, "column": 1, @@ -436,8 +346,8 @@ "problem": "InteropNoHaveNum", "autofix": [ { - "start": 730, - "end": 739, + "start": 729, + "end": 738, "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", "line": 25, "column": 1, @@ -457,8 +367,8 @@ "problem": "InteropObjectProperty", "autofix": [ { - "start": 731, - "end": 738, + "start": 730, + "end": 737, "replacementText": "foo.getPropertyByName(\"num\")", "line": 25, "column": 3, @@ -469,90 +379,6 @@ "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, - "line": 25, - "column": 3, - "endLine": 25, - "endColumn": 10 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 1, - "endLine": 26, - "endColumn": 11, - "problem": "InteropNoHaveNum", - "autofix": [ - { - "start": 742, - "end": 751, - "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", - "line": 26, - "column": 1, - "endLine": 26, - "endColumn": 11 - } - ], - "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\")", - "line": 26, - "column": 3, - "endLine": 26, - "endColumn": 10 - } - ], - "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, - "line": 26, - "column": 3, - "endLine": 26, - "endColumn": 10 - } - ], - "suggest": "", - "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js-object-usage)", - "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 456612d680..ca88f857e9 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 @@ -13,16 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file 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 index 1a22e1418c..09086d9892 100644 --- 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 @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' let GeneratedImportVar_1 = ESValue.load('./interop_property_num_js'); let foo = GeneratedImportVar_1.getPropertyByName('foo'); 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 index 01cf629ed9..ef4a1a04e1 100644 --- 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 @@ -15,9 +15,9 @@ ], "result": [ { - "line": 17, + "line": 16, "column": 5, - "endLine": 17, + "endLine": 16, "endColumn": 69, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 5, - "endLine": 18, + "endLine": 17, "endColumn": 56, "problem": "AnyType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 20, "column": 1, - "endLine": 21, + "endLine": 20, "endColumn": 41, "problem": "UnaryArithmNotNumber", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 22, + "line": 21, "column": 1, - "endLine": 22, + "endLine": 21, "endColumn": 41, "problem": "UnaryArithmNotNumber", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 23, "column": 1, - "endLine": 24, + "endLine": 23, "endColumn": 41, "problem": "UnaryArithmNotNumber", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 24, "column": 1, - "endLine": 25, + "endLine": 24, "endColumn": 43, "problem": "UnaryArithmNotNumber", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 1, - "endLine": 26, + "endLine": 25, "endColumn": 43, "problem": "UnaryArithmNotNumber", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 27, "column": 1, - "endLine": 28, + "endLine": 27, "endColumn": 43, "problem": "UnaryArithmNotNumber", "suggest": "", @@ -95,4 +95,4 @@ "severity": "ERROR" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_await_js_promise.ets b/ets2panda/linter/test/interop/no_await_js_promise.ets old mode 100755 new mode 100644 index 9247c363b4..124f7b4dab --- a/ets2panda/linter/test/interop/no_await_js_promise.ets +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets @@ -1,65 +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. - */ -'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()); +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +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 index 66fb88f859..6958168fef 100755 --- a/ets2panda/linter/test/interop/no_await_js_promise.ets.args.json +++ b/ets2panda/linter/test/interop/no_await_js_promise.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/no_await_js_promise.ets.arkts2.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.arkts2.json old mode 100755 new mode 100644 index 5021d02c43..13cd6170a9 --- a/ets2panda/linter/test/interop/no_await_js_promise.ets.arkts2.json +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.arkts2.json @@ -1,33 +1,9 @@ { - "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT WARRANTIES OR 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, + "line": 16, "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, + "endLine": 16, "endColumn": 89, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +11,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 19, "column": 10, - "endLine": 20, + "endLine": 19, "endColumn": 17, "problem": "NoAwaitJsPromise", "suggest": "", @@ -45,9 +21,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 23, "column": 10, - "endLine": 24, + "endLine": 23, "endColumn": 21, "problem": "NoAwaitJsPromise", "suggest": "", @@ -55,19 +31,9 @@ "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, + "line": 27, "column": 10, - "endLine": 28, + "endLine": 27, "endColumn": 25, "problem": "NoAwaitJsPromise", "suggest": "", @@ -75,29 +41,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 35, "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": "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, + "endLine": 35, "endColumn": 26, "problem": "NoAwaitJsPromise", "suggest": "", @@ -105,9 +51,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 40, "column": 12, - "endLine": 41, + "endLine": 40, "endColumn": 19, "problem": "NoAwaitJsPromise", "suggest": "", @@ -115,9 +61,9 @@ "severity": "ERROR" }, { - "line": 45, + "line": 44, "column": 12, - "endLine": 45, + "endLine": 44, "endColumn": 27, "problem": "NoAwaitJsPromise", "suggest": "", @@ -125,9 +71,9 @@ "severity": "ERROR" }, { - "line": 49, + "line": 48, "column": 20, - "endLine": 49, + "endLine": 48, "endColumn": 21, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -135,9 +81,9 @@ "severity": "ERROR" }, { - "line": 50, + "line": 49, "column": 3, - "endLine": 52, + "endLine": 51, "endColumn": 4, "problem": "ObjectLiteralProperty", "suggest": "", @@ -145,9 +91,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 50, "column": 12, - "endLine": 51, + "endLine": 50, "endColumn": 28, "problem": "NoAwaitJsPromise", "suggest": "", @@ -155,9 +101,9 @@ "severity": "ERROR" }, { - "line": 55, + "line": 54, "column": 12, - "endLine": 55, + "endLine": 54, "endColumn": 23, "problem": "NoAwaitJsPromise", "suggest": "", @@ -165,19 +111,9 @@ "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, + "line": 58, "column": 2, - "endLine": 61, + "endLine": 60, "endColumn": 2, "problem": "FunctionExpression", "suggest": "", @@ -185,34 +121,14 @@ "severity": "ERROR" }, { - "line": 60, + "line": 59, "column": 31, - "endLine": 60, + "endLine": 59, "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": "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_await_js_promise.ets.autofix.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.autofix.json new file mode 100644 index 0000000000..5254337c77 --- /dev/null +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.autofix.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": 16, + "column": 1, + "endLine": 16, + "endColumn": 89, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 605, + "end": 693, + "replacementText": "", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 89 + }, + { + "start": 693, + "end": 693, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./no_await_js_promise_export');\nlet p = GeneratedImportVar_1.getPropertyByName('p');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet pFuncCall = GeneratedImportVar_1.getPropertyByName('pFuncCall');\nlet arrowFunc = GeneratedImportVar_1.getPropertyByName('arrowFunc');\nlet pArrowCall = GeneratedImportVar_1.getPropertyByName('pArrowCall');\n", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 89 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 10, + "endLine": 19, + "endColumn": 17, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 742, + "end": 743, + "replacementText": "p.toPromise()", + "line": 19, + "column": 10, + "endLine": 19, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 10, + "endLine": 23, + "endColumn": 21, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 800, + "end": 805, + "replacementText": "foo.invoke().toPromise()", + "line": 23, + "column": 10, + "endLine": 23, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 10, + "endLine": 27, + "endColumn": 25, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 860, + "end": 869, + "replacementText": "pFuncCall.toPromise()", + "line": 27, + "column": 10, + "endLine": 27, + "endColumn": 25 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 10, + "endLine": 35, + "endColumn": 26, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 990, + "end": 1000, + "replacementText": "pArrowCall.toPromise()", + "line": 35, + "column": 10, + "endLine": 35, + "endColumn": 26 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 12, + "endLine": 40, + "endColumn": 19, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 1067, + "end": 1068, + "replacementText": "p.toPromise()", + "line": 40, + "column": 12, + "endLine": 40, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 12, + "endLine": 44, + "endColumn": 27, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 1118, + "end": 1127, + "replacementText": "pFuncCall.toPromise()", + "line": 44, + "column": 12, + "endLine": 44, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 20, + "endLine": 48, + "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": 49, + "column": 3, + "endLine": 51, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 12, + "endLine": 50, + "endColumn": 28, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 1197, + "end": 1207, + "replacementText": "pArrowCall.toPromise()", + "line": 50, + "column": 12, + "endLine": 50, + "endColumn": 28 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 12, + "endLine": 54, + "endColumn": 23, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 1262, + "end": 1267, + "replacementText": "foo.invoke().toPromise()", + "line": 54, + "column": 12, + "endLine": 54, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 2, + "endLine": 60, + "endColumn": 2, + "problem": "FunctionExpression", + "autofix": [ + { + "start": 1278, + "end": 1338, + "replacementText": "async () => {\n console.log(\"IIFE result:\", await p);\n}", + "line": 58, + "column": 2, + "endLine": 60, + "endColumn": 2 + } + ], + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 31, + "endLine": 59, + "endColumn": 38, + "problem": "NoAwaitJsPromise", + "autofix": [ + { + "start": 1333, + "end": 1334, + "replacementText": "p.toPromise()", + "line": 59, + "column": 31, + "endLine": 59, + "endColumn": 38 + } + ], + "suggest": "", + "rule": "\"Await\" operator can't be used with interop objects (arkts-interop-js2s-await-js-promise)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/no_await_js_promise.ets.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.json index 5285bc41f6..02889dfd82 100755 --- a/ets2panda/linter/test/interop/no_await_js_promise.ets.json +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.json @@ -15,19 +15,9 @@ ], "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": 49, + "line": 48, "column": 20, - "endLine": 49, + "endLine": 48, "endColumn": 21, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 59, + "line": 58, "column": 2, - "endLine": 61, + "endLine": 60, "endColumn": 2, "problem": "FunctionExpression", "suggest": "", diff --git a/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.ets b/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.ets new file mode 100644 index 0000000000..a89d3e58d3 --- /dev/null +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.ets @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 GeneratedImportVar_1 = ESValue.load('./no_await_js_promise_export'); +let p = GeneratedImportVar_1.getPropertyByName('p'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let pFuncCall = GeneratedImportVar_1.getPropertyByName('pFuncCall'); +let arrowFunc = GeneratedImportVar_1.getPropertyByName('arrowFunc'); +let pArrowCall = GeneratedImportVar_1.getPropertyByName('pArrowCall'); + + +async function awaitPromise() { + return await p.toPromise(); +} + +async function awaitFunctionCall() { + return await foo.invoke().toPromise(); +} + +async function awaitFuncResult() { + return await pFuncCall.toPromise(); +} + +async function awaitArrowCall() { + return await arrowFunc(); +} + +async function awaitArrowResult() { + return await pArrowCall.toPromise(); +} + +class ExampleClass { + async classMethod() { + return await p.toPromise(); + } + + handler = async () => { + return await pFuncCall.toPromise(); + }; +} + +const exampleObj = { + async objMethod() { + return await pArrowCall.toPromise(); + }, + + arrowHandler: async () => { + return await foo.invoke().toPromise(); + } +}; + +(async () => { + 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.migrate.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.json new file mode 100644 index 0000000000..5d4c781348 --- /dev/null +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.json @@ -0,0 +1,188 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 72, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 52, + "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": 68, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 68, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 5, + "endLine": 21, + "endColumn": 70, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 16, + "endLine": 24, + "endColumn": 28, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 16, + "endLine": 28, + "endColumn": 33, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 16, + "endLine": 32, + "endColumn": 31, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 16, + "endLine": 36, + "endColumn": 30, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 16, + "endLine": 40, + "endColumn": 32, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 9, + "endLine": 45, + "endColumn": 20, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 13, + "endLine": 51, + "endColumn": 4, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "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": 55, + "column": 9, + "endLine": 55, + "endColumn": 18, + "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, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets b/ets2panda/linter/test/interop/no_js_instanceof.ets old mode 100755 new mode 100644 index f3e57eeee8..9c7c1b6453 --- a/ets2panda/linter/test/interop/no_js_instanceof.ets +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets @@ -12,7 +12,6 @@ * 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" diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.args.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.args.json index 3ef4496a81..571ee6bb76 100755 --- a/ets2panda/linter/test/interop/no_js_instanceof.ets.args.json +++ b/ets2panda/linter/test/interop/no_js_instanceof.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/no_js_instanceof.ets.arkts2.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json old mode 100755 new mode 100644 index 31d9a91eef..4c2e0aa32a --- a/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.arkts2.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 17, + "line": 16, "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": 17, - "column": 1, - "endLine": 17, + "endLine": 16, "endColumn": 88, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 4, - "endLine": 27, + "endLine": 26, "endColumn": 22, "problem": "InteropJsInstanceof", "suggest": "", @@ -45,9 +35,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 4, - "endLine": 31, + "endLine": 30, "endColumn": 23, "problem": "InteropJsInstanceof", "suggest": "", @@ -55,9 +45,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 34, "column": 4, - "endLine": 35, + "endLine": 34, "endColumn": 23, "problem": "InteropJsInstanceof", "suggest": "", @@ -65,9 +55,9 @@ "severity": "ERROR" }, { - "line": 39, + "line": 38, "column": 28, - "endLine": 39, + "endLine": 38, "endColumn": 50, "problem": "CallJSFunction", "suggest": "", @@ -75,9 +65,9 @@ "severity": "ERROR" }, { - "line": 39, + "line": 38, "column": 47, - "endLine": 39, + "endLine": 38, "endColumn": 49, "problem": "NumericSemantics", "suggest": "", @@ -85,9 +75,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 40, "column": 4, - "endLine": 41, + "endLine": 40, "endColumn": 34, "problem": "InteropJsInstanceof", "suggest": "", @@ -95,9 +85,9 @@ "severity": "ERROR" }, { - "line": 46, + "line": 45, "column": 8, - "endLine": 46, + "endLine": 45, "endColumn": 38, "problem": "InteropJsInstanceof", "suggest": "", @@ -105,9 +95,9 @@ "severity": "ERROR" }, { - "line": 52, + "line": 51, "column": 8, - "endLine": 52, + "endLine": 51, "endColumn": 38, "problem": "InteropJsInstanceof", "suggest": "", @@ -115,9 +105,9 @@ "severity": "ERROR" }, { - "line": 59, + "line": 58, "column": 12, - "endLine": 59, + "endLine": 58, "endColumn": 42, "problem": "InteropJsInstanceof", "suggest": "", @@ -125,9 +115,9 @@ "severity": "ERROR" }, { - "line": 65, + "line": 64, "column": 4, - "endLine": 65, + "endLine": 64, "endColumn": 22, "problem": "InteropJsInstanceof", "suggest": "", @@ -135,9 +125,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 68, "column": 4, - "endLine": 69, + "endLine": 68, "endColumn": 24, "problem": "InteropJsInstanceof", "suggest": "", @@ -145,9 +135,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 68, "column": 4, - "endLine": 69, + "endLine": 68, "endColumn": 7, "problem": "CallJSFunction", "suggest": "", @@ -155,9 +145,9 @@ "severity": "ERROR" }, { - "line": 73, + "line": 72, "column": 36, - "endLine": 73, + "endLine": 72, "endColumn": 51, "problem": "DynamicCtorCall", "suggest": "", @@ -165,9 +155,9 @@ "severity": "ERROR" }, { - "line": 73, + "line": 72, "column": 36, - "endLine": 73, + "endLine": 72, "endColumn": 51, "problem": "InteropObjectProperty", "suggest": "", @@ -175,19 +165,9 @@ "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": 75, + "line": 74, "column": 5, - "endLine": 75, + "endLine": 74, "endColumn": 37, "problem": "InteropJsInstanceof", "suggest": "", @@ -195,9 +175,9 @@ "severity": "ERROR" }, { - "line": 75, + "line": 74, "column": 22, - "endLine": 75, + "endLine": 74, "endColumn": 37, "problem": "InteropObjectProperty", "suggest": "", @@ -205,9 +185,9 @@ "severity": "ERROR" }, { - "line": 75, + "line": 74, "column": 22, - "endLine": 75, + "endLine": 74, "endColumn": 37, "problem": "InteropJsObjectConditionJudgment", "suggest": "", diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.autofix.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.autofix.json new file mode 100644 index 0000000000..8b4189586e --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.autofix.json @@ -0,0 +1,394 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 88, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 605, + "end": 692, + "replacementText": "", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 88 + }, + { + "start": 692, + "end": 692, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./no_js_instanceof_file.js');\nlet Foo = GeneratedImportVar_1.getPropertyByName('Foo');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet CreatePerson = GeneratedImportVar_1.getPropertyByName('CreatePerson');\nlet a = GeneratedImportVar_1.getPropertyByName('a');\nlet b = GeneratedImportVar_1.getPropertyByName('b');\nlet MyNamespace = GeneratedImportVar_1.getPropertyByName('MyNamespace');\n", + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 88 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 4, + "endLine": 26, + "endColumn": 22, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "foo.isInstanceOf(Foo)", + "start": 766, + "end": 784, + "line": 26, + "column": 4, + "endLine": 26, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 4, + "endLine": 30, + "endColumn": 23, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "foo1.isInstanceOf(Foo)", + "start": 799, + "end": 818, + "line": 30, + "column": 4, + "endLine": 30, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 4, + "endLine": 34, + "endColumn": 23, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "foo.isInstanceOf(Foo1)", + "start": 829, + "end": 848, + "line": 34, + "column": 4, + "endLine": 34, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 28, + "endLine": 38, + "endColumn": 50, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 883, + "end": 905, + "replacementText": "CreatePerson.invoke(ESValue.wrap('xc'), ESValue.wrap(18))", + "line": 38, + "column": 28, + "endLine": 38, + "endColumn": 50 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 47, + "endLine": 38, + "endColumn": 49, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 902, + "end": 904, + "replacementText": "18.0", + "line": 38, + "column": 47, + "endLine": 38, + "endColumn": 49 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 4, + "endLine": 40, + "endColumn": 34, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "person.isInstanceOf(CreatePerson)", + "start": 910, + "end": 940, + "line": 40, + "column": 4, + "endLine": 40, + "endColumn": 34 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 8, + "endLine": 45, + "endColumn": 38, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "person.isInstanceOf(CreatePerson)", + "start": 980, + "end": 1010, + "line": 45, + "column": 8, + "endLine": 45, + "endColumn": 38 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 8, + "endLine": 51, + "endColumn": 38, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "person.isInstanceOf(CreatePerson)", + "start": 1059, + "end": 1089, + "line": 51, + "column": 8, + "endLine": 51, + "endColumn": 38 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 12, + "endLine": 58, + "endColumn": 42, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "person.isInstanceOf(CreatePerson)", + "start": 1147, + "end": 1177, + "line": 58, + "column": 12, + "endLine": 58, + "endColumn": 42 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 4, + "endLine": 64, + "endColumn": 22, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "a.isInstanceOf(Array)", + "start": 1204, + "end": 1222, + "line": 64, + "column": 4, + "endLine": 64, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 4, + "endLine": 68, + "endColumn": 24, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "b().isInstanceOf(Array)", + "start": 1233, + "end": 1253, + "line": 68, + "column": 4, + "endLine": 68, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 4, + "endLine": 68, + "endColumn": 7, + "problem": "CallJSFunction", + "autofix": [ + { + "start": 1233, + "end": 1236, + "replacementText": "b.invoke()", + "line": 68, + "column": 4, + "endLine": 68, + "endColumn": 7 + } + ], + "suggest": "", + "rule": "ArkTS directly call JS functions or parameters is not supported (arkts-interop-js2s-call-js-func)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 36, + "endLine": 72, + "endColumn": 51, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 36, + "endLine": 72, + "endColumn": 51, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1296, + "end": 1311, + "replacementText": "MyNamespace.getPropertyByName(\"Dog\")", + "line": 72, + "column": 36, + "endLine": 72, + "endColumn": 51 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 5, + "endLine": 74, + "endColumn": 37, + "problem": "InteropJsInstanceof", + "autofix": [ + { + "replacementText": "myDog.isInstanceOf(MyNamespace.Dog)", + "start": 1327, + "end": 1359, + "line": 74, + "column": 5, + "endLine": 74, + "endColumn": 37 + } + ], + "suggest": "", + "rule": "Usage of \"instanceof\" operator is not allowed with interop objects (arkts-interop-js2s-instanceof-js-type)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 22, + "endLine": 74, + "endColumn": 37, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 1344, + "end": 1359, + "replacementText": "MyNamespace.getPropertyByName(\"Dog\")", + "line": 74, + "column": 22, + "endLine": 74, + "endColumn": 37 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 22, + "endLine": 74, + "endColumn": 37, + "problem": "InteropJsObjectConditionJudgment", + "autofix": [ + { + "replacementText": "MyNamespace.getPropertyByName('Dog')", + "start": 1344, + "end": 1359, + "line": 74, + "column": 22, + "endLine": 74, + "endColumn": 37 + } + ], + "suggest": "", + "rule": "Direct usage of interop JS objects is not supported (arkts-interop-js2s-condition-judgment)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.json index e6955adae6..ca88f857e9 100755 --- a/ets2panda/linter/test/interop/no_js_instanceof.ets.json +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.json @@ -1,29 +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": [ - { - "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" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.ets b/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.ets new file mode 100644 index 0000000000..b71a99dcc0 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_instanceof.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. + */ + +let GeneratedImportVar_1 = ESValue.load('./no_js_instanceof_file.js'); +let Foo = GeneratedImportVar_1.getPropertyByName('Foo'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let CreatePerson = GeneratedImportVar_1.getPropertyByName('CreatePerson'); +let a = GeneratedImportVar_1.getPropertyByName('a'); +let b = GeneratedImportVar_1.getPropertyByName('b'); +let MyNamespace = GeneratedImportVar_1.getPropertyByName('MyNamespace'); + + +class Foo1 {} + +let foo1 = new Foo1() + +if(foo1 instanceof Foo1) { + +} + +if(foo.isInstanceOf(Foo)) { + +} + +if(foo1.isInstanceOf(Foo)) { + +} + +if(foo.isInstanceOf(Foo1)) { + +} + +let person: CreatePerson = CreatePerson.invoke(ESValue.wrap('xc'), ESValue.wrap(18.0)) + +if(person.isInstanceOf(CreatePerson)) { + +} + +function test1(): void { + if(person.isInstanceOf(CreatePerson)) { + + } +} + +const test2 = (): void => { + if(person.isInstanceOf(CreatePerson)) { + + } +} + +class Test3 { + init(): void { + if(person.isInstanceOf(CreatePerson)) { + + } + } +} + +if(a.isInstanceOf(Array)) { + +} + +if(b().isInstanceOf(Array)) { + +} + +const myDog: MyNamespace.Dog = new MyNamespace.getPropertyByName("Dog")('Buddy'); + +if (myDog.isInstanceOf(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.migrate.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.json new file mode 100644 index 0000000000..63aabda702 --- /dev/null +++ b/ets2panda/linter/test/interop/no_js_instanceof.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": 16, + "column": 5, + "endLine": 16, + "endColumn": 70, + "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": 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": 74, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "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": 21, + "column": 5, + "endLine": 21, + "endColumn": 52, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 72, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 19, + "endLine": 71, + "endColumn": 24, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 21, + "endLine": 75, + "endColumn": 26, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 36, + "endLine": 79, + "endColumn": 65, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/interop/object_built_in.ets b/ets2panda/linter/test/interop/object_built_in.ets index 7797930ffd..3170f3f087 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets +++ b/ets2panda/linter/test/interop/object_built_in.ets @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' + import { X } from "./oh_modules/object_built_in" diff --git a/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json b/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json index 07296c65fc..d9cadcd5d4 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json +++ b/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json @@ -14,16 +14,6 @@ "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, @@ -54,6 +44,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 14, + "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": 27, "column": 1, @@ -65,4 +65,4 @@ "severity": "ERROR" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/object_built_in.ets.json b/ets2panda/linter/test/interop/object_built_in.ets.json index 582a700d94..d2adea10e5 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets.json +++ b/ets2panda/linter/test/interop/object_built_in.ets.json @@ -14,16 +14,6 @@ "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": 5, @@ -53,6 +43,16 @@ "suggest": "", "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" + }, + { + "line": 27, + "column": 1, + "endLine": 27, + "endColumn": 14, + "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" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/object_literal_constructor.ets b/ets2panda/linter/test/interop/object_literal_constructor.ets index 7c15e1bf64..c66bdfabca 100644 --- a/ets2panda/linter/test/interop/object_literal_constructor.ets +++ b/ets2panda/linter/test/interop/object_literal_constructor.ets @@ -1,4 +1,3 @@ -'use static' /* * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/ets2panda/linter/test/interop/object_literal_constructor.ets.arkts2.json b/ets2panda/linter/test/interop/object_literal_constructor.ets.arkts2.json index 6a51dd80b2..7fe4087dbb 100644 --- a/ets2panda/linter/test/interop/object_literal_constructor.ets.arkts2.json +++ b/ets2panda/linter/test/interop/object_literal_constructor.ets.arkts2.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 101, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 20, + "line": 19, "column": 18, - "endLine": 20, + "endLine": 19, "endColumn": 27, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 19, "column": 24, - "endLine": 20, + "endLine": 19, "endColumn": 25, "problem": "NumericSemantics", "suggest": "", @@ -45,9 +35,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 23, "column": 22, - "endLine": 24, + "endLine": 23, "endColumn": 51, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -55,9 +45,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 14, - "endLine": 26, + "endLine": 25, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -65,9 +55,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 14, - "endLine": 27, + "endLine": 26, "endColumn": 25, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -75,9 +65,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 16, - "endLine": 27, + "endLine": 26, "endColumn": 23, "problem": "ObjectLiteralProperty", "suggest": "", @@ -85,9 +75,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 16, - "endLine": 27, + "endLine": 26, "endColumn": 23, "problem": "SpreadOperator", "suggest": "", @@ -95,9 +85,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 5, - "endLine": 30, + "endLine": 29, "endColumn": 18, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -105,9 +95,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 35, "column": 12, - "endLine": 36, + "endLine": 35, "endColumn": 29, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -115,9 +105,9 @@ "severity": "ERROR" }, { - "line": 49, + "line": 48, "column": 15, - "endLine": 49, + "endLine": 48, "endColumn": 35, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -125,9 +115,9 @@ "severity": "ERROR" }, { - "line": 57, + "line": 56, "column": 11, - "endLine": 57, + "endLine": 56, "endColumn": 29, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -135,9 +125,9 @@ "severity": "ERROR" }, { - "line": 63, + "line": 62, "column": 30, - "endLine": 63, + "endLine": 62, "endColumn": 48, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -145,9 +135,9 @@ "severity": "ERROR" }, { - "line": 70, + "line": 69, "column": 5, - "endLine": 73, + "endLine": 72, "endColumn": 2, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -155,9 +145,9 @@ "severity": "ERROR" }, { - "line": 72, + "line": 71, "column": 6, - "endLine": 72, + "endLine": 71, "endColumn": 8, "problem": "NumericSemantics", "suggest": "", @@ -165,9 +155,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 78, "column": 5, - "endLine": 79, + "endLine": 78, "endColumn": 24, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -175,9 +165,9 @@ "severity": "ERROR" }, { - "line": 80, + "line": 79, "column": 5, - "endLine": 80, + "endLine": 79, "endColumn": 23, "problem": "InteropObjectLiteralClass", "suggest": "", @@ -185,9 +175,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 78, "column": 21, - "endLine": 79, + "endLine": 78, "endColumn": 22, "problem": "NumericSemantics", "suggest": "", @@ -195,9 +185,9 @@ "severity": "ERROR" }, { - "line": 80, + "line": 79, "column": 20, - "endLine": 80, + "endLine": 79, "endColumn": 21, "problem": "NumericSemantics", "suggest": "", diff --git a/ets2panda/linter/test/interop/object_literal_constructor.ets.json b/ets2panda/linter/test/interop/object_literal_constructor.ets.json index bafc2e9e54..b242a6c5b9 100644 --- a/ets2panda/linter/test/interop/object_literal_constructor.ets.json +++ b/ets2panda/linter/test/interop/object_literal_constructor.ets.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 101, - "problem": "ImportAfterStatement", - "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", - "severity": "ERROR" - }, - { - "line": 26, + "line": 25, "column": 14, - "endLine": 26, + "endLine": 25, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 16, - "endLine": 27, + "endLine": 26, "endColumn": 23, "problem": "SpreadOperator", "suggest": "", diff --git a/ets2panda/linter/test/interop/object_literal_union_type.ets b/ets2panda/linter/test/interop/object_literal_union_type.ets index f57fd51379..2e730940c3 100644 --- a/ets2panda/linter/test/interop/object_literal_union_type.ets +++ b/ets2panda/linter/test/interop/object_literal_union_type.ets @@ -1,4 +1,3 @@ -'use static' /* * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); 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 index 5c02f0cb4d..4b9be812e4 100644 --- a/ets2panda/linter/test/interop/object_literal_union_type.ets.arkts2.json +++ b/ets2panda/linter/test/interop/object_literal_union_type.ets.arkts2.json @@ -15,29 +15,19 @@ ], "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", + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 31, + "problem": "InteropObjectLiteralAmbiguity", "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "rule": "Object literal not compatible with target union type. (arkts-interop-d2s-object-literal-no-ambiguity)", "severity": "ERROR" }, { - "line": 21, + "line": 22, "column": 5, - "endLine": 21, + "endLine": 22, "endColumn": 31, "problem": "InteropObjectLiteralAmbiguity", "suggest": "", @@ -45,20 +35,20 @@ "severity": "ERROR" }, { - "line": 23, + "line": 24, "column": 5, - "endLine": 23, - "endColumn": 31, + "endLine": 24, + "endColumn": 37, "problem": "InteropObjectLiteralAmbiguity", "suggest": "", "rule": "Object literal not compatible with target union type. (arkts-interop-d2s-object-literal-no-ambiguity)", "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 5, - "endLine": 25, - "endColumn": 37, + "endLine": 26, + "endColumn": 34, "problem": "InteropObjectLiteralAmbiguity", "suggest": "", "rule": "Object literal not compatible with target union type. (arkts-interop-d2s-object-literal-no-ambiguity)", diff --git a/ets2panda/linter/test/interop/object_literal_union_type.ets.json b/ets2panda/linter/test/interop/object_literal_union_type.ets.json index 25154ac0c6..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/object_literal_union_type.ets.json +++ b/ets2panda/linter/test/interop/object_literal_union_type.ets.json @@ -13,26 +13,5 @@ "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" - } - ] + "result": [] } \ 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 index dad32c88ba..81c8a334d4 100644 --- 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 @@ -12,7 +12,6 @@ * 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 4fd2894dd8..5bfb75a301 100644 --- a/ets2panda/linter/test/interop/oh_modules/reflect_export.ets +++ b/ets2panda/linter/test/interop/oh_modules/reflect_export.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' export function foo(prx: Object) { Reflect.get(prx, 'a') // 'hello' @@ -28,3 +27,37 @@ export class X { a: string = 'hello' getName() { return this.a } } + +export class Reflect1 { + a: string = 'hello' + getName() { return this.a } +} +export let obj_Reflect1 = new Reflect1(); + +interface Iface { + a:number +} +export let objInter:Iface = {a:1} + +export function reflect_method1(prx: ESObject) { + Reflect.ownKeys(prx) // ['a'] + Reflect.set(prx, 'a', 7) // true + Reflect.get(prx, 'a') // true + Reflect.has(prx, 'a') // true +} + +export function reflect_method1_set(prx: ESObject) { + Reflect.set(prx, 'a', 7) // true +} + +export function reflect_method1_get(prx: ESObject) { + Reflect.get(prx, 'a') // true +} + +export function reflect_method1_ownKeys(prx: ESObject) { + Reflect.ownKeys(prx) // ['a'] +} + +export function reflect_method1_has(prx: ESObject) { + Reflect.has(prx, 'a') // true +} 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 index 2191e01971..540539ec6b 100644 --- a/ets2panda/linter/test/interop/oh_modules/static_object_literals_export.ets +++ b/ets2panda/linter/test/interop/oh_modules/static_object_literals_export.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' export class X { name: string = '' } diff --git a/ets2panda/linter/test/interop/reflect_built_in.ets b/ets2panda/linter/test/interop/reflect_built_in.ets index 96b0800185..90b377fc15 100644 --- a/ets2panda/linter/test/interop/reflect_built_in.ets +++ b/ets2panda/linter/test/interop/reflect_built_in.ets @@ -12,8 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' - import { X } from "./oh_modules/reflect_export" export function foo(prx: Object) { @@ -29,3 +27,34 @@ export function bar(obj: Object) { foo(new X()); //illegal bar(new X()); //illegal + +import {Reflect1} from "./oh_modules/reflect_export" +import {obj_Reflect1} from "./oh_modules/reflect_export" +import {objInter} from "./oh_modules/reflect_export" + +function reflect_method2(prx: Object) { + Reflect.get(prx, 'a') // 'hello' + Reflect.set(prx, 'a', 'world') // true + Reflect.ownKeys(prx) // ['a'] +} + +reflect_method2(new Reflect1()); +Reflect.get(new Reflect1(), 'a') +Reflect.set(new Reflect1(), 'a', 'world') +Reflect.ownKeys(new Reflect1()) +let obj = new Reflect1() +reflect_method2(obj); +Reflect.get(obj, 'a') +Reflect.set(obj, 'a', 'world') +Reflect.ownKeys(obj) + +reflect_method2(obj_Reflect1); +Reflect.get(obj_Reflect1, 'a') +Reflect.set(obj_Reflect1, 'a', 'world') +Reflect.ownKeys(obj_Reflect1) + +reflect_method2(objInter); +Reflect.get(objInter, 'a') +Reflect.set(objInter, 'a', 'world') +Reflect.ownKeys(objInter) + diff --git a/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json b/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json index f16e3c2498..1dd3014588 100644 --- a/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json +++ b/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json @@ -15,13 +15,73 @@ ], "result": [ { - "line": 17, + "line": 18, + "column": 2, + "endLine": 18, + "endColumn": 23, + "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": 19, + "column": 2, + "endLine": 19, + "endColumn": 32, + "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": 20, + "column": 2, + "endLine": 20, + "endColumn": 22, + "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": 24, + "column": 5, + "endLine": 24, + "endColumn": 37, + "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": 27, "column": 1, - "endLine": 17, - "endColumn": 48, - "problem": "ImportAfterStatement", + "endLine": 27, + "endColumn": 14, + "problem": "InteropCallReflect", "suggest": "", - "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "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": 27, + "column": 1, + "endLine": 27, + "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": 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" }, { @@ -38,11 +98,261 @@ "line": 31, "column": 1, "endLine": 31, - "endColumn": 14, + "endColumn": 53, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 57, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 1, + "endLine": 33, + "endColumn": 53, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 5, + "endLine": 36, + "endColumn": 26, + "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": 37, + "column": 5, + "endLine": 37, + "endColumn": 35, + "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": 38, + "column": 5, + "endLine": 38, + "endColumn": 25, + "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": 41, + "column": 1, + "endLine": 41, + "endColumn": 33, + "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": 41, + "column": 1, + "endLine": 41, + "endColumn": 33, + "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": 42, + "column": 1, + "endLine": 42, + "endColumn": 33, + "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": 43, + "column": 1, + "endLine": 43, + "endColumn": 42, + "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": 44, + "column": 1, + "endLine": 44, + "endColumn": 32, + "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": 46, + "column": 1, + "endLine": 46, + "endColumn": 22, + "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": 46, + "column": 1, + "endLine": 46, + "endColumn": 22, + "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": 47, + "column": 1, + "endLine": 47, + "endColumn": 22, + "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": 48, + "column": 1, + "endLine": 48, + "endColumn": 31, + "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": 49, + "column": 1, + "endLine": 49, + "endColumn": 21, + "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": 51, + "column": 1, + "endLine": 51, + "endColumn": 31, + "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": 51, + "column": 1, + "endLine": 51, + "endColumn": 31, + "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": 52, + "column": 1, + "endLine": 52, + "endColumn": 31, + "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": 53, + "column": 1, + "endLine": 53, + "endColumn": 40, + "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": 54, + "column": 1, + "endLine": 54, + "endColumn": 30, + "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": 56, + "column": 1, + "endLine": 56, + "endColumn": 27, + "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": 56, + "column": 1, + "endLine": 56, + "endColumn": 27, + "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": 57, + "column": 1, + "endLine": 57, + "endColumn": 27, + "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": 58, + "column": 1, + "endLine": 58, + "endColumn": 36, + "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": 59, + "column": 1, + "endLine": 59, + "endColumn": 26, "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" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/reflect_built_in.ets.json b/ets2panda/linter/test/interop/reflect_built_in.ets.json index 0ee87e87fb..eb39c3a62e 100644 --- a/ets2panda/linter/test/interop/reflect_built_in.ets.json +++ b/ets2panda/linter/test/interop/reflect_built_in.ets.json @@ -15,14 +15,284 @@ ], "result": [ { - "line": 17, + "line": 18, + "column": 2, + "endLine": 18, + "endColumn": 23, + "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": 19, + "column": 2, + "endLine": 19, + "endColumn": 32, + "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": 20, + "column": 2, + "endLine": 20, + "endColumn": 22, + "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": 24, + "column": 5, + "endLine": 24, + "endColumn": 37, + "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": 27, "column": 1, - "endLine": 17, - "endColumn": 48, + "endLine": 27, + "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": 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": 53, "problem": "ImportAfterStatement", "suggest": "", "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", "severity": "ERROR" + }, + { + "line": 32, + "column": 1, + "endLine": 32, + "endColumn": 57, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 1, + "endLine": 33, + "endColumn": 53, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 5, + "endLine": 36, + "endColumn": 26, + "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": 37, + "column": 5, + "endLine": 37, + "endColumn": 35, + "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": 38, + "column": 5, + "endLine": 38, + "endColumn": 25, + "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": 41, + "column": 1, + "endLine": 41, + "endColumn": 33, + "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": 42, + "column": 1, + "endLine": 42, + "endColumn": 33, + "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": 43, + "column": 1, + "endLine": 43, + "endColumn": 42, + "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": 44, + "column": 1, + "endLine": 44, + "endColumn": 32, + "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": 46, + "column": 1, + "endLine": 46, + "endColumn": 22, + "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": 47, + "column": 1, + "endLine": 47, + "endColumn": 22, + "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": 48, + "column": 1, + "endLine": 48, + "endColumn": 31, + "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": 49, + "column": 1, + "endLine": 49, + "endColumn": 21, + "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": 51, + "column": 1, + "endLine": 51, + "endColumn": 31, + "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": 52, + "column": 1, + "endLine": 52, + "endColumn": 31, + "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": 53, + "column": 1, + "endLine": 53, + "endColumn": 40, + "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": 54, + "column": 1, + "endLine": 54, + "endColumn": 30, + "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": 56, + "column": 1, + "endLine": 56, + "endColumn": 27, + "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": 57, + "column": 1, + "endLine": 57, + "endColumn": 27, + "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": 58, + "column": 1, + "endLine": 58, + "endColumn": 36, + "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": 59, + "column": 1, + "endLine": 59, + "endColumn": 26, + "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" } ] -} +} \ No newline at end of file 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..7eec28c419 --- /dev/null +++ b/ets2panda/linter/test/interop/static_dynamic_import.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 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.arkts2.json b/ets2panda/linter/test/interop/static_dynamic_import.ets.arkts2.json new file mode 100644 index 0000000000..dc7f9e0521 --- /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": 16, + "column": 16, + "endLine": 16, + "endColumn": 62, + "problem": "InteropDynamicImport", + "suggest": "", + "rule": "No support for static dynamic import (arkts-interop-d2s-dynamic-import)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 22, + "endLine": 16, + "endColumn": 62, + "problem": "DynamicImport", + "suggest": "", + "rule": "Dynamic import is not supported(arkts-no-dynamic-import)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 17, + "endLine": 17, + "endColumn": 59, + "problem": "InteropDynamicImportTs", + "suggest": "", + "rule": "No support for static dynamic import (arkts-interop-ts2s-dynamic-import-ts)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 23, + "endLine": 17, + "endColumn": 59, + "problem": "DynamicImport", + "suggest": "", + "rule": "Dynamic import is not supported(arkts-no-dynamic-import)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 58, + "problem": "InteropDynamicImportJs", + "suggest": "", + "rule": "No support for static dynamic import (arkts-interop-js2s-dynamic-import-js)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 22, + "endLine": 18, + "endColumn": 58, + "problem": "DynamicImport", + "suggest": "", + "rule": "Dynamic import is not supported(arkts-no-dynamic-import)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 3, + "endLine": 21, + "endColumn": 44, + "problem": "InteropDynamicImportTs", + "suggest": "", + "rule": "No support for static dynamic import (arkts-interop-ts2s-dynamic-import-ts)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 3, + "endLine": 21, + "endColumn": 39, + "problem": "DynamicImport", + "suggest": "", + "rule": "Dynamic import is not supported(arkts-no-dynamic-import)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/global_this.ets.migrate.json b/ets2panda/linter/test/interop/static_dynamic_import.ets.json similarity index 67% rename from ets2panda/linter/test/main/global_this.ets.migrate.json rename to ets2panda/linter/test/interop/static_dynamic_import.ets.json index cdc3cef837..999000f1d0 100644 --- a/ets2panda/linter/test/main/global_this.ets.migrate.json +++ b/ets2panda/linter/test/interop/static_dynamic_import.ets.json @@ -15,43 +15,43 @@ ], "result": [ { - "line": 19, - "column": 7, - "endLine": 19, - "endColumn": 17, - "problem": "GlobalThisError", + "line": 16, + "column": 5, + "endLine": 16, + "endColumn": 62, + "problem": "AnyType", "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 24, - "column": 17, - "endLine": 24, - "endColumn": 20, + "line": 17, + "column": 5, + "endLine": 17, + "endColumn": 59, "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, + "line": 18, + "column": 5, + "endLine": 18, + "endColumn": 58, "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", + "line": 21, + "column": 46, + "endLine": 21, + "endColumn": 47, + "problem": "AnyType", "suggest": "", - "rule": "\"delete\" operator is not supported (arkts-no-delete)", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/static_object_literals.ets.json b/ets2panda/linter/test/interop/static_object_literals.ets.json index 12d46c0860..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/static_object_literals.ets.json +++ b/ets2panda/linter/test/interop/static_object_literals.ets.json @@ -13,66 +13,5 @@ "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" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets b/ets2panda/linter/test/interop/unary_operation_js_obj.ets similarity index 80% rename from ets2panda/linter/test/main/prop_name_from_value.ets rename to ets2panda/linter/test/interop/unary_operation_js_obj.ets index bdfdc1a80d..a6d66fee06 100644 --- a/ets2panda/linter/test/main/prop_name_from_value.ets +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.ets @@ -12,14 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import {foo} from "./unary_operation_js_obj_js.js" -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 ++foo.num; +-foo.num; +!foo.num; +~foo.num; \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.args.json b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.args.json new file mode 100644 index 0000000000..a89d885810 --- /dev/null +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.args.json @@ -0,0 +1,21 @@ +{ + "copyright": [ + "Copyright (c) 2024-2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT 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/unary_operation_js_obj.ets.arkts2.json b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.arkts2.json new file mode 100644 index 0000000000..13a3e19d15 --- /dev/null +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.arkts2.json @@ -0,0 +1,94 @@ +{ + "result": [ + { + "line": 15, + "column": 1, + "endLine": 15, + "endColumn": 51, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 2, + "endLine": 18, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9, + "problem": "InteropObjectProperty", + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.autofix.json new file mode 100644 index 0000000000..07cb92eb1a --- /dev/null +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.autofix.json @@ -0,0 +1,216 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 1, + "endLine": 15, + "endColumn": 51, + "problem": "InterOpImportJs", + "autofix": [ + { + "start": 604, + "end": 654, + "replacementText": "", + "line": 15, + "column": 1, + "endLine": 15, + "endColumn": 51 + }, + { + "start": 654, + "end": 654, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./unary_operation_js_obj_js.js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", + "line": 15, + "column": 1, + "endLine": 15, + "endColumn": 51 + } + ], + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 657, + "end": 664, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "line": 17, + "column": 1, + "endLine": 17, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 657, + "end": 664, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 667, + "end": 674, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 2, + "endLine": 18, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 667, + "end": 674, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 18, + "column": 2, + "endLine": 18, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 677, + "end": 684, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 677, + "end": 684, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 19, + "column": 2, + "endLine": 19, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9, + "problem": "InteropNoHaveNum", + "autofix": [ + { + "start": 687, + "end": 694, + "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Interop object does not have property num (arkts-interop-js2s-unary-op)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9, + "problem": "InteropObjectProperty", + "autofix": [ + { + "start": 687, + "end": 694, + "replacementText": "foo.getPropertyByName(\"num\")", + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Properties of interop objects can't be accessed directly (arkts-interop-js2s-access-js-prop)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.json b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.json new file mode 100644 index 0000000000..43cb4a27bc --- /dev/null +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.json @@ -0,0 +1,3 @@ +{ + "result": [] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.ets b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.ets new file mode 100644 index 0000000000..5448d6f5f0 --- /dev/null +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.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. + */ +let GeneratedImportVar_1 = ESValue.load('./unary_operation_js_obj_js.js'); +let foo = GeneratedImportVar_1.getPropertyByName('foo'); + + ++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/unary_operation_js_obj.ets.migrate.json b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.json new file mode 100644 index 0000000000..4d448e180c --- /dev/null +++ b/ets2panda/linter/test/interop/unary_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": 15, + "column": 5, + "endLine": 15, + "endColumn": 74, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 5, + "endLine": 16, + "endColumn": 56, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 41, + "problem": "UnaryArithmNotNumber", + "suggest": "", + "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "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" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unary_operation_js_obj_js.js b/ets2panda/linter/test/interop/unary_operation_js_obj_js.js new file mode 100644 index 0000000000..6787c96784 --- /dev/null +++ b/ets2panda/linter/test/interop/unary_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 = {num: 0}; \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unique_types.ets b/ets2panda/linter/test/interop/unique_types.ets index 35f8bae391..da2c034f53 100644 --- a/ets2panda/linter/test/interop/unique_types.ets +++ b/ets2panda/linter/test/interop/unique_types.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' import { objectLiteralType, diff --git a/ets2panda/linter/test/interop/unique_types.ets.arkts2.json b/ets2panda/linter/test/interop/unique_types.ets.arkts2.json index 3c2bcf66a7..b3274fd874 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.arkts2.json +++ b/ets2panda/linter/test/interop/unique_types.ets.arkts2.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 17, + "line": 24, "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": 25, - "column": 1, - "endLine": 25, + "endLine": 24, "endColumn": 23, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 1, - "endLine": 27, + "endLine": 26, "endColumn": 22, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -45,9 +35,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 1, - "endLine": 30, + "endLine": 29, "endColumn": 13, "problem": "InteropTSFunctionInvoke", "suggest": "", @@ -55,9 +45,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 1, - "endLine": 30, + "endLine": 29, "endColumn": 11, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -65,19 +55,9 @@ "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, + "line": 33, "column": 1, - "endLine": 34, + "endLine": 33, "endColumn": 20, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -85,9 +65,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 33, "column": 1, - "endLine": 34, + "endLine": 33, "endColumn": 11, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -95,4 +75,4 @@ "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 5f1b6e40b9..a6deb3a499 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.autofix.json +++ b/ets2panda/linter/test/interop/unique_types.ets.autofix.json @@ -15,29 +15,19 @@ ], "result": [ { - "line": 17, + "line": 24, "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": 25, - "column": 1, - "endLine": 25, + "endLine": 24, "endColumn": 23, "problem": "InteropDirectAccessToTSTypes", "autofix": [ { - "start": 744, - "end": 775, + "start": 731, + "end": 762, "replacementText": "objectLiteralType.setPropertyByName('name',ESValue.wrap(\"test\"))", - "line": 25, + "line": 24, "column": 1, - "endLine": 25, + "endLine": 24, "endColumn": 23 } ], @@ -46,19 +36,19 @@ "severity": "ERROR" }, { - "line": 27, + "line": 26, "column": 1, - "endLine": 27, + "endLine": 26, "endColumn": 22, "problem": "InteropDirectAccessToTSTypes", "autofix": [ { - "start": 777, - "end": 807, + "start": 764, + "end": 794, "replacementText": "intersectionType.setPropertyByName('name',ESValue.wrap(\"test\"))", - "line": 27, + "line": 26, "column": 1, - "endLine": 27, + "endLine": 26, "endColumn": 22 } ], @@ -67,9 +57,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 1, - "endLine": 30, + "endLine": 29, "endColumn": 13, "problem": "InteropTSFunctionInvoke", "suggest": "", @@ -77,9 +67,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 1, - "endLine": 30, + "endLine": 29, "endColumn": 11, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -87,19 +77,9 @@ "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, + "line": 33, "column": 1, - "endLine": 34, + "endLine": 33, "endColumn": 20, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -107,9 +87,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 33, "column": 1, - "endLine": 34, + "endLine": 33, "endColumn": 11, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -117,4 +97,4 @@ "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 3e8e488310..ca88f857e9 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.json +++ b/ets2panda/linter/test/interop/unique_types.ets.json @@ -1,14 +1,17 @@ { - "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" - } - ] + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES 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/unique_types.ets.migrate.ets b/ets2panda/linter/test/interop/unique_types.ets.migrate.ets index 86dd5f4ed0..884003da24 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.migrate.ets +++ b/ets2panda/linter/test/interop/unique_types.ets.migrate.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use static' import { objectLiteralType, diff --git a/ets2panda/linter/test/interop/unique_types.ets.migrate.json b/ets2panda/linter/test/interop/unique_types.ets.migrate.json index 4eb8c2c72d..6e0fbe1a85 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.migrate.json +++ b/ets2panda/linter/test/interop/unique_types.ets.migrate.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 17, + "line": 29, "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, + "endLine": 29, "endColumn": 13, "problem": "InteropTSFunctionInvoke", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 29, "column": 1, - "endLine": 30, + "endLine": 29, "endColumn": 11, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -45,19 +35,9 @@ "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, + "line": 33, "column": 1, - "endLine": 34, + "endLine": 33, "endColumn": 20, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -65,9 +45,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 33, "column": 1, - "endLine": 34, + "endLine": 33, "endColumn": 11, "problem": "InteropDirectAccessToTSTypes", "suggest": "", @@ -75,4 +55,4 @@ "severity": "ERROR" } ] -} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/@ohos.taskpool.ets b/ets2panda/linter/test/main/@ohos.taskpool.ets new file mode 100755 index 0000000000..eef90ba56a --- /dev/null +++ b/ets2panda/linter/test/main/@ohos.taskpool.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. + */ + +export namespace taskpool{ + export function isConcurrent(param:func):boolean { + return true + } + export class Task { + constructor(func: Function, ...args: Object[]){} + setTransferList(transfer?: ArrayBuffer[]): void{} + setCloneList(cloneList: Object[] | ArrayBuffer[]): void{} + } +} +export namespace otherTaskPool{ + export function isConcurrent(param:func):boolean { + return true + } + + export class Task { + constructor(func: Function, ...args: Object[]){} + setTransferList(transfer?: ArrayBuffer[]): void{} + setCloneList(cloneList: Object[] | ArrayBuffer[]): void{} + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/@ohos.taskpool.ets.args.json b/ets2panda/linter/test/main/@ohos.taskpool.ets.args.json new file mode 100755 index 0000000000..0adede204e --- /dev/null +++ b/ets2panda/linter/test/main/@ohos.taskpool.ets.args.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." + ], + "mode": { + } +} diff --git a/ets2panda/linter/test/main/@ohos.taskpool.ets.json b/ets2panda/linter/test/main/@ohos.taskpool.ets.json new file mode 100755 index 0000000000..9f305c86d7 --- /dev/null +++ b/ets2panda/linter/test/main/@ohos.taskpool.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/animatable_extend_decorator_1.ets.arkts2.json b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.arkts2.json index b35596cae2..0ac07a8af8 100644 --- a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.arkts2.json @@ -91,7 +91,7 @@ "endColumn": 18, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AnimatableExtend\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 50, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Curve\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -161,7 +161,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 4a99d7ea8c..bedac192c9 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 @@ -179,7 +179,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AnimatableExtend\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -200,7 +200,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -242,7 +242,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -263,7 +263,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -284,7 +284,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -305,7 +305,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Curve\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -326,7 +326,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/arkts-array-type-immutable.ets b/ets2panda/linter/test/main/arkts-array-type-immutable.ets index 75a02116dd..c0d79ba065 100644 --- a/ets2panda/linter/test/main/arkts-array-type-immutable.ets +++ b/ets2panda/linter/test/main/arkts-array-type-immutable.ets @@ -34,4 +34,123 @@ 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 +} + +let arrayTypeImmutableA2: [number] = [1]; +let arrayTypeImmutableB2: [number | string] = arrayTypeImmutableA2; + +class ArrayTypeImmutableA{ + arrayTypeImmutableA: number[] = [1]; + arrayTypeImmutableB: (number | string)[] = this.arrayTypeImmutableA; // error + arrayTypeImmutableB1: (number | string)[] = this.arrayTypeImmutableA; // error + + arrayTypeImmutableA2: [number] = [1]; + arrayTypeImmutableB2: [number | string] = arrayTypeImmutableA2; + arrayTypeImmutableB21: [number | string] = this.arrayTypeImmutableA2; +} + +interface IA { + ia: string; +} + +type TA = string | IA + +interface IB { + i: TA|TA[] +} + +class CA { + static fun(...a: IB[]): void{}; +} + +CA.fun({ + i: [ { ia: '1'}, { ia: '2'}, { ia: '3'}, ] as IA[] // error +} as IB) + + +class A { + a: number[] = [-11,0]; + arrayData: (number| string| boolean)[] = [1, 'hi'] + arrs: (number| boolean)[] = new A().a //error + val: (number|string|boolean) [] = new A().arrayData + A() { + const val1 = new A().a + let array2: (string | number | boolean)[] = val1 //error + } + aa(ss:(number| boolean)[]) { + ss = this.a //error + } + cc(): (boolean| number)[] { + return [true, 33]; + } + dd(): (boolean| string| A)[] { + return [true, 'hello', new A()]; + } + ee() { + let ccVal: (boolean | number | boolean)[] = this.cc() + return ccVal; + } + + ff() { + let array: (number| boolean|string)[] = newArr; //error + return array; + } + gg() { + return this.arrs; + } +} + +function test2():(string|number|boolean)[] { + return ['s', 3.14, true]; +} +function test3() { + let obj: A = new A() + return obj.dd(); +} + +let objA: A = new A() + +const newArr: (number| boolean)[] = [1, true] +const newArr1: (number|string|boolean)[] = [1, '3.14', true] +const array: (number | boolean|string)[] = newArr1 +const newArr2: (string|number|boolean)[] = ['s', 3.14, false] +const array1: (number | string | boolean)[] = newArr2 +const array2: (string | number | boolean)[] = newArr1 + +let tt: (boolean | number | boolean)[] = this.test2() //error +let gg: (boolean | number | boolean)[] = new A().ee() +let ff = new A().ff() +let hh: (boolean | number | string)[] =ff +let mm: (boolean | number | boolean)[] = objA.gg(); +let test: (boolean | A | string)[] = test3() + +let array13: (number|boolean|string)[] = newArr as (number|string)[] //error +let array14: (number|boolean|number)[] = [3.14, true] as (number|boolean)[] +let array15: (boolean|number)[] = array as (number|boolean)[] //error +let array16: (boolean | number | boolean)[] = objA.gg() as (boolean | number)[] +let tuple15: (number|boolean|string)[] = this.test2() as (string|number|boolean)[] +let tuple16: (number|boolean)[] = array as [number, number, boolean] +let array17: (number|string|boolean)[] = ['s', 3.14, true] as (number|string|boolean)[] +const array18 = Array.from({ length: 5 }, (_, index) => index % 2 === 0 ? index : index % 3 === 0); +let array19: (number|boolean)[] = array18 as (number)[] //error +const originalArray: number[] = [1, 2, 3, 4, 5]; +const array20 = originalArray.map((value) => value % 2 === 0 ? true : value * 2); +let array21: [number, boolean] = array20 as [number, boolean] +let array22: (number|string)[] = array20 as (number)[] //error +const array23: (number)[] = [1, 2, 3, 4, 5]; + +let aaa: number[] = [1] +let bbb: (number | string)[] = aaa //error +const fn29: Function[] = []; +function bar(): T[] { + return []; +} +let a: number[] = []; +let repairableArr: Array = new Array(); +repairableArr = new Array(3); +Reflect.apply(() => {}, objA, []); +if (handler.apply) handler.apply(objA, objA, []); + +let readonlyArr: ReadonlyArray = []; +let arr66 = new Array(); +readonlyArr = arr66; //error \ 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 index 50fb25efbd..fa6b50ae6c 100644 --- a/ets2panda/linter/test/main/arkts-array-type-immutable.ets.arkts2.json +++ b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.arkts2.json @@ -123,6 +123,586 @@ "suggest": "", "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", "severity": "ERROR" + }, + { + "line": 39, + "column": 39, + "endLine": 39, + "endColumn": 40, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 36, + "endLine": 43, + "endColumn": 37, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 3, + "endLine": 44, + "endColumn": 71, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 3, + "endLine": 45, + "endColumn": 72, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 37, + "endLine": 47, + "endColumn": 38, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 6, + "endLine": 67, + "endColumn": 63, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 19, + "endLine": 72, + "endColumn": 21, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 22, + "endLine": 72, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 45, + "endLine": 73, + "endColumn": 46, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 3, + "endLine": 74, + "endColumn": 40, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 9, + "endLine": 78, + "endColumn": 53, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 5, + "endLine": 81, + "endColumn": 16, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 19, + "endLine": 84, + "endColumn": 21, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 9, + "endLine": 95, + "endColumn": 51, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 10, + "endLine": 106, + "endColumn": 15, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 38, + "endLine": 113, + "endColumn": 39, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 45, + "endLine": 114, + "endColumn": 46, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 5, + "endLine": 120, + "endColumn": 54, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 122, + "column": 5, + "endLine": 122, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 5, + "endLine": 127, + "endColumn": 69, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 42, + "endLine": 127, + "endColumn": 69, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 129, + "column": 35, + "endLine": 129, + "endColumn": 62, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 5, + "endLine": 132, + "endColumn": 70, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 36, + "endLine": 132, + "endColumn": 70, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 17, + "endLine": 134, + "endColumn": 99, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 38, + "endLine": 134, + "endColumn": 39, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 44, + "endLine": 134, + "endColumn": 45, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 65, + "endLine": 134, + "endColumn": 66, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 71, + "endLine": 134, + "endColumn": 72, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 91, + "endLine": 134, + "endColumn": 92, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 97, + "endLine": 134, + "endColumn": 98, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 135, + "column": 5, + "endLine": 135, + "endColumn": 56, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 135, + "column": 35, + "endLine": 135, + "endColumn": 56, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 34, + "endLine": 136, + "endColumn": 35, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 37, + "endLine": 136, + "endColumn": 38, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 40, + "endLine": 136, + "endColumn": 41, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 43, + "endLine": 136, + "endColumn": 44, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 46, + "endLine": 136, + "endColumn": 47, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 137, + "column": 54, + "endLine": 137, + "endColumn": 55, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 137, + "column": 60, + "endLine": 137, + "endColumn": 61, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 137, + "column": 79, + "endLine": 137, + "endColumn": 80, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 34, + "endLine": 138, + "endColumn": 62, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 5, + "endLine": 139, + "endColumn": 55, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 34, + "endLine": 139, + "endColumn": 55, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 30, + "endLine": 140, + "endColumn": 31, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 33, + "endLine": 140, + "endColumn": 34, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 36, + "endLine": 140, + "endColumn": 37, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 39, + "endLine": 140, + "endColumn": 40, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 42, + "endLine": 140, + "endColumn": 43, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 22, + "endLine": 142, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 5, + "endLine": 143, + "endColumn": 35, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 36, + "endLine": 149, + "endColumn": 47, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 17, + "endLine": 150, + "endColumn": 29, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 27, + "endLine": 150, + "endColumn": 28, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 1, + "endLine": 151, + "endColumn": 54, + "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": 151, + "column": 9, + "endLine": 151, + "endColumn": 14, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 5, + "endLine": 155, + "endColumn": 32, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 156, + "column": 1, + "endLine": 156, + "endColumn": 20, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/arkts-array-type-immutable.ets.json b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.json index ca88f857e9..d8f6775c62 100644 --- a/ets2panda/linter/test/main/arkts-array-type-immutable.ets.json +++ b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.json @@ -13,5 +13,66 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 106, + "column": 10, + "endLine": 106, + "endColumn": 15, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 122, + "column": 5, + "endLine": 122, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 17, + "endLine": 134, + "endColumn": 99, + "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": 45, + "problem": "UnknownType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 1, + "endLine": 151, + "endColumn": 53, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 151, + "column": 1, + "endLine": 151, + "endColumn": 54, + "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" + } + ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/arktsutils_module.ets b/ets2panda/linter/test/main/arktsutils_module.ets index 4e81dea82b..a8fbe4b65e 100644 --- a/ets2panda/linter/test/main/arktsutils_module.ets +++ b/ets2panda/linter/test/main/arktsutils_module.ets @@ -35,4 +35,6 @@ function tesCollectionsUsage() { type CreatedType = ArkTSUtils.ASON.SomeType; const someType: CreatedType = ArkTSUtils.ASON.SomeType; + + const map: number = ArkTSUtils.ASON.ParseReturnType.map; } diff --git a/ets2panda/linter/test/main/arktsutils_module.ets.arkts2.json b/ets2panda/linter/test/main/arktsutils_module.ets.arkts2.json index 6da6e6ae15..30c0ecdc72 100644 --- a/ets2panda/linter/test/main/arktsutils_module.ets.arkts2.json +++ b/ets2panda/linter/test/main/arktsutils_module.ets.arkts2.json @@ -113,6 +113,16 @@ "suggest": "", "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", "severity": "ERROR" + }, + { + "line": 39, + "column": 23, + "endLine": 39, + "endColumn": 33, + "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 index d6868a9cbf..bb4f5f6610 100644 --- a/ets2panda/linter/test/main/arktsutils_module.ets.autofix.json +++ b/ets2panda/linter/test/main/arktsutils_module.ets.autofix.json @@ -20,6 +20,17 @@ "endLine": 27, "endColumn": 31, "problem": "LimitedStdLibNoASON", + "autofix": [ + { + "start": 980, + "end": 990, + "replacementText": "JSON", + "line": 27, + "column": 26, + "endLine": 27, + "endColumn": 31 + } + ], "suggest": "", "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", "severity": "ERROR" @@ -51,6 +62,17 @@ "endLine": 29, "endColumn": 33, "problem": "LimitedStdLibNoASON", + "autofix": [ + { + "start": 1023, + "end": 1043, + "replacementText": "JSON", + "line": 29, + "column": 18, + "endLine": 29, + "endColumn": 33 + } + ], "suggest": "", "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", "severity": "ERROR" @@ -82,6 +104,17 @@ "endLine": 31, "endColumn": 31, "problem": "LimitedStdLibNoASON", + "autofix": [ + { + "start": 1076, + "end": 1094, + "replacementText": "JSON", + "line": 31, + "column": 18, + "endLine": 31, + "endColumn": 31 + } + ], "suggest": "", "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", "severity": "ERROR" @@ -113,6 +146,17 @@ "endLine": 33, "endColumn": 41, "problem": "LimitedStdLibNoASON", + "autofix": [ + { + "start": 1135, + "end": 1155, + "replacementText": "JSON", + "line": 33, + "column": 26, + "endLine": 33, + "endColumn": 41 + } + ], "suggest": "", "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", "severity": "ERROR" @@ -157,6 +201,16 @@ "suggest": "", "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", "severity": "ERROR" + }, + { + "line": 39, + "column": 23, + "endLine": 39, + "endColumn": 33, + "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.migrate.ets b/ets2panda/linter/test/main/arktsutils_module.ets.migrate.ets index 3b1d7e17b6..5dc1d2c5c2 100644 --- a/ets2panda/linter/test/main/arktsutils_module.ets.migrate.ets +++ b/ets2panda/linter/test/main/arktsutils_module.ets.migrate.ets @@ -24,15 +24,17 @@ export { utils } from './oh_modules/@arkts.utils'; function tesCollectionsUsage() { - const utils1: string = utils.ASON.stringify(1.0); + const utils1: string = JSON.stringify(1.0); - const utils2 = ArkTSUtilsAlias.ASON.stringify(1.0); + const utils2 = JSON.stringify(1.0); - const utils3 = kitArkTSUtils.ASON.stringify(1.0); + const utils3 = JSON.stringify(1.0); - const utils4: string = ArkTSUtilsAlias.ASON.stringify(1.0); + const utils4: string = JSON.stringify(1.0); type CreatedType = ArkTSUtils.ASON.SomeType; const someType: CreatedType = ArkTSUtils.ASON.SomeType; + + const map: number = ArkTSUtils.ASON.ParseReturnType.map; } diff --git a/ets2panda/linter/test/main/arktsutils_module.ets.migrate.json b/ets2panda/linter/test/main/arktsutils_module.ets.migrate.json index 1b597eff5b..a3e735670a 100644 --- a/ets2panda/linter/test/main/arktsutils_module.ets.migrate.json +++ b/ets2panda/linter/test/main/arktsutils_module.ets.migrate.json @@ -14,46 +14,6 @@ "limitations under the License." ], "result": [ - { - "line": 27, - "column": 26, - "endLine": 27, - "endColumn": 31, - "problem": "LimitedStdLibNoASON", - "suggest": "", - "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", - "severity": "ERROR" - }, - { - "line": 29, - "column": 18, - "endLine": 29, - "endColumn": 33, - "problem": "LimitedStdLibNoASON", - "suggest": "", - "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", - "severity": "ERROR" - }, - { - "line": 31, - "column": 18, - "endLine": 31, - "endColumn": 31, - "problem": "LimitedStdLibNoASON", - "suggest": "", - "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", - "severity": "ERROR" - }, - { - "line": 33, - "column": 26, - "endLine": 33, - "endColumn": 41, - "problem": "LimitedStdLibNoASON", - "suggest": "", - "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", - "severity": "ERROR" - }, { "line": 35, "column": 22, @@ -73,6 +33,16 @@ "suggest": "", "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", "severity": "ERROR" + }, + { + "line": 39, + "column": 23, + "endLine": 39, + "endColumn": 33, + "problem": "LimitedStdLibNoASON", + "suggest": "", + "rule": "ASON is not supported. (arkts-no-need-stdlib-ason)", + "severity": "ERROR" } ] } diff --git a/ets2panda/linter/test/main/array_index_expr_type.ets b/ets2panda/linter/test/main/array_index_expr_type.ets index fe370c16cd..a2120f59ea 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets +++ b/ets2panda/linter/test/main/array_index_expr_type.ets @@ -83,3 +83,7 @@ arr[a] = 1; arr[b] = 1; arr[c] = 1; arr[d] = 1; + +let test = 1; +arr[1 as number]; +arr[test as number]; \ 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 40493eb175..27fa37360d 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 @@ -1,18 +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." - ], + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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, @@ -64,6 +64,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 18, + "column": 11, + "endLine": 18, + "endColumn": 26, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 18, "column": 20, @@ -84,6 +94,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 19, + "column": 12, + "endLine": 19, + "endColumn": 31, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 19, "column": 21, @@ -104,6 +124,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 20, + "column": 12, + "endLine": 20, + "endColumn": 33, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 20, "column": 21, @@ -124,6 +154,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 21, + "column": 11, + "endLine": 21, + "endColumn": 25, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 21, "column": 20, @@ -244,6 +284,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 27, + "column": 11, + "endLine": 27, + "endColumn": 24, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 27, "column": 20, @@ -264,6 +314,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 28, + "column": 11, + "endLine": 28, + "endColumn": 25, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 28, "column": 20, @@ -284,6 +344,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 29, + "column": 11, + "endLine": 29, + "endColumn": 22, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 30, "column": 7, @@ -294,6 +364,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 37, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 30, "column": 20, @@ -314,6 +394,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 31, + "column": 11, + "endLine": 31, + "endColumn": 37, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 31, "column": 20, @@ -334,6 +424,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 32, + "column": 11, + "endLine": 32, + "endColumn": 44, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 32, "column": 20, @@ -394,6 +494,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 39, + "column": 1, + "endLine": 39, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 39, "column": 7, @@ -404,6 +514,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 40, + "column": 1, + "endLine": 40, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 40, "column": 7, @@ -414,6 +534,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 41, + "column": 1, + "endLine": 41, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 41, "column": 7, @@ -434,6 +564,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 45, + "column": 1, + "endLine": 45, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 45, "column": 7, @@ -494,6 +634,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 51, + "column": 1, + "endLine": 51, + "endColumn": 19, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 51, "column": 8, @@ -614,6 +764,26 @@ "rule": "Enumeration members can be initialized only with compile time expressions of the same type (arkts-no-enum-mixed-types)", "severity": "ERROR" }, + { + "line": 65, + "column": 8, + "endLine": 65, + "endColumn": 9, + "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": 67, "column": 6, @@ -624,6 +794,46 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 68, + "column": 1, + "endLine": 68, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 1, + "endLine": 69, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 72, "column": 1, @@ -634,11 +844,31 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 73, "column": 6, "endLine": 73, - "endColumn": 9, + "endColumn": 19, "problem": "ArrayIndexExprType", "suggest": "", "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", @@ -714,6 +944,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 18, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 81, "column": 5, @@ -763,6 +1003,66 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 87, + "column": 5, + "endLine": 87, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 12, + "endLine": 87, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 1, + "endLine": 88, + "endColumn": 17, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 5, + "endLine": 88, + "endColumn": 16, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 1, + "endLine": 89, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 5, + "endLine": 89, + "endColumn": 19, + "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 index ec4168139c..a65d5f7162 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets.autofix.json +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.autofix.json @@ -1,18 +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." - ], + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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, @@ -119,6 +119,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 18, + "column": 11, + "endLine": 18, + "endColumn": 26, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 18, "column": 20, @@ -161,6 +171,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 19, + "column": 12, + "endLine": 19, + "endColumn": 31, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 19, "column": 21, @@ -203,6 +223,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 20, + "column": 12, + "endLine": 20, + "endColumn": 33, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 20, "column": 21, @@ -245,6 +275,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 21, + "column": 11, + "endLine": 21, + "endColumn": 25, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 21, "column": 20, @@ -398,6 +438,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 27, + "column": 11, + "endLine": 27, + "endColumn": 24, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 27, "column": 20, @@ -440,6 +490,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 28, + "column": 11, + "endLine": 28, + "endColumn": 25, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 28, "column": 20, @@ -482,6 +542,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 29, + "column": 11, + "endLine": 29, + "endColumn": 22, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 30, "column": 7, @@ -503,6 +573,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 37, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 30, "column": 20, @@ -545,6 +625,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 31, + "column": 11, + "endLine": 31, + "endColumn": 37, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 31, "column": 20, @@ -587,6 +677,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 32, + "column": 11, + "endLine": 32, + "endColumn": 44, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 32, "column": 20, @@ -713,6 +813,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 39, + "column": 1, + "endLine": 39, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 39, "column": 7, @@ -734,6 +844,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 40, + "column": 1, + "endLine": 40, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 40, "column": 7, @@ -755,6 +875,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 41, + "column": 1, + "endLine": 41, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 41, "column": 7, @@ -797,6 +927,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 45, + "column": 1, + "endLine": 45, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 45, "column": 7, @@ -923,6 +1063,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 51, + "column": 1, + "endLine": 51, + "endColumn": 19, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 51, "column": 8, @@ -1164,6 +1314,37 @@ "rule": "Enumeration members can be initialized only with compile time expressions of the same type (arkts-no-enum-mixed-types)", "severity": "ERROR" }, + { + "line": 65, + "column": 8, + "endLine": 65, + "endColumn": 9, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1669, + "end": 1670, + "replacementText": "0.0", + "line": 65, + "column": 8, + "endLine": 65, + "endColumn": 9 + } + ], + "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": 67, "column": 6, @@ -1185,6 +1366,46 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 68, + "column": 1, + "endLine": 68, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 1, + "endLine": 69, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 72, "column": 1, @@ -1195,11 +1416,31 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 73, "column": 6, "endLine": 73, - "endColumn": 9, + "endColumn": 19, "problem": "ArrayIndexExprType", "autofix": [ { @@ -1209,7 +1450,7 @@ "line": 73, "column": 6, "endLine": 73, - "endColumn": 9 + "endColumn": 19 } ], "suggest": "", @@ -1363,6 +1604,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 18, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 81, "column": 5, @@ -1456,6 +1707,110 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 87, + "column": 5, + "endLine": 87, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1924, + "end": 1932, + "replacementText": "test: number = 1", + "line": 87, + "column": 5, + "endLine": 87, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 12, + "endLine": 87, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1931, + "end": 1932, + "replacementText": "1.0", + "line": 87, + "column": 12, + "endLine": 87, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 1, + "endLine": 88, + "endColumn": 17, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 5, + "endLine": 88, + "endColumn": 16, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1938, + "end": 1949, + "replacementText": "1 as int", + "line": 88, + "column": 5, + "endLine": 88, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 1, + "endLine": 89, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 5, + "endLine": 89, + "endColumn": 19, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 1956, + "end": 1970, + "replacementText": "test as int", + "line": 89, + "column": 5, + "endLine": 89, + "endColumn": 19 + } + ], + "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.migrate.ets b/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.ets index 5ba7613e1b..eb9ab9c696 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.ets +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.ets @@ -62,7 +62,7 @@ for (let i: int = 0.0; i < array2.length; i++) { let arr1:number[] = [1.0, 2.0, 3.0] enum TE{ AA = 1.12 - BB = 0 + BB = 0.0 } arr1[TE.AA as int]; arr1[TE.BB]; @@ -83,3 +83,7 @@ arr[a] = 1.0; arr[b] = 1.0; arr[c] = 1.0; arr[d] = 1.0; + +let test: number = 1.0; +arr[1 as int]; +arr[test as int]; \ No newline at end of file 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 index 8407a76e0f..457bd6501c 100644 --- a/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.json +++ b/ets2panda/linter/test/main/array_index_expr_type.ets.migrate.json @@ -104,6 +104,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 29, + "column": 19, + "endLine": 29, + "endColumn": 30, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 64, "column": 3, @@ -114,6 +124,46 @@ "rule": "Enumeration members can be initialized only with compile time expressions of the same type (arkts-no-enum-mixed-types)", "severity": "ERROR" }, + { + "line": 68, + "column": 1, + "endLine": 68, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 1, + "endLine": 69, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 72, "column": 1, @@ -124,6 +174,26 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 18, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 81, "column": 5, diff --git a/ets2panda/linter/test/main/class_as_object.ets b/ets2panda/linter/test/main/class_as_object.ets index fcc5a36250..a2bdc36a95 100644 --- a/ets2panda/linter/test/main/class_as_object.ets +++ b/ets2panda/linter/test/main/class_as_object.ets @@ -203,4 +203,13 @@ function parse(type: "number" | "boolean", value: string): number | boolean { } function format(input: string | number): string[] | number[] { return typeof input === "string" ? input.split("") : input.toString().split("").map(Number); -} \ No newline at end of file +} + +let version: string = "1.2" +let a1 = version.split('.').map(Number); + +let version2: string = "1.2" +let a2 = version2.split('.').map(String); + +let version3: string = "1.2" +let a3 = version3.split('.').map(Boolean); \ 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 3bf41adaeb..461137acca 100644 --- a/ets2panda/linter/test/main/class_as_object.ets.arkts2.json +++ b/ets2panda/linter/test/main/class_as_object.ets.arkts2.json @@ -334,6 +334,26 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 102, + "column": 13, + "endLine": 102, + "endColumn": 23, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 18, + "endLine": 114, + "endColumn": 25, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 116, "column": 10, @@ -394,36 +414,6 @@ "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", "severity": "ERROR" }, - { - "line": 129, - "column": 15, - "endLine": 129, - "endColumn": 21, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, - { - "line": 130, - "column": 15, - "endLine": 130, - "endColumn": 22, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, - { - "line": 131, - "column": 15, - "endLine": 131, - "endColumn": 21, - "problem": "ClassAsObjectError", - "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", - "severity": "ERROR" - }, { "line": 132, "column": 15, @@ -905,13 +895,13 @@ "severity": "ERROR" }, { - "line": 205, - "column": 87, - "endLine": 205, - "endColumn": 93, - "problem": "ClassAsObjectError", + "line": 209, + "column": 5, + "endLine": 209, + "endColumn": 40, + "problem": "NumericSemantics", "suggest": "", - "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/class_as_object.ets.json b/ets2panda/linter/test/main/class_as_object.ets.json index cb35d61776..5bfa876a0a 100644 --- a/ets2panda/linter/test/main/class_as_object.ets.json +++ b/ets2panda/linter/test/main/class_as_object.ets.json @@ -212,36 +212,6 @@ "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, @@ -661,16 +631,6 @@ "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/class_no_constructor.ets b/ets2panda/linter/test/main/class_no_constructor.ets index c13aa9b54a..deb0598bc5 100644 --- a/ets2panda/linter/test/main/class_no_constructor.ets +++ b/ets2panda/linter/test/main/class_no_constructor.ets @@ -17,3 +17,13 @@ class A {} const variable = new A().constructor + +let a = new A() +console.log(a.constructor + ""); + +function foo3(): A { + return new A(); +} +console.log(foo3().constructor + ""); + +console.log(A.constructor + ""); \ No newline at end of file diff --git a/ets2panda/linter/test/main/class_no_constructor.ets.arkts2.json b/ets2panda/linter/test/main/class_no_constructor.ets.arkts2.json index 12f07f6aef..940e32b5f0 100644 --- a/ets2panda/linter/test/main/class_no_constructor.ets.arkts2.json +++ b/ets2panda/linter/test/main/class_no_constructor.ets.arkts2.json @@ -21,7 +21,37 @@ "endColumn": 37, "problem": "NoConstructorOnClass", "suggest": "", - "rule": "The Class object does not have a constructor. (arkts-no-arkts-constructor)", + "rule": "Objects have no constructor property in ArkTS1.2 (arkts-obj-no-constructor)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 13, + "endLine": 22, + "endColumn": 26, + "problem": "NoConstructorOnClass", + "suggest": "", + "rule": "Objects have no constructor property in ArkTS1.2 (arkts-obj-no-constructor)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 13, + "endLine": 27, + "endColumn": 31, + "problem": "NoConstructorOnClass", + "suggest": "", + "rule": "Objects have no constructor property in ArkTS1.2 (arkts-obj-no-constructor)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 13, + "endLine": 29, + "endColumn": 26, + "problem": "NoConstructorOnClass", + "suggest": "", + "rule": "Objects have no constructor property in ArkTS1.2 (arkts-obj-no-constructor)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/class_no_constructor.ets.migrate.ets b/ets2panda/linter/test/main/class_no_constructor.ets.migrate.ets index c13aa9b54a..deb0598bc5 100644 --- a/ets2panda/linter/test/main/class_no_constructor.ets.migrate.ets +++ b/ets2panda/linter/test/main/class_no_constructor.ets.migrate.ets @@ -17,3 +17,13 @@ class A {} const variable = new A().constructor + +let a = new A() +console.log(a.constructor + ""); + +function foo3(): A { + return new A(); +} +console.log(foo3().constructor + ""); + +console.log(A.constructor + ""); \ No newline at end of file diff --git a/ets2panda/linter/test/main/class_no_constructor.ets.migrate.json b/ets2panda/linter/test/main/class_no_constructor.ets.migrate.json index 12f07f6aef..940e32b5f0 100644 --- a/ets2panda/linter/test/main/class_no_constructor.ets.migrate.json +++ b/ets2panda/linter/test/main/class_no_constructor.ets.migrate.json @@ -21,7 +21,37 @@ "endColumn": 37, "problem": "NoConstructorOnClass", "suggest": "", - "rule": "The Class object does not have a constructor. (arkts-no-arkts-constructor)", + "rule": "Objects have no constructor property in ArkTS1.2 (arkts-obj-no-constructor)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 13, + "endLine": 22, + "endColumn": 26, + "problem": "NoConstructorOnClass", + "suggest": "", + "rule": "Objects have no constructor property in ArkTS1.2 (arkts-obj-no-constructor)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 13, + "endLine": 27, + "endColumn": 31, + "problem": "NoConstructorOnClass", + "suggest": "", + "rule": "Objects have no constructor property in ArkTS1.2 (arkts-obj-no-constructor)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 13, + "endLine": 29, + "endColumn": 26, + "problem": "NoConstructorOnClass", + "suggest": "", + "rule": "Objects have no constructor property in ArkTS1.2 (arkts-obj-no-constructor)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/class_static_init.ets.arkts2.json b/ets2panda/linter/test/main/class_static_init.ets.arkts2.json old mode 100755 new mode 100644 index 17db245900..da2a0d8e4b --- a/ets2panda/linter/test/main/class_static_init.ets.arkts2.json +++ b/ets2panda/linter/test/main/class_static_init.ets.arkts2.json @@ -501,7 +501,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -511,7 +511,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -521,7 +521,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -531,7 +531,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/main/comment_test.ets b/ets2panda/linter/test/main/comment_test.ets new file mode 100644 index 0000000000..3731be6780 --- /dev/null +++ b/ets2panda/linter/test/main/comment_test.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 TestClass { + /** + * This is a comment. + */ + property = 123; // This is a comment. + // This is a comment. + arr = [1, 0]; // This is a comment. +} diff --git a/ets2panda/linter/test/main/comment_test.ets.args.json b/ets2panda/linter/test/main/comment_test.ets.args.json new file mode 100644 index 0000000000..ef3938e967 --- /dev/null +++ b/ets2panda/linter/test/main/comment_test.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/comment_test.ets.arkts2.json b/ets2panda/linter/test/main/comment_test.ets.arkts2.json new file mode 100644 index 0000000000..76f0d20523 --- /dev/null +++ b/ets2panda/linter/test/main/comment_test.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": 20, + "column": 5, + "endLine": 20, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 16, + "endLine": 20, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 12, + "endLine": 22, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 15, + "endLine": 22, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/comment_test.ets.autofix.json b/ets2panda/linter/test/main/comment_test.ets.autofix.json new file mode 100644 index 0000000000..e1951adff8 --- /dev/null +++ b/ets2panda/linter/test/main/comment_test.ets.autofix.json @@ -0,0 +1,123 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 669, + "end": 684, + "replacementText": "property: number = 123;", + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 16, + "endLine": 20, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 680, + "end": 683, + "replacementText": "123.0", + "line": 20, + "column": 16, + "endLine": 20, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 737, + "end": 750, + "replacementText": "arr: number[] = [1, 0];", + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 12, + "endLine": 22, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 744, + "end": 745, + "replacementText": "1.0", + "line": 22, + "column": 12, + "endLine": 22, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 15, + "endLine": 22, + "endColumn": 16, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 747, + "end": 748, + "replacementText": "0.0", + "line": 22, + "column": 15, + "endLine": 22, + "endColumn": 16 + } + ], + "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/main/debugger_statememt.ets.migrate.json b/ets2panda/linter/test/main/comment_test.ets.json similarity index 100% rename from ets2panda/linter/test/main/debugger_statememt.ets.migrate.json rename to ets2panda/linter/test/main/comment_test.ets.json diff --git a/ets2panda/linter/test/main/comment_test.ets.migrate.ets b/ets2panda/linter/test/main/comment_test.ets.migrate.ets new file mode 100644 index 0000000000..2131000bfa --- /dev/null +++ b/ets2panda/linter/test/main/comment_test.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. + */ + +class TestClass { + /** + * This is a comment. + */ + property: number = 123.0; // This is a comment. + // This is a comment. + arr: number[] = [1.0, 0.0]; // This is a comment. +} diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json b/ets2panda/linter/test/main/comment_test.ets.migrate.json similarity index 100% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.json rename to ets2panda/linter/test/main/comment_test.ets.migrate.json diff --git a/ets2panda/linter/test/main/custom_layout.ets b/ets2panda/linter/test/main/custom_layout.ets index 233a5aaa79..eb0c300ec8 100644 --- a/ets2panda/linter/test/main/custom_layout.ets +++ b/ets2panda/linter/test/main/custom_layout.ets @@ -20,6 +20,7 @@ struct Index { Column() { CustomLayout1({ builder: ColumnChildren }) CustomLayout2({ builder: ColumnChildren }) + CustomLayout3({ builder: ColumnChildren }) } } } @@ -94,7 +95,44 @@ struct CustomLayout2 { @Component struct CustomLayout3 { - build { + @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; + } + + 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 CustomLayout4 { + build() { } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/custom_layout.ets.arkts2.json b/ets2panda/linter/test/main/custom_layout.ets.arkts2.json index 32ddf7ff59..afc0270a64 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.arkts2.json +++ b/ets2panda/linter/test/main/custom_layout.ets.arkts2.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 29, + "line": 30, "column": 12, - "endLine": 29, + "endLine": 30, "endColumn": 13, "problem": "NumericSemantics", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 30, "column": 15, - "endLine": 29, + "endLine": 30, "endColumn": 16, "problem": "NumericSemantics", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 30, "column": 18, - "endLine": 29, + "endLine": 30, "endColumn": 19, "problem": "NumericSemantics", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 32, "column": 17, - "endLine": 31, + "endLine": 32, "endColumn": 19, "problem": "NumericSemantics", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 33, "column": 14, - "endLine": 32, + "endLine": 33, "endColumn": 17, "problem": "NumericSemantics", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 34, "column": 15, - "endLine": 33, + "endLine": 34, "endColumn": 18, "problem": "NumericSemantics", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 35, "column": 20, - "endLine": 34, + "endLine": 35, "endColumn": 21, "problem": "NumericSemantics", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 36, "column": 20, - "endLine": 35, + "endLine": 36, "endColumn": 22, "problem": "NumericSemantics", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 36, "column": 27, - "endLine": 35, + "endLine": 36, "endColumn": 29, "problem": "NumericSemantics", "suggest": "", @@ -105,19 +105,19 @@ "severity": "ERROR" }, { - "line": 40, + "line": 41, "column": 8, - "endLine": 40, + "endLine": 41, "endColumn": 21, "problem": "CustomLayoutNeedAddDecorator", "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@Layoutable\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 46, + "line": 47, "column": 30, - "endLine": 46, + "endLine": 47, "endColumn": 33, "problem": "NumericSemantics", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 48, + "line": 49, "column": 12, - "endLine": 48, + "endLine": 49, "endColumn": 13, "problem": "NumericSemantics", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 49, + "line": 50, "column": 13, - "endLine": 49, + "endLine": 50, "endColumn": 14, "problem": "NumericSemantics", "suggest": "", @@ -145,9 +145,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 9, - "endLine": 53, + "endLine": 54, "endColumn": 23, "problem": "NumericSemantics", "suggest": "", @@ -155,9 +155,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 20, - "endLine": 53, + "endLine": 54, "endColumn": 23, "problem": "NumericSemantics", "suggest": "", @@ -165,9 +165,9 @@ "severity": "ERROR" }, { - "line": 55, + "line": 56, "column": 11, - "endLine": 55, + "endLine": 56, "endColumn": 54, "problem": "NumericSemantics", "suggest": "", @@ -175,19 +175,19 @@ "severity": "ERROR" }, { - "line": 66, + "line": 67, "column": 8, - "endLine": 66, + "endLine": 67, "endColumn": 21, "problem": "CustomLayoutNeedAddDecorator", "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@Layoutable\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 72, + "line": 73, "column": 30, - "endLine": 72, + "endLine": 73, "endColumn": 33, "problem": "NumericSemantics", "suggest": "", @@ -195,9 +195,9 @@ "severity": "ERROR" }, { - "line": 74, + "line": 75, "column": 12, - "endLine": 74, + "endLine": 75, "endColumn": 13, "problem": "NumericSemantics", "suggest": "", @@ -205,9 +205,9 @@ "severity": "ERROR" }, { - "line": 75, + "line": 76, "column": 13, - "endLine": 75, + "endLine": 76, "endColumn": 14, "problem": "NumericSemantics", "suggest": "", @@ -215,9 +215,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 80, "column": 9, - "endLine": 79, + "endLine": 80, "endColumn": 19, "problem": "NumericSemantics", "suggest": "", @@ -225,9 +225,9 @@ "severity": "ERROR" }, { - "line": 79, + "line": 80, "column": 16, - "endLine": 79, + "endLine": 80, "endColumn": 19, "problem": "NumericSemantics", "suggest": "", @@ -235,9 +235,9 @@ "severity": "ERROR" }, { - "line": 82, + "line": 83, "column": 30, - "endLine": 82, + "endLine": 83, "endColumn": 31, "problem": "NumericSemantics", "suggest": "", @@ -245,9 +245,9 @@ "severity": "ERROR" }, { - "line": 85, + "line": 86, "column": 25, - "endLine": 85, + "endLine": 86, "endColumn": 28, "problem": "NumericSemantics", "suggest": "", @@ -255,9 +255,9 @@ "severity": "ERROR" }, { - "line": 86, + "line": 87, "column": 26, - "endLine": 86, + "endLine": 87, "endColumn": 29, "problem": "NumericSemantics", "suggest": "", @@ -266,12 +266,122 @@ }, { "line": 97, - "column": 3, + "column": 8, "endLine": 97, - "endColumn": 8, - "problem": "AnyType", + "endColumn": 21, + "problem": "CustomLayoutNeedAddDecorator", + "suggest": "", + "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 30, + "endLine": 103, + "endColumn": 33, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 12, + "endLine": 105, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 13, + "endLine": 106, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 9, + "endLine": 110, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 16, + "endLine": 110, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 30, + "endLine": 113, + "endColumn": 31, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 25, + "endLine": 115, + "endColumn": 28, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 26, + "endLine": 116, + "endColumn": 29, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 9, + "endLine": 121, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 20, + "endLine": 121, + "endColumn": 23, + "problem": "NumericSemantics", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 11, + "endLine": 123, + "endColumn": 54, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { @@ -281,7 +391,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -291,7 +401,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -301,217 +411,337 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 27, + "line": 28, "column": 2, - "endLine": 27, + "endLine": 28, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Builder\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 29, + "line": 30, "column": 3, - "endLine": 29, + "endLine": 30, "endColumn": 10, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ForEach\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 30, + "line": 31, "column": 5, - "endLine": 30, + "endLine": 31, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 39, + "line": 40, "column": 2, - "endLine": 39, + "endLine": 40, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 41, + "line": 42, "column": 4, - "endLine": 41, + "endLine": 42, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Builder\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 45, + "line": 46, "column": 4, - "endLine": 45, + "endLine": 46, "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 46, + "line": 47, "column": 4, - "endLine": 46, + "endLine": 47, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 47, + "line": 48, "column": 11, - "endLine": 47, + "endLine": 48, "endColumn": 21, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SizeResult\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 35, - "endLine": 52, + "endLine": 53, "endColumn": 47, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"GeometryInfo\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 65, - "endLine": 52, + "endLine": 53, "endColumn": 75, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Layoutable\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 90, - "endLine": 52, + "endLine": 53, "endColumn": 111, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ConstraintSizeOptions\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 65, + "line": 66, "column": 2, - "endLine": 65, + "endLine": 66, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 67, + "line": 68, "column": 4, - "endLine": 67, + "endLine": 68, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Builder\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 71, + "line": 72, "column": 4, - "endLine": 71, + "endLine": 72, "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 72, + "line": 73, "column": 4, - "endLine": 72, + "endLine": 73, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 73, + "line": 74, "column": 11, - "endLine": 73, + "endLine": 74, + "endColumn": 21, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"SizeResult\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 33, + "endLine": 79, + "endColumn": 45, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"GeometryInfo\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 63, + "endLine": 79, + "endColumn": 73, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Measurable\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 88, + "endLine": 79, + "endColumn": 109, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"ConstraintSizeOptions\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 19, + "endLine": 82, + "endColumn": 32, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"MeasureResult\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 2, + "endLine": 96, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 4, + "endLine": 98, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Builder\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 102, + "column": 4, + "endLine": 102, + "endColumn": 16, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 4, + "endLine": 103, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 11, + "endLine": 104, "endColumn": 21, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SizeResult\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 78, + "line": 109, "column": 33, - "endLine": 78, + "endLine": 109, "endColumn": 45, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"GeometryInfo\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 78, + "line": 109, "column": 63, - "endLine": 78, + "endLine": 109, "endColumn": 73, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Measurable\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 78, + "line": 109, "column": 88, - "endLine": 78, + "endLine": 109, "endColumn": 109, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ConstraintSizeOptions\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 81, + "line": 112, "column": 19, - "endLine": 81, + "endLine": 112, "endColumn": 32, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"MeasureResult\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 35, + "endLine": 120, + "endColumn": 47, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"GeometryInfo\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 65, + "endLine": 120, + "endColumn": 75, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Layoutable\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 90, + "endLine": 120, + "endColumn": 111, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"ConstraintSizeOptions\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/custom_layout.ets.autofix.json b/ets2panda/linter/test/main/custom_layout.ets.autofix.json index 889e3da043..ac5f81be97 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.autofix.json +++ b/ets2panda/linter/test/main/custom_layout.ets.autofix.json @@ -15,19 +15,19 @@ ], "result": [ { - "line": 29, + "line": 30, "column": 12, - "endLine": 29, + "endLine": 30, "endColumn": 13, "problem": "NumericSemantics", "autofix": [ { - "start": 824, - "end": 825, + "start": 873, + "end": 874, "replacementText": "1.0", - "line": 29, + "line": 30, "column": 12, - "endLine": 29, + "endLine": 30, "endColumn": 13 } ], @@ -36,19 +36,19 @@ "severity": "ERROR" }, { - "line": 29, + "line": 30, "column": 15, - "endLine": 29, + "endLine": 30, "endColumn": 16, "problem": "NumericSemantics", "autofix": [ { - "start": 827, - "end": 828, + "start": 876, + "end": 877, "replacementText": "2.0", - "line": 29, + "line": 30, "column": 15, - "endLine": 29, + "endLine": 30, "endColumn": 16 } ], @@ -57,19 +57,19 @@ "severity": "ERROR" }, { - "line": 29, + "line": 30, "column": 18, - "endLine": 29, + "endLine": 30, "endColumn": 19, "problem": "NumericSemantics", "autofix": [ { - "start": 830, - "end": 831, + "start": 879, + "end": 880, "replacementText": "3.0", - "line": 29, + "line": 30, "column": 18, - "endLine": 29, + "endLine": 30, "endColumn": 19 } ], @@ -78,19 +78,19 @@ "severity": "ERROR" }, { - "line": 31, + "line": 32, "column": 17, - "endLine": 31, + "endLine": 32, "endColumn": 19, "problem": "NumericSemantics", "autofix": [ { - "start": 914, - "end": 916, + "start": 963, + "end": 965, "replacementText": "30.0", - "line": 31, + "line": 32, "column": 17, - "endLine": 31, + "endLine": 32, "endColumn": 19 } ], @@ -99,19 +99,19 @@ "severity": "ERROR" }, { - "line": 32, + "line": 33, "column": 14, - "endLine": 32, + "endLine": 33, "endColumn": 17, "problem": "NumericSemantics", "autofix": [ { - "start": 931, - "end": 934, + "start": 980, + "end": 983, "replacementText": "100.0", - "line": 32, + "line": 33, "column": 14, - "endLine": 32, + "endLine": 33, "endColumn": 17 } ], @@ -120,19 +120,19 @@ "severity": "ERROR" }, { - "line": 33, + "line": 34, "column": 15, - "endLine": 33, + "endLine": 34, "endColumn": 18, "problem": "NumericSemantics", "autofix": [ { - "start": 950, - "end": 953, + "start": 999, + "end": 1002, "replacementText": "100.0", - "line": 33, + "line": 34, "column": 15, - "endLine": 33, + "endLine": 34, "endColumn": 18 } ], @@ -141,19 +141,19 @@ "severity": "ERROR" }, { - "line": 34, + "line": 35, "column": 20, - "endLine": 34, + "endLine": 35, "endColumn": 21, "problem": "NumericSemantics", "autofix": [ { - "start": 974, - "end": 975, + "start": 1023, + "end": 1024, "replacementText": "2.0", - "line": 34, + "line": 35, "column": 20, - "endLine": 34, + "endLine": 35, "endColumn": 21 } ], @@ -162,19 +162,19 @@ "severity": "ERROR" }, { - "line": 35, + "line": 36, "column": 20, - "endLine": 35, + "endLine": 36, "endColumn": 22, "problem": "NumericSemantics", "autofix": [ { - "start": 996, - "end": 998, + "start": 1045, + "end": 1047, "replacementText": "10.0", - "line": 35, + "line": 36, "column": 20, - "endLine": 35, + "endLine": 36, "endColumn": 22 } ], @@ -183,19 +183,19 @@ "severity": "ERROR" }, { - "line": 35, + "line": 36, "column": 27, - "endLine": 35, + "endLine": 36, "endColumn": 29, "problem": "NumericSemantics", "autofix": [ { - "start": 1003, - "end": 1005, + "start": 1052, + "end": 1054, "replacementText": "20.0", - "line": 35, + "line": 36, "column": 27, - "endLine": 35, + "endLine": 36, "endColumn": 29 } ], @@ -204,40 +204,40 @@ "severity": "ERROR" }, { - "line": 40, + "line": 41, "column": 8, - "endLine": 40, + "endLine": 41, "endColumn": 21, "problem": "CustomLayoutNeedAddDecorator", "autofix": [ { - "start": 1027, - "end": 1027, - "replacementText": "\n@Layoutable", - "line": 40, + "start": 1076, + "end": 1076, + "replacementText": "\n@CustomLayout", + "line": 41, "column": 8, - "endLine": 40, + "endLine": 41, "endColumn": 21 } ], "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@Layoutable\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 46, + "line": 47, "column": 30, - "endLine": 46, + "endLine": 47, "endColumn": 33, "problem": "NumericSemantics", "autofix": [ { - "start": 1181, - "end": 1184, + "start": 1230, + "end": 1233, "replacementText": "100.0", - "line": 46, + "line": 47, "column": 30, - "endLine": 46, + "endLine": 47, "endColumn": 33 } ], @@ -246,19 +246,19 @@ "severity": "ERROR" }, { - "line": 48, + "line": 49, "column": 12, - "endLine": 48, + "endLine": 49, "endColumn": 13, "problem": "NumericSemantics", "autofix": [ { - "start": 1222, - "end": 1223, + "start": 1271, + "end": 1272, "replacementText": "0.0", - "line": 48, + "line": 49, "column": 12, - "endLine": 48, + "endLine": 49, "endColumn": 13 } ], @@ -267,19 +267,19 @@ "severity": "ERROR" }, { - "line": 49, + "line": 50, "column": 13, - "endLine": 49, + "endLine": 50, "endColumn": 14, "problem": "NumericSemantics", "autofix": [ { - "start": 1237, - "end": 1238, + "start": 1286, + "end": 1287, "replacementText": "0.0", - "line": 49, + "line": 50, "column": 13, - "endLine": 49, + "endLine": 50, "endColumn": 14 } ], @@ -288,19 +288,19 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 9, - "endLine": 53, + "endLine": 54, "endColumn": 23, "problem": "NumericSemantics", "autofix": [ { - "start": 1367, - "end": 1381, + "start": 1416, + "end": 1430, "replacementText": "startPos: number = 300", - "line": 53, + "line": 54, "column": 9, - "endLine": 53, + "endLine": 54, "endColumn": 23 } ], @@ -309,19 +309,19 @@ "severity": "ERROR" }, { - "line": 53, + "line": 54, "column": 20, - "endLine": 53, + "endLine": 54, "endColumn": 23, "problem": "NumericSemantics", "autofix": [ { - "start": 1378, - "end": 1381, + "start": 1427, + "end": 1430, "replacementText": "300.0", - "line": 53, + "line": 54, "column": 20, - "endLine": 53, + "endLine": 54, "endColumn": 23 } ], @@ -330,19 +330,19 @@ "severity": "ERROR" }, { - "line": 55, + "line": 56, "column": 11, - "endLine": 55, + "endLine": 56, "endColumn": 54, "problem": "NumericSemantics", "autofix": [ { - "start": 1427, - "end": 1470, + "start": 1476, + "end": 1519, "replacementText": "pos: number = startPos - child.measureResult.height", - "line": 55, + "line": 56, "column": 11, - "endLine": 55, + "endLine": 56, "endColumn": 54 } ], @@ -351,40 +351,40 @@ "severity": "ERROR" }, { - "line": 66, + "line": 67, "column": 8, - "endLine": 66, + "endLine": 67, "endColumn": 21, "problem": "CustomLayoutNeedAddDecorator", "autofix": [ { - "start": 1571, - "end": 1571, - "replacementText": "\n@Layoutable", - "line": 66, + "start": 1620, + "end": 1620, + "replacementText": "\n@CustomLayout", + "line": 67, "column": 8, - "endLine": 66, + "endLine": 67, "endColumn": 21 } ], "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@Layoutable\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 72, + "line": 73, "column": 30, - "endLine": 72, + "endLine": 73, "endColumn": 33, "problem": "NumericSemantics", "autofix": [ { - "start": 1725, - "end": 1728, + "start": 1774, + "end": 1777, "replacementText": "100.0", - "line": 72, + "line": 73, "column": 30, - "endLine": 72, + "endLine": 73, "endColumn": 33 } ], @@ -393,19 +393,19 @@ "severity": "ERROR" }, { - "line": 74, + "line": 75, "column": 12, - "endLine": 74, + "endLine": 75, "endColumn": 13, "problem": "NumericSemantics", "autofix": [ { - "start": 1766, - "end": 1767, + "start": 1815, + "end": 1816, "replacementText": "0.0", - "line": 74, + "line": 75, "column": 12, - "endLine": 74, + "endLine": 75, "endColumn": 13 } ], @@ -414,19 +414,19 @@ "severity": "ERROR" }, { - "line": 75, + "line": 76, "column": 13, - "endLine": 75, + "endLine": 76, "endColumn": 14, "problem": "NumericSemantics", "autofix": [ { - "start": 1781, - "end": 1782, + "start": 1830, + "end": 1831, "replacementText": "0.0", - "line": 75, + "line": 76, "column": 13, - "endLine": 75, + "endLine": 76, "endColumn": 14 } ], @@ -435,19 +435,19 @@ "severity": "ERROR" }, { - "line": 79, + "line": 80, "column": 9, - "endLine": 79, + "endLine": 80, "endColumn": 19, "problem": "NumericSemantics", "autofix": [ { - "start": 1909, - "end": 1919, + "start": 1958, + "end": 1968, "replacementText": "size: number = 100", - "line": 79, + "line": 80, "column": 9, - "endLine": 79, + "endLine": 80, "endColumn": 19 } ], @@ -456,19 +456,19 @@ "severity": "ERROR" }, { - "line": 79, + "line": 80, "column": 16, - "endLine": 79, + "endLine": 80, "endColumn": 19, "problem": "NumericSemantics", "autofix": [ { - "start": 1916, - "end": 1919, + "start": 1965, + "end": 1968, "replacementText": "100.0", - "line": 79, + "line": 80, "column": 16, - "endLine": 79, + "endLine": 80, "endColumn": 19 } ], @@ -477,19 +477,19 @@ "severity": "ERROR" }, { - "line": 82, + "line": 83, "column": 30, - "endLine": 82, + "endLine": 83, "endColumn": 31, "problem": "NumericSemantics", "autofix": [ { - "start": 2102, - "end": 2103, + "start": 2151, + "end": 2152, "replacementText": "2.0", - "line": 82, + "line": 83, "column": 30, - "endLine": 82, + "endLine": 83, "endColumn": 31 } ], @@ -498,19 +498,19 @@ "severity": "ERROR" }, { - "line": 85, + "line": 86, "column": 25, - "endLine": 85, + "endLine": 86, "endColumn": 28, "problem": "NumericSemantics", "autofix": [ { - "start": 2143, - "end": 2146, + "start": 2192, + "end": 2195, "replacementText": "100.0", - "line": 85, + "line": 86, "column": 25, - "endLine": 85, + "endLine": 86, "endColumn": 28 } ], @@ -519,19 +519,19 @@ "severity": "ERROR" }, { - "line": 86, + "line": 87, "column": 26, - "endLine": 86, + "endLine": 87, "endColumn": 29, "problem": "NumericSemantics", "autofix": [ { - "start": 2173, - "end": 2176, + "start": 2222, + "end": 2225, "replacementText": "400.0", - "line": 86, + "line": 87, "column": 26, - "endLine": 86, + "endLine": 87, "endColumn": 29 } ], @@ -541,228 +541,470 @@ }, { "line": 97, - "column": 3, + "column": 8, "endLine": 97, - "endColumn": 8, - "problem": "AnyType", + "endColumn": 21, + "problem": "CustomLayoutNeedAddDecorator", + "autofix": [ + { + "start": 2304, + "end": 2304, + "replacementText": "\n@CustomLayout", + "line": 97, + "column": 8, + "endLine": 97, + "endColumn": 21 + } + ], "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { - "line": 16, - "column": 2, - "endLine": 16, - "endColumn": 7, - "problem": "UIInterfaceImport", + "line": 103, + "column": 30, + "endLine": 103, + "endColumn": 33, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 2458, + "end": 2461, + "replacementText": "100.0", + "line": 103, + "column": 30, + "endLine": 103, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 17, - "column": 2, - "endLine": 17, - "endColumn": 11, - "problem": "UIInterfaceImport", + "line": 105, + "column": 12, + "endLine": 105, + "endColumn": 13, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 2499, + "end": 2500, + "replacementText": "0.0", + "line": 105, + "column": 12, + "endLine": 105, + "endColumn": 13 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 20, - "column": 5, - "endLine": 20, - "endColumn": 11, - "problem": "UIInterfaceImport", + "line": 106, + "column": 13, + "endLine": 106, + "endColumn": 14, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 2514, + "end": 2515, + "replacementText": "0.0", + "line": 106, + "column": 13, + "endLine": 106, + "endColumn": 14 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 27, - "column": 2, - "endLine": 27, - "endColumn": 9, - "problem": "UIInterfaceImport", + "line": 110, + "column": 9, + "endLine": 110, + "endColumn": 19, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 2642, + "end": 2652, + "replacementText": "size: number = 100", + "line": 110, + "column": 9, + "endLine": 110, + "endColumn": 19 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 29, - "column": 3, - "endLine": 29, - "endColumn": 10, - "problem": "UIInterfaceImport", + "line": 110, + "column": 16, + "endLine": 110, + "endColumn": 19, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 2649, + "end": 2652, + "replacementText": "100.0", + "line": 110, + "column": 16, + "endLine": 110, + "endColumn": 19 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 30, - "column": 5, - "endLine": 30, - "endColumn": 9, - "problem": "UIInterfaceImport", + "line": 113, + "column": 30, + "endLine": 113, + "endColumn": 31, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 2835, + "end": 2836, + "replacementText": "2.0", + "line": 113, + "column": 30, + "endLine": 113, + "endColumn": 31 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 39, - "column": 2, - "endLine": 39, - "endColumn": 11, - "problem": "UIInterfaceImport", + "line": 115, + "column": 25, + "endLine": 115, + "endColumn": 28, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 2869, + "end": 2872, + "replacementText": "100.0", + "line": 115, + "column": 25, + "endLine": 115, + "endColumn": 28 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 41, - "column": 4, - "endLine": 41, - "endColumn": 11, - "problem": "UIInterfaceImport", + "line": 116, + "column": 26, + "endLine": 116, + "endColumn": 29, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 2899, + "end": 2902, + "replacementText": "400.0", + "line": 116, + "column": 26, + "endLine": 116, + "endColumn": 29 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 45, - "column": 4, - "endLine": 45, - "endColumn": 16, - "problem": "UIInterfaceImport", + "line": 121, + "column": 9, + "endLine": 121, + "endColumn": 23, + "problem": "NumericSemantics", "autofix": [ { - "start": 603, - "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, - "column": 2, - "endLine": 95, - "endColumn": 11 + "start": 3055, + "end": 3069, + "replacementText": "startPos: number = 300", + "line": 121, + "column": 9, + "endLine": 121, + "endColumn": 23 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 46, + "line": 121, + "column": 20, + "endLine": 121, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 3066, + "end": 3069, + "replacementText": "300.0", + "line": 121, + "column": 20, + "endLine": 121, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 11, + "endLine": 123, + "endColumn": 54, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 3115, + "end": 3158, + "replacementText": "pos: number = startPos - child.measureResult.height", + "line": 123, + "column": 11, + "endLine": 123, + "endColumn": 54 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (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, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 5, + "endLine": 20, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 2, + "endLine": 28, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Builder\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 3, + "endLine": 30, + "endColumn": 10, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"ForEach\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 2, + "endLine": 40, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 4, + "endLine": 42, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Builder\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 46, "column": 4, "endLine": 46, - "endColumn": 9, + "endColumn": 16, "problem": "UIInterfaceImport", "autofix": [ { "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { "line": 47, - "column": 11, + "column": 4, "endLine": 47, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 11, + "endLine": 48, "endColumn": 21, "problem": "UIInterfaceImport", "autofix": [ @@ -770,20 +1012,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SizeResult\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 35, - "endLine": 52, + "endLine": 53, "endColumn": 47, "problem": "UIInterfaceImport", "autofix": [ @@ -791,20 +1033,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"GeometryInfo\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 65, - "endLine": 52, + "endLine": 53, "endColumn": 75, "problem": "UIInterfaceImport", "autofix": [ @@ -812,20 +1054,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Layoutable\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 52, + "line": 53, "column": 90, - "endLine": 52, + "endLine": 53, "endColumn": 111, "problem": "UIInterfaceImport", "autofix": [ @@ -833,20 +1075,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ConstraintSizeOptions\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 65, + "line": 66, "column": 2, - "endLine": 65, + "endLine": 66, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -854,20 +1096,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 67, + "line": 68, "column": 4, - "endLine": 67, + "endLine": 68, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -875,20 +1117,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Builder\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 71, + "line": 72, "column": 4, - "endLine": 71, + "endLine": 72, "endColumn": 16, "problem": "UIInterfaceImport", "autofix": [ @@ -896,20 +1138,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 72, + "line": 73, "column": 4, - "endLine": 72, + "endLine": 73, "endColumn": 9, "problem": "UIInterfaceImport", "autofix": [ @@ -917,20 +1159,209 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 73, + "line": 74, "column": 11, - "endLine": 73, + "endLine": 74, + "endColumn": 21, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"SizeResult\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 33, + "endLine": 79, + "endColumn": 45, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"GeometryInfo\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 63, + "endLine": 79, + "endColumn": 73, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Measurable\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 88, + "endLine": 79, + "endColumn": 109, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"ConstraintSizeOptions\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 19, + "endLine": 82, + "endColumn": 32, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"MeasureResult\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 2, + "endLine": 96, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 4, + "endLine": 98, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Builder\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 102, + "column": 4, + "endLine": 102, + "endColumn": 16, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 4, + "endLine": 103, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 11, + "endLine": 104, "endColumn": 21, "problem": "UIInterfaceImport", "autofix": [ @@ -938,20 +1369,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SizeResult\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 78, + "line": 109, "column": 33, - "endLine": 78, + "endLine": 109, "endColumn": 45, "problem": "UIInterfaceImport", "autofix": [ @@ -959,20 +1390,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"GeometryInfo\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 78, + "line": 109, "column": 63, - "endLine": 78, + "endLine": 109, "endColumn": 73, "problem": "UIInterfaceImport", "autofix": [ @@ -980,20 +1411,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Measurable\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 78, + "line": 109, "column": 88, - "endLine": 78, + "endLine": 109, "endColumn": 109, "problem": "UIInterfaceImport", "autofix": [ @@ -1001,20 +1432,20 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ConstraintSizeOptions\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 81, + "line": 112, "column": 19, - "endLine": 81, + "endLine": 112, "endColumn": 32, "problem": "UIInterfaceImport", "autofix": [ @@ -1022,20 +1453,83 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"MeasureResult\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 35, + "endLine": 120, + "endColumn": 47, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"GeometryInfo\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 65, + "endLine": 120, + "endColumn": 75, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, + "column": 2, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Layoutable\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 90, + "endLine": 120, + "endColumn": 111, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ConstraintSizeOptions\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11, "problem": "UIInterfaceImport", "autofix": [ @@ -1043,14 +1537,14 @@ "start": 603, "end": 603, "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", - "line": 95, + "line": 133, "column": 2, - "endLine": 95, + "endLine": 133, "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/custom_layout.ets.json b/ets2panda/linter/test/main/custom_layout.ets.json index 5d769b466b..cc51fe6a1b 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.json +++ b/ets2panda/linter/test/main/custom_layout.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 78, + "line": 79, "column": 3, - "endLine": 78, + "endLine": 79, "endColumn": 16, "problem": "LimitedReturnTypeInference", "suggest": "", @@ -25,13 +25,13 @@ "severity": "ERROR" }, { - "line": 97, + "line": 109, "column": 3, - "endLine": 97, - "endColumn": 8, - "problem": "AnyType", + "endLine": 109, + "endColumn": 16, + "problem": "LimitedReturnTypeInference", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/custom_layout.ets.migrate.ets b/ets2panda/linter/test/main/custom_layout.ets.migrate.ets index 97dd101026..5053380e4c 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.migrate.ets +++ b/ets2panda/linter/test/main/custom_layout.ets.migrate.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +import { CustomLayout } from '@kit.ArkUI'; + import { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI'; @Entry @@ -22,6 +24,7 @@ struct Index { Column() { CustomLayout1({ builder: ColumnChildren }) CustomLayout2({ builder: ColumnChildren }) + CustomLayout3({ builder: ColumnChildren }) } } } @@ -39,7 +42,7 @@ function ColumnChildren() { } @Component -@Layoutable +@CustomLayout struct CustomLayout1 { @Builder doNothingBuilder() { @@ -66,7 +69,7 @@ struct CustomLayout1 { } @Component -@Layoutable +@CustomLayout struct CustomLayout2 { @Builder doNothingBuilder() { @@ -97,8 +100,46 @@ struct CustomLayout2 { } @Component +@CustomLayout struct CustomLayout3 { - build { + @Builder + doNothingBuilder() { + }; + + @BuilderParam builder: () => void = this.doNothingBuilder; + @State startSize: number = 100.0; + result: SizeResult = { + width: 0.0, + height: 0.0 + }; + + onMeasureSize(selfLayoutInfo: GeometryInfo, children: Array, constraint: ConstraintSizeOptions) { + let size: number = 100.0; + children.forEach((child) => { + let result: MeasureResult = child.measure({ minHeight: size, minWidth: size, maxWidth: size, maxHeight: size }) + size += result.width / 2.0; + }) + this.result.width = 100.0; + this.result.height = 400.0; + return this.result; + } + + onPlaceChildren(selfLayoutInfo: GeometryInfo, children: Array, constraint: ConstraintSizeOptions) { + let startPos: number = 300.0; + children.forEach((child) => { + let pos: number = startPos - child.measureResult.height; + child.layout({ x: pos, y: pos }) + }) + } + + build() { + this.builder() + } +} + +@Component +struct CustomLayout4 { + 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 index 6c283c3ef1..21ac1fc70c 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.migrate.json +++ b/ets2panda/linter/test/main/custom_layout.ets.migrate.json @@ -15,33 +15,33 @@ ], "result": [ { - "line": 42, + "line": 45, "column": 1, - "endLine": 42, - "endColumn": 12, + "endLine": 45, + "endColumn": 14, "problem": "DecoratorsNotSupported", "suggest": "", "rule": "Decorators are not supported(arkts-no-ts-decorators)", "severity": "ERROR" }, { - "line": 69, + "line": 72, "column": 1, - "endLine": 69, - "endColumn": 12, + "endLine": 72, + "endColumn": 14, "problem": "DecoratorsNotSupported", "suggest": "", "rule": "Decorators are not supported(arkts-no-ts-decorators)", "severity": "ERROR" }, { - "line": 101, - "column": 3, - "endLine": 101, - "endColumn": 8, - "problem": "AnyType", + "line": 103, + "column": 1, + "endLine": 103, + "endColumn": 14, + "problem": "DecoratorsNotSupported", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/debugger_statememt.ets.args.json b/ets2panda/linter/test/main/debugger_statememt.ets.args.json index f56752f228..4acc088d1d 100644 --- a/ets2panda/linter/test/main/debugger_statememt.ets.args.json +++ b/ets2panda/linter/test/main/debugger_statememt.ets.args.json @@ -14,8 +14,6 @@ "limitations under the License." ], "mode": { - "arkts2": "", - "autofix": "--arkts-2", - "migrate": "--arkts-2" + "arkts2": "" } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/debugger_statememt.ets.arkts2.json b/ets2panda/linter/test/main/debugger_statememt.ets.arkts2.json index a220a01038..09196c4c33 100644 --- a/ets2panda/linter/test/main/debugger_statememt.ets.arkts2.json +++ b/ets2panda/linter/test/main/debugger_statememt.ets.arkts2.json @@ -21,7 +21,7 @@ "endColumn": 10, "problem": "DebuggerStatement", "suggest": "", - "rule": "\"debugger\" is not supported (arkts-no-debugger-stmt)", + "rule": "\"debugger\" is not supported (arkts-no-debugger)", "severity": "ERROR" }, { @@ -31,7 +31,7 @@ "endColumn": 12, "problem": "DebuggerStatement", "suggest": "", - "rule": "\"debugger\" is not supported (arkts-no-debugger-stmt)", + "rule": "\"debugger\" is not supported (arkts-no-debugger)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/default_required_args.ets b/ets2panda/linter/test/main/default_required_args.ets index cbccdb42cf..613b5ac307 100644 --- a/ets2panda/linter/test/main/default_required_args.ets +++ b/ets2panda/linter/test/main/default_required_args.ets @@ -57,4 +57,17 @@ function log(level: string = 'info', some: string, message?: string): void { function config(debug: boolean = true, verbose?: boolean): string { //legal return `Debug: ${debug ?? false}, Verbose: ${verbose ?? false}`; +} + +export class DefaultArgsA { + readonly left: number; + readonly right: number; + constructor(left: number = 0.0, right: number) { // 漏扫 + this.left = left; + this.right = right; + } + + defaultArgsFoo1(left: number = 0.0, right: number): number { + return left + right; + } } \ 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 index bbcdfcb085..33a446a701 100644 --- a/ets2panda/linter/test/main/default_required_args.ets.arkts2.json +++ b/ets2panda/linter/test/main/default_required_args.ets.arkts2.json @@ -173,6 +173,26 @@ "suggest": "", "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", "severity": "ERROR" + }, + { + "line": 65, + "column": 15, + "endLine": 65, + "endColumn": 19, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 19, + "endLine": 70, + "endColumn": 23, + "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/dollar_binding_1.ets.arkts2.json b/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json index 674cd0d868..0370cab257 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.arkts2.json @@ -61,7 +61,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Link\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (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 3081866ef6..3987f67867 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json @@ -116,7 +116,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -137,7 +137,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -158,7 +158,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -179,7 +179,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -200,7 +200,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Link\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -242,7 +242,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -263,7 +263,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 f62cf13942..6fcb57db65 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 @@ -51,7 +51,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Checkbox\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 12, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (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 7a7748866b..b76e000be1 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 @@ -95,7 +95,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -116,7 +116,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -137,7 +137,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -158,7 +158,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -179,7 +179,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -200,7 +200,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -242,7 +242,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Checkbox\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -263,7 +263,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -284,7 +284,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 1049eb7c5c..96a079fe66 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 @@ -131,7 +131,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -161,7 +161,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -171,7 +171,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -181,7 +181,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -191,7 +191,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -201,7 +201,7 @@ "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Checkbox\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -211,7 +211,7 @@ "endColumn": 12, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -231,7 +231,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -241,7 +241,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -251,7 +251,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -261,7 +261,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -271,7 +271,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -281,7 +281,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -291,7 +291,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -301,7 +301,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -311,7 +311,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -321,7 +321,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -331,7 +331,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -341,7 +341,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -351,7 +351,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -361,7 +361,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -371,7 +371,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -381,7 +381,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -391,7 +391,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -401,7 +401,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -411,7 +411,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -421,7 +421,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -431,7 +431,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Param\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -441,7 +441,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Event\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -451,7 +451,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -461,7 +461,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -471,7 +471,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (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 b10e76da6e..4115b5173b 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 @@ -263,7 +263,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -284,7 +284,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -305,7 +305,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -326,7 +326,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -347,7 +347,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -368,7 +368,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -389,7 +389,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -410,7 +410,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Checkbox\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -431,7 +431,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -452,7 +452,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -473,7 +473,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -494,7 +494,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -515,7 +515,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -536,7 +536,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -557,7 +557,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -578,7 +578,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -599,7 +599,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -620,7 +620,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -641,7 +641,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -662,7 +662,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -683,7 +683,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -704,7 +704,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Slider\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -725,7 +725,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -746,7 +746,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -767,7 +767,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -788,7 +788,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -809,7 +809,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -830,7 +830,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -851,7 +851,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -872,7 +872,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -893,7 +893,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Param\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -914,7 +914,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Event\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -935,7 +935,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -956,7 +956,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -977,7 +977,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/double_excla_binding_3.ets b/ets2panda/linter/test/main/double_excla_binding_3.ets new file mode 100644 index 0000000000..8c9dcc1e87 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_3.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 User { + name: string = "Jack" +} + +@Entry +@Component +struct MyComponent { + @State user: User = new User() + + build() { + Row() { + Text(this.user!.name) + Text(this.user!!.name) + Text(this.user!!!.name) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_3.ets.args.json b/ets2panda/linter/test/main/double_excla_binding_3.ets.args.json new file mode 100644 index 0000000000..30973c00a2 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_3.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/double_excla_binding_3.ets.arkts2.json b/ets2panda/linter/test/main/double_excla_binding_3.ets.arkts2.json new file mode 100644 index 0000000000..d73e979005 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_3.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": 20, + "column": 2, + "endLine": 20, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 4, + "endLine": 23, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 7, + "endLine": 27, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 7, + "endLine": 28, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_3.ets.autofix.json b/ets2panda/linter/test/main/double_excla_binding_3.ets.autofix.json new file mode 100644 index 0000000000..36d4ed4525 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_3.ets.autofix.json @@ -0,0 +1,165 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 2, + "endLine": 20, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 4, + "endLine": 23, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 7, + "endLine": 27, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 7, + "endLine": 28, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "line": 29, + "column": 7, + "endLine": 29, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_3.ets.json b/ets2panda/linter/test/main/double_excla_binding_3.ets.json new file mode 100644 index 0000000000..b7a8809e02 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_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/global_this.ets.migrate.ets b/ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.ets similarity index 50% rename from ets2panda/linter/test/main/global_this.ets.migrate.ets rename to ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.ets index aaafd6ebd1..b646a64c49 100644 --- a/ets2panda/linter/test/main/global_this.ets.migrate.ets +++ b/ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.ets @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-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 @@ -13,29 +13,22 @@ * limitations under the License. */ -const pi: number = 3.1416; +import { Entry, Component, State, Row, Text } from '@kit.ArkUI'; -function circleArea(r: number): number { - foo(globalThis); - - return specialAutofixLib.globalThis.get("pi") * r * r; -} - -function foo(x: any): void { - console.log(x.pi); +class User { + name: string = "Jack" } -specialAutofixLib.globalThis.set("abc", 200.0); - -const value = specialAutofixLib.globalThis.get("obj").prop; - -delete specialAutofixLib.globalThis.get("property"); - -globalThisprop = 100.0; - -specialAutofixLib.globalThis.get("pi"); - -specialAutofixLib.globalThis.set("pi",3.1416); - -specialAutofixLib.globalThis; - +@Entry +@Component +struct MyComponent { + @State user: User = new User() + + build() { + Row() { + Text(this.user!.name) + Text(this.user!!.name) + Text(this.user!!!.name) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.json b/ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.json new file mode 100644 index 0000000000..b7a8809e02 --- /dev/null +++ b/ets2panda/linter/test/main/double_excla_binding_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/main/dynamic_ctor_call.ets.arkts2.json b/ets2panda/linter/test/main/dynamic_ctor_call.ets.arkts2.json index 0ef26c352d..b4ee74500e 100644 --- a/ets2panda/linter/test/main/dynamic_ctor_call.ets.arkts2.json +++ b/ets2panda/linter/test/main/dynamic_ctor_call.ets.arkts2.json @@ -124,6 +124,16 @@ "rule": "Construct signatures are not supported in interfaces (arkts-no-ctor-signatures-iface)", "severity": "ERROR" }, + { + "line": 39, + "column": 14, + "endLine": 39, + "endColumn": 18, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, { "line": 39, "column": 14, diff --git a/ets2panda/linter/test/main/dynamic_import.ets.arkts2.json b/ets2panda/linter/test/main/dynamic_import.ets.arkts2.json index 30c87c82a5..ae596bc17e 100644 --- a/ets2panda/linter/test/main/dynamic_import.ets.arkts2.json +++ b/ets2panda/linter/test/main/dynamic_import.ets.arkts2.json @@ -161,7 +161,7 @@ "endColumn": 76, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"EllipseShape\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 c1e82092cb..a8450fce0e 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 @@ -20,13 +20,6 @@ "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" @@ -41,7 +34,11 @@ { "start": 725, "end": 750, - "replacementText": "const __get_local_storage__ = (): LocalStorage => source;\n@Entry({ storage: \"__get_local_storage__\" })" + "replacementText": "const __get_local_storage__ = (): LocalStorage => source;\n@Entry({ storage: \"__get_local_storage__\" })", + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 26 } ], "suggest": "", 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 index 1159381e1c..bf1b217b00 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.ets @@ -15,8 +15,8 @@ import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; -const source = specialAutofixLib.globalThis.get("localStorage"); -const __get_local_storage__ = (): LocalStorage => source; +const source = globalThis.localStorage; +const __get_local_storage__ = (): LocalStorage => source; @Entry({ storage: "__get_local_storage__" }) @Component struct MyPage { 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 index 045feeac1b..8723136274 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.json +++ b/ets2panda/linter/test/main/entry_annotation_test8_1.ets.migrate.json @@ -16,12 +16,12 @@ "result": [ { "line": 18, - "column": 7, + "column": 16, "endLine": 18, - "endColumn": 64, - "problem": "AnyType", + "endColumn": 39, + "problem": "GlobalThisError", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", "severity": "ERROR" } ] 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 f73277ba2c..8723136274 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 @@ -20,13 +20,6 @@ "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" 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 index 0c20666abf..1120a5a860 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.ets +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.ets @@ -15,7 +15,7 @@ import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; -const source = specialAutofixLib.globalThis.get("localStorage"); +const source = globalThis.localStorage; const __get_local_storage__ = (): LocalStorage => source; @Entry({storage: "__get_local_storage__"}) @Component 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 index 045feeac1b..8723136274 100644 --- a/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.json +++ b/ets2panda/linter/test/main/entry_annotation_test8_2.ets.migrate.json @@ -16,12 +16,12 @@ "result": [ { "line": 18, - "column": 7, + "column": 16, "endLine": 18, - "endColumn": 64, - "problem": "AnyType", + "endColumn": 39, + "problem": "GlobalThisError", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", "severity": "ERROR" } ] 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 f8e2a1ef6c..19bc667ae8 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 @@ -24,7 +24,11 @@ { "start": 685, "end": 727, - "replacementText": "const __get_local_storage__ = (): LocalStorage => globalThis.localStorage;\n@Entry({ storage: \"__get_local_storage__\" })" + "replacementText": "const __get_local_storage__ = (): LocalStorage => globalThis.localStorage;\n@Entry({ storage: \"__get_local_storage__\" })", + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 43 } ], "suggest": "", @@ -37,13 +41,6 @@ "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" 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 index 8c9d2b2012..94bcbfdd9b 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.ets @@ -15,7 +15,7 @@ import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; -const __get_local_storage__ = (): LocalStorage => specialAutofixLib.globalThis.get("localStorage"); +const __get_local_storage__ = (): LocalStorage => globalThis.localStorage; @Entry({ storage: "__get_local_storage__" }) @Component struct MyPage { 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 index ca88f857e9..a390c87a2e 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.json +++ b/ets2panda/linter/test/main/entry_annotation_test9_1.ets.migrate.json @@ -13,5 +13,16 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "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 index 17f6fcde03..a390c87a2e 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 @@ -20,13 +20,6 @@ "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" 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 index 9f1162ccfd..f6f5bf039f 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.ets +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.ets @@ -15,7 +15,7 @@ import { Entry, Component, Text, LocalStorage } from '@ohos.arkui.components'; -const __get_local_storage__ = (): LocalStorage => specialAutofixLib.globalThis.get("localStorage"); +const __get_local_storage__ = (): LocalStorage => globalThis.localStorage; @Entry({storage: "__get_local_storage__"}) @Component struct MyPage { 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 index ca88f857e9..a390c87a2e 100644 --- a/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.json +++ b/ets2panda/linter/test/main/entry_annotation_test9_2.ets.migrate.json @@ -13,5 +13,16 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "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/enum_not_support_float.ets.arkts2.json b/ets2panda/linter/test/main/enum_not_support_float.ets.arkts2.json index ff258d6c12..95b3bdaefb 100644 --- a/ets2panda/linter/test/main/enum_not_support_float.ets.arkts2.json +++ b/ets2panda/linter/test/main/enum_not_support_float.ets.arkts2.json @@ -14,6 +14,16 @@ "limitations under the License." ], "result": [ + { + "line": 23, + "column": 7, + "endLine": 23, + "endColumn": 9, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 24, "column": 3, 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 6c7ca94b92..54fab7a23c 100755 --- a/ets2panda/linter/test/main/explicit_function_type.ets.arkts2.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.arkts2.json @@ -224,6 +224,16 @@ "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, + { + "line": 133, + "column": 10, + "endLine": 133, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 139, "column": 3, @@ -323,6 +333,16 @@ "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": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json b/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json index 6f0f0a0481..a9ddde793c 100644 --- a/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json @@ -106,7 +106,7 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "fn.unSafeCall", + "replacementText": "fn.unsafeCall", "start": 1572, "end": 1574, "line": 57, @@ -345,6 +345,27 @@ "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, + { + "line": 133, + "column": 10, + "endLine": 133, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2849, + "end": 2850, + "replacementText": "1.0", + "line": 133, + "column": 10, + "endLine": 133, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 139, "column": 3, @@ -353,7 +374,7 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "callback.unSafeCall", + "replacementText": "callback.unsafeCall", "start": 2921, "end": 2929, "line": 139, @@ -425,7 +446,7 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "curr.unSafeCall", + "replacementText": "curr.unsafeCall", "start": 3458, "end": 3462, "line": 160, @@ -446,7 +467,7 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "prev.unSafeCall", + "replacementText": "prev.unsafeCall", "start": 3463, "end": 3467, "line": 160, @@ -467,7 +488,7 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "f1.unSafeCall", + "replacementText": "f1.unsafeCall", "start": 3586, "end": 3588, "line": 166, @@ -488,7 +509,7 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "ab3.fn3.unSafeCall", + "replacementText": "ab3.fn3.unsafeCall", "start": 3656, "end": 3663, "line": 172, @@ -509,7 +530,7 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "fn29[1].unSafeCall", + "replacementText": "fn29[1].unsafeCall", "start": 3697, "end": 3704, "line": 175, @@ -521,6 +542,16 @@ "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": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets index 0a5b1a221f..7d20e3f229 100644 --- a/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets +++ b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets @@ -54,7 +54,7 @@ class D5 implements C5 { } function run6(fn: Function) { - fn.unSafeCall(); + fn.unsafeCall(); } function getFunction8(): Function { @@ -130,13 +130,13 @@ let tup38:[['arkts'|Function, 1.0|true, false], string[], Function] = [['arkts', //枚举 enum E39 { Function, - BLUE = 1, + BLUE = 1.0, YELLOW } //回调参数不明确 function handleEvent41(callback: Function) { - callback.unSafeCall("event", Date.now()); + callback.unsafeCall("event", Date.now()); } let fn43: Function = (x: number) => x + 1.0; @@ -157,19 +157,19 @@ const fetchData44: Function = async (url: string) => { //高阶函数 function compose45(...fns: Function[]): Function { - return fns.reduce((prev, curr) => (...args: Function[]) => curr.unSafeCall(prev.unSafeCall(...args)) as 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(); +f1.unsafeCall(); class AB3 { fn3: Function = () => {}; } let ab3 = new AB3(); -ab3.fn3.unSafeCall(); +ab3.fn3.unsafeCall(); const fn29: Function[] = []; -fn29[1].unSafeCall(); \ No newline at end of file +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 index ca5758bca2..b4e8db486e 100644 --- a/ets2panda/linter/test/main/explicit_function_type.ets.migrate.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.json @@ -143,6 +143,16 @@ "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" + }, + { + "line": 175, + "column": 1, + "endLine": 175, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/exponent.ets.autofix.json b/ets2panda/linter/test/main/exponent.ets.autofix.json index ee4e3b4662..cc6218a973 100644 --- a/ets2panda/linter/test/main/exponent.ets.autofix.json +++ b/ets2panda/linter/test/main/exponent.ets.autofix.json @@ -231,9 +231,9 @@ "problem": "NumericSemantics", "autofix": [ { - "start": 721, + "start": 720, "end": 722, - "replacementText": "1.0", + "replacementText": "-1.0", "line": 25, "column": 15, "endLine": 25, diff --git a/ets2panda/linter/test/main/extend_decorator_1.ets.arkts2.json b/ets2panda/linter/test/main/extend_decorator_1.ets.arkts2.json index d35d9872c4..66b998c943 100644 --- a/ets2panda/linter/test/main/extend_decorator_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.arkts2.json @@ -91,7 +91,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 25, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (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 6f96180e67..375b4f7440 100644 --- a/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json @@ -179,7 +179,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -200,7 +200,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -242,7 +242,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 c7c9c047cb..eee42f58f0 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 @@ -294,6 +294,16 @@ "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", "severity": "ERROR" }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 11, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, { "line": 78, "column": 37, diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets b/ets2panda/linter/test/main/func_inferred_type_args_2.ets index 636e016aea..0d7b3467d1 100644 --- a/ets2panda/linter/test/main/func_inferred_type_args_2.ets +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { AttributeUpdater } from '@kit.ArkUI'; const irreparableArr = new Array(); let repairableArr: Array = new Array(); @@ -37,7 +38,7 @@ repairableC.repairableSet = new Set(); repairableC.repairableMap = new Map(); MyClass.repairableStaticMap = new Map(); -const promise: Promise = new Promise(()=> {return ''}); +const promise: Promise = new Promise(() => { return ''; }); function testA(): Map { return new Map(); @@ -72,3 +73,24 @@ class MyClassB { return new Set(); } } + +const testMap: Map = new Map([ + ['123', 1], // my comment 1 + ['sfe', 2] // my comment 2 +]); +let a : Array = new Array(); +function foo(arr:Array) { } +foo(new Array()); +@Observed +export class AppIconCloneBadgeVm { + @Track public cloneBadgeModifier: AttributeUpdater = new AttributeUpdater(); +} +class B {} +class C {} +class A { + t:T; + constructor(t:T) { + this.t = t; + } +} +new A(new C()) 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 index 8332379fa7..bc1cd482a4 100644 --- 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 @@ -1,23 +1,23 @@ { "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT 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": 16, + "line": 17, "column": 7, - "endLine": 16, + "endLine": 17, "endColumn": 35, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 16, + "line": 17, "column": 24, - "endLine": 16, + "endLine": 17, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 17, + "line": 18, "column": 36, - "endLine": 17, + "endLine": 18, "endColumn": 47, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 19, "column": 17, - "endLine": 18, + "endLine": 19, "endColumn": 28, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 7, - "endLine": 20, + "endLine": 21, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 7, - "endLine": 20, + "endLine": 21, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 24, - "endLine": 20, + "endLine": 21, "endColumn": 33, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 22, "column": 44, - "endLine": 21, + "endLine": 22, "endColumn": 53, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 22, + "line": 23, "column": 17, - "endLine": 22, + "endLine": 23, "endColumn": 26, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 3, - "endLine": 25, + "endLine": 26, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 3, - "endLine": 25, + "endLine": 26, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 27, - "endLine": 25, + "endLine": 26, "endColumn": 36, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 27, "column": 10, - "endLine": 26, + "endLine": 27, "endColumn": 23, "problem": "StructuralIdentity", "suggest": "", @@ -145,9 +145,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 27, "column": 39, - "endLine": 26, + "endLine": 27, "endColumn": 48, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -155,9 +155,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 28, "column": 55, - "endLine": 27, + "endLine": 28, "endColumn": 64, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -165,9 +165,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 29, "column": 61, - "endLine": 28, + "endLine": 29, "endColumn": 70, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -175,9 +175,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 33, "column": 7, - "endLine": 32, + "endLine": 33, "endColumn": 35, "problem": "UnknownType", "suggest": "", @@ -185,9 +185,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 33, "column": 22, - "endLine": 32, + "endLine": 33, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -195,9 +195,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 35, "column": 38, - "endLine": 34, + "endLine": 35, "endColumn": 51, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -205,9 +205,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 36, "column": 30, - "endLine": 35, + "endLine": 36, "endColumn": 39, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -215,9 +215,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 37, "column": 29, - "endLine": 36, + "endLine": 37, "endColumn": 38, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -225,9 +225,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 38, "column": 29, - "endLine": 37, + "endLine": 38, "endColumn": 38, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -235,9 +235,9 @@ "severity": "ERROR" }, { - "line": 38, + "line": 39, "column": 31, - "endLine": 38, + "endLine": 39, "endColumn": 40, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -245,19 +245,29 @@ "severity": "ERROR" }, { - "line": 40, + "line": 41, "column": 34, - "endLine": 40, - "endColumn": 63, + "endLine": 41, + "endColumn": 67, "problem": "GenericCallNoTypeArgs", "suggest": "", "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, { - "line": 43, + "line": 44, + "column": 14, + "endLine": 44, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 44, "column": 10, - "endLine": 43, + "endLine": 44, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -265,9 +275,19 @@ "severity": "ERROR" }, { - "line": 47, + "line": 48, + "column": 14, + "endLine": 48, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 48, "column": 10, - "endLine": 47, + "endLine": 48, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -275,9 +295,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 52, "column": 10, - "endLine": 51, + "endLine": 52, "endColumn": 19, "problem": "StructuralIdentity", "suggest": "", @@ -285,9 +305,19 @@ "severity": "ERROR" }, { - "line": 51, + "line": 52, + "column": 14, + "endLine": 52, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 52, "column": 10, - "endLine": 51, + "endLine": 52, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -295,9 +325,9 @@ "severity": "ERROR" }, { - "line": 55, + "line": 56, "column": 10, - "endLine": 55, + "endLine": 56, "endColumn": 19, "problem": "StructuralIdentity", "suggest": "", @@ -305,9 +335,19 @@ "severity": "ERROR" }, { - "line": 55, + "line": 56, + "column": 14, + "endLine": 56, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 56, "column": 10, - "endLine": 55, + "endLine": 56, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -315,9 +355,19 @@ "severity": "ERROR" }, { - "line": 60, + "line": 61, + "column": 16, + "endLine": 61, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 61, "column": 12, - "endLine": 60, + "endLine": 61, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -325,9 +375,19 @@ "severity": "ERROR" }, { - "line": 64, + "line": 65, + "column": 16, + "endLine": 65, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 65, "column": 12, - "endLine": 64, + "endLine": 65, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -335,9 +395,9 @@ "severity": "ERROR" }, { - "line": 68, + "line": 69, "column": 12, - "endLine": 68, + "endLine": 69, "endColumn": 21, "problem": "StructuralIdentity", "suggest": "", @@ -345,9 +405,19 @@ "severity": "ERROR" }, { - "line": 68, + "line": 69, + "column": 16, + "endLine": 69, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 69, "column": 12, - "endLine": 68, + "endLine": 69, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -355,9 +425,9 @@ "severity": "ERROR" }, { - "line": 72, + "line": 73, "column": 12, - "endLine": 72, + "endLine": 73, "endColumn": 21, "problem": "StructuralIdentity", "suggest": "", @@ -365,14 +435,124 @@ "severity": "ERROR" }, { - "line": 72, + "line": 73, + "column": 16, + "endLine": 73, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 73, "column": 12, - "endLine": 72, + "endLine": 73, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" + }, + { + "line": 77, + "column": 38, + "endLine": 80, + "endColumn": 3, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 11, + "endLine": 78, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 11, + "endLine": 79, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 25, + "endLine": 81, + "endColumn": 36, + "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": 16, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 77, + "endLine": 86, + "endColumn": 93, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 2, + "endLine": 84, + "endColumn": 10, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Observed\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 4, + "endLine": 86, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Track\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 54, + "endLine": 86, + "endColumn": 69, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"CommonAttribute\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 94, + "endLine": 86, + "endColumn": 109, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"CommonAttribute\" should be imported before it is used (arkui-modular-interface)", + "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 index 773fea5ff8..e59af03e37 100644 --- 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 @@ -1,23 +1,23 @@ { "copyright": [ - "Copyright (c) 2025 Huawei Device Co., Ltd.", - "Licensed under the Apache License, Version 2.0 (the 'License');", - "you may not use this file except in compliance with the License.", - "You may obtain a copy of the License at", - "", - "http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an 'AS IS' BASIS,", - "WITHOUT 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": 16, + "line": 17, "column": 7, - "endLine": 16, + "endLine": 17, "endColumn": 35, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 16, + "line": 17, "column": 24, - "endLine": 16, + "endLine": 17, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -35,16 +35,20 @@ "severity": "ERROR" }, { - "line": 17, + "line": 18, "column": 36, - "endLine": 17, + "endLine": 18, "endColumn": 47, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 676, - "end": 687, - "replacementText": "new Array()" + "start": 732, + "end": 732, + "replacementText": "", + "line": 18, + "column": 36, + "endLine": 18, + "endColumn": 47 } ], "suggest": "", @@ -52,16 +56,20 @@ "severity": "ERROR" }, { - "line": 18, + "line": 19, "column": 17, - "endLine": 18, + "endLine": 19, "endColumn": 28, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 705, - "end": 716, - "replacementText": "new Array()" + "start": 761, + "end": 761, + "replacementText": "", + "line": 19, + "column": 17, + "endLine": 19, + "endColumn": 28 } ], "suggest": "", @@ -69,9 +77,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 7, - "endLine": 20, + "endLine": 21, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -79,9 +87,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 7, - "endLine": 20, + "endLine": 21, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -89,9 +97,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 24, - "endLine": 20, + "endLine": 21, "endColumn": 33, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -99,16 +107,20 @@ "severity": "ERROR" }, { - "line": 21, + "line": 22, "column": 44, - "endLine": 21, + "endLine": 22, "endColumn": 53, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 796, - "end": 805, - "replacementText": "new Map()" + "start": 850, + "end": 850, + "replacementText": "", + "line": 22, + "column": 44, + "endLine": 22, + "endColumn": 53 } ], "suggest": "", @@ -116,16 +128,20 @@ "severity": "ERROR" }, { - "line": 22, + "line": 23, "column": 17, - "endLine": 22, + "endLine": 23, "endColumn": 26, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 823, - "end": 832, - "replacementText": "new Map()" + "start": 877, + "end": 877, + "replacementText": "", + "line": 23, + "column": 17, + "endLine": 23, + "endColumn": 26 } ], "suggest": "", @@ -133,9 +149,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 3, - "endLine": 25, + "endLine": 26, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -143,9 +159,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 3, - "endLine": 25, + "endLine": 26, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -153,9 +169,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 27, - "endLine": 25, + "endLine": 26, "endColumn": 36, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -163,9 +179,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 27, "column": 10, - "endLine": 26, + "endLine": 27, "endColumn": 23, "problem": "StructuralIdentity", "suggest": "", @@ -173,9 +189,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 27, "column": 39, - "endLine": 26, + "endLine": 27, "endColumn": 48, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -183,16 +199,20 @@ "severity": "ERROR" }, { - "line": 27, + "line": 28, "column": 55, - "endLine": 27, + "endLine": 28, "endColumn": 64, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 994, - "end": 1003, - "replacementText": "new Map string[]>()" + "start": 1048, + "end": 1048, + "replacementText": " string[]>", + "line": 28, + "column": 55, + "endLine": 28, + "endColumn": 64 } ], "suggest": "", @@ -200,16 +220,20 @@ "severity": "ERROR" }, { - "line": 28, + "line": 29, "column": 61, - "endLine": 28, + "endLine": 29, "endColumn": 70, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1065, - "end": 1074, - "replacementText": "new Map string[]>()" + "start": 1119, + "end": 1119, + "replacementText": " string[]>", + "line": 29, + "column": 61, + "endLine": 29, + "endColumn": 70 } ], "suggest": "", @@ -217,9 +241,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 33, "column": 7, - "endLine": 32, + "endLine": 33, "endColumn": 35, "problem": "UnknownType", "suggest": "", @@ -227,9 +251,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 33, "column": 22, - "endLine": 32, + "endLine": 33, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -237,16 +261,20 @@ "severity": "ERROR" }, { - "line": 34, + "line": 35, "column": 38, - "endLine": 34, + "endLine": 35, "endColumn": 51, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1215, - "end": 1228, - "replacementText": "new MyClass()" + "start": 1273, + "end": 1273, + "replacementText": "", + "line": 35, + "column": 38, + "endLine": 35, + "endColumn": 51 } ], "suggest": "", @@ -254,9 +282,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 36, "column": 30, - "endLine": 35, + "endLine": 36, "endColumn": 39, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -264,16 +292,20 @@ "severity": "ERROR" }, { - "line": 36, + "line": 37, "column": 29, - "endLine": 36, + "endLine": 37, "endColumn": 38, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1298, - "end": 1307, - "replacementText": "new Set()" + "start": 1352, + "end": 1352, + "replacementText": "", + "line": 37, + "column": 29, + "endLine": 37, + "endColumn": 38 } ], "suggest": "", @@ -281,16 +313,20 @@ "severity": "ERROR" }, { - "line": 37, + "line": 38, "column": 29, - "endLine": 37, + "endLine": 38, "endColumn": 38, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1337, - "end": 1346, - "replacementText": "new Map string[]>()" + "start": 1391, + "end": 1391, + "replacementText": " string[]>", + "line": 38, + "column": 29, + "endLine": 38, + "endColumn": 38 } ], "suggest": "", @@ -298,16 +334,20 @@ "severity": "ERROR" }, { - "line": 38, + "line": 39, "column": 31, - "endLine": 38, + "endLine": 39, "endColumn": 40, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1378, - "end": 1387, - "replacementText": "new Map string[]>()" + "start": 1432, + "end": 1432, + "replacementText": " string[]>", + "line": 39, + "column": 31, + "endLine": 39, + "endColumn": 40 } ], "suggest": "", @@ -315,16 +355,20 @@ "severity": "ERROR" }, { - "line": 40, + "line": 41, "column": 34, - "endLine": 40, - "endColumn": 63, + "endLine": 41, + "endColumn": 67, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1423, - "end": 1452, - "replacementText": "new Promise(() => { return ''; })" + "start": 1481, + "end": 1481, + "replacementText": "", + "line": 41, + "column": 34, + "endLine": 41, + "endColumn": 67 } ], "suggest": "", @@ -332,16 +376,30 @@ "severity": "ERROR" }, { - "line": 43, + "line": 44, + "column": 14, + "endLine": 44, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 44, "column": 10, - "endLine": 43, + "endLine": 44, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1504, - "end": 1513, - "replacementText": "new Map()" + "start": 1562, + "end": 1562, + "replacementText": "", + "line": 44, + "column": 10, + "endLine": 44, + "endColumn": 19 } ], "suggest": "", @@ -349,16 +407,30 @@ "severity": "ERROR" }, { - "line": 47, + "line": 48, + "column": 14, + "endLine": 48, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 48, "column": 10, - "endLine": 47, + "endLine": 48, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1582, - "end": 1591, - "replacementText": "new Map()" + "start": 1640, + "end": 1640, + "replacementText": "", + "line": 48, + "column": 10, + "endLine": 48, + "endColumn": 19 } ], "suggest": "", @@ -366,9 +438,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 52, "column": 10, - "endLine": 51, + "endLine": 52, "endColumn": 19, "problem": "StructuralIdentity", "suggest": "", @@ -376,9 +448,19 @@ "severity": "ERROR" }, { - "line": 51, + "line": 52, + "column": 14, + "endLine": 52, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 52, "column": 10, - "endLine": 51, + "endLine": 52, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -386,9 +468,9 @@ "severity": "ERROR" }, { - "line": 55, + "line": 56, "column": 10, - "endLine": 55, + "endLine": 56, "endColumn": 19, "problem": "StructuralIdentity", "suggest": "", @@ -396,9 +478,19 @@ "severity": "ERROR" }, { - "line": 55, + "line": 56, + "column": 14, + "endLine": 56, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 56, "column": 10, - "endLine": 55, + "endLine": 56, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -406,16 +498,30 @@ "severity": "ERROR" }, { - "line": 60, + "line": 61, + "column": 16, + "endLine": 61, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 61, "column": 12, - "endLine": 60, + "endLine": 61, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1798, - "end": 1807, - "replacementText": "new Map()" + "start": 1856, + "end": 1856, + "replacementText": "", + "line": 61, + "column": 12, + "endLine": 61, + "endColumn": 21 } ], "suggest": "", @@ -423,16 +529,30 @@ "severity": "ERROR" }, { - "line": 64, + "line": 65, + "column": 16, + "endLine": 65, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 65, "column": 12, - "endLine": 64, + "endLine": 65, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "autofix": [ { - "start": 1873, - "end": 1882, - "replacementText": "new Map()" + "start": 1931, + "end": 1931, + "replacementText": "", + "line": 65, + "column": 12, + "endLine": 65, + "endColumn": 21 } ], "suggest": "", @@ -440,9 +560,9 @@ "severity": "ERROR" }, { - "line": 68, + "line": 69, "column": 12, - "endLine": 68, + "endLine": 69, "endColumn": 21, "problem": "StructuralIdentity", "suggest": "", @@ -450,9 +570,19 @@ "severity": "ERROR" }, { - "line": 68, + "line": 69, + "column": 16, + "endLine": 69, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 69, "column": 12, - "endLine": 68, + "endLine": 69, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -460,9 +590,9 @@ "severity": "ERROR" }, { - "line": 72, + "line": 73, "column": 12, - "endLine": 72, + "endLine": 73, "endColumn": 21, "problem": "StructuralIdentity", "suggest": "", @@ -470,14 +600,223 @@ "severity": "ERROR" }, { - "line": 72, + "line": 73, + "column": 16, + "endLine": 73, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 73, "column": 12, - "endLine": 72, + "endLine": 73, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" + }, + { + "line": 77, + "column": 38, + "endLine": 80, + "endColumn": 3, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 2121, + "end": 2121, + "replacementText": "", + "line": 77, + "column": 38, + "endLine": 80, + "endColumn": 3 + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 11, + "endLine": 78, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2134, + "end": 2135, + "replacementText": "1.0", + "line": 78, + "column": 11, + "endLine": 78, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 11, + "endLine": 79, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2164, + "end": 2165, + "replacementText": "2.0", + "line": 79, + "column": 11, + "endLine": 79, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 25, + "endLine": 81, + "endColumn": 36, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 2220, + "end": 2220, + "replacementText": "", + "line": 81, + "column": 25, + "endLine": 81, + "endColumn": 36 + } + ], + "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": 16, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 2264, + "end": 2275, + "replacementText": "new Array()", + "line": 83, + "column": 5, + "endLine": 83, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 77, + "endLine": 86, + "endColumn": 93, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 2, + "endLine": 84, + "endColumn": 10, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Track, CommonAttribute } from '@kit.ArkUI';\n", + "line": 86, + "column": 94, + "endLine": 86, + "endColumn": 109 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Observed\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 4, + "endLine": 86, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Track, CommonAttribute } from '@kit.ArkUI';\n", + "line": 86, + "column": 94, + "endLine": 86, + "endColumn": 109 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Track\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 54, + "endLine": 86, + "endColumn": 69, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Track, CommonAttribute } from '@kit.ArkUI';\n", + "line": 86, + "column": 94, + "endLine": 86, + "endColumn": 109 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"CommonAttribute\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 94, + "endLine": 86, + "endColumn": 109, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Observed, Track, CommonAttribute } from '@kit.ArkUI';\n", + "line": 86, + "column": 94, + "endLine": 86, + "endColumn": 109 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"CommonAttribute\" should be imported before it is used (arkui-modular-interface)", + "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 index 1f00081d43..616182be4e 100644 --- a/ets2panda/linter/test/main/func_inferred_type_args_2.ets.json +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 16, + "line": 17, "column": 7, - "endLine": 16, + "endLine": 17, "endColumn": 35, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 7, - "endLine": 20, + "endLine": 21, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 21, "column": 7, - "endLine": 20, + "endLine": 21, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 3, - "endLine": 25, + "endLine": 26, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 26, "column": 3, - "endLine": 25, + "endLine": 26, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 33, "column": 7, - "endLine": 32, + "endLine": 33, "endColumn": 35, "problem": "UnknownType", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 33, "column": 22, - "endLine": 32, + "endLine": 33, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 52, "column": 10, - "endLine": 51, + "endLine": 52, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 55, + "line": 56, "column": 10, - "endLine": 55, + "endLine": 56, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 68, + "line": 69, "column": 12, - "endLine": 68, + "endLine": 69, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 72, + "line": 73, "column": 12, - "endLine": 72, + "endLine": 73, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", 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 index 01a5d89f97..f76d33da37 100644 --- 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 @@ -13,6 +13,10 @@ * limitations under the License. */ +import { Observed, Track, CommonAttribute } from '@kit.ArkUI'; + +import { AttributeUpdater } from '@kit.ArkUI'; + const irreparableArr = new Array(); let repairableArr: Array = new Array(); repairableArr = new Array(); @@ -72,3 +76,24 @@ class MyClassB { return new Set(); } } + +const testMap: Map = new Map([ + ['123', 1.0], // my comment 1 + ['sfe', 2.0] // my comment 2 +]); +let a : Array = new Array(); +function foo(arr:Array) { } +foo(new Array()); +@Observed +export class AppIconCloneBadgeVm { + @Track public cloneBadgeModifier: AttributeUpdater = new AttributeUpdater(); +} +class B {} +class C {} +class A { + t:T; + constructor(t:T) { + this.t = t; + } +} +new A(new C()) 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 index a3d92d0d96..7926f03ac9 100644 --- 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 @@ -15,9 +15,9 @@ ], "result": [ { - "line": 16, + "line": 20, "column": 7, - "endLine": 16, + "endLine": 20, "endColumn": 35, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 16, + "line": 20, "column": 24, - "endLine": 16, + "endLine": 20, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 24, "column": 7, - "endLine": 20, + "endLine": 24, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 24, "column": 7, - "endLine": 20, + "endLine": 24, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 24, "column": 24, - "endLine": 20, + "endLine": 24, "endColumn": 33, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 29, "column": 3, - "endLine": 25, + "endLine": 29, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 29, "column": 3, - "endLine": 25, + "endLine": 29, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 25, + "line": 29, "column": 27, - "endLine": 25, + "endLine": 29, "endColumn": 36, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 30, "column": 10, - "endLine": 26, + "endLine": 30, "endColumn": 23, "problem": "StructuralIdentity", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 30, "column": 39, - "endLine": 26, + "endLine": 30, "endColumn": 48, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 36, "column": 7, - "endLine": 32, + "endLine": 36, "endColumn": 35, "problem": "UnknownType", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 36, "column": 22, - "endLine": 32, + "endLine": 36, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -135,19 +135,39 @@ "severity": "ERROR" }, { - "line": 35, + "line": 39, "column": 30, - "endLine": 35, + "endLine": 39, "endColumn": 39, "problem": "GenericCallNoTypeArgs", "suggest": "", "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, + { + "line": 47, + "column": 14, + "endLine": 47, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, { "line": 51, - "column": 10, + "column": 14, "endLine": 51, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 10, + "endLine": 55, "endColumn": 19, "problem": "StructuralIdentity", "suggest": "", @@ -155,9 +175,19 @@ "severity": "ERROR" }, { - "line": 51, + "line": 55, + "column": 14, + "endLine": 55, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 55, "column": 10, - "endLine": 51, + "endLine": 55, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -165,9 +195,9 @@ "severity": "ERROR" }, { - "line": 55, + "line": 59, "column": 10, - "endLine": 55, + "endLine": 59, "endColumn": 19, "problem": "StructuralIdentity", "suggest": "", @@ -175,19 +205,49 @@ "severity": "ERROR" }, { - "line": 55, + "line": 59, + "column": 14, + "endLine": 59, + "endColumn": 17, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 59, "column": 10, - "endLine": 55, + "endLine": 59, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, + { + "line": 64, + "column": 16, + "endLine": 64, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, { "line": 68, - "column": 12, + "column": 16, "endLine": 68, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 12, + "endLine": 72, "endColumn": 21, "problem": "StructuralIdentity", "suggest": "", @@ -195,9 +255,19 @@ "severity": "ERROR" }, { - "line": 68, + "line": 72, + "column": 16, + "endLine": 72, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 72, "column": 12, - "endLine": 68, + "endLine": 72, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -205,9 +275,9 @@ "severity": "ERROR" }, { - "line": 72, + "line": 76, "column": 12, - "endLine": 72, + "endLine": 76, "endColumn": 21, "problem": "StructuralIdentity", "suggest": "", @@ -215,14 +285,34 @@ "severity": "ERROR" }, { - "line": 72, + "line": 76, + "column": 16, + "endLine": 76, + "endColumn": 19, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 76, "column": 12, - "endLine": 72, + "endLine": 76, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" + }, + { + "line": 89, + "column": 77, + "endLine": 89, + "endColumn": 93, + "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/global_this.ets.args.json b/ets2panda/linter/test/main/global_this.ets.args.json index a89d885810..4d93062f69 100644 --- a/ets2panda/linter/test/main/global_this.ets.args.json +++ b/ets2panda/linter/test/main/global_this.ets.args.json @@ -14,8 +14,6 @@ "limitations under the License." ], "mode": { - "arkts2": "", - "autofix": "--arkts-2", - "migrate": "--arkts-2" + "arkts2": "" } } diff --git a/ets2panda/linter/test/main/index_negative.ets.arkts2.json b/ets2panda/linter/test/main/index_negative.ets.arkts2.json index d1daebd5f8..522db19434 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": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 17, + "column": 15, + "endLine": 17, + "endColumn": 26, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 18, "column": 5, @@ -84,6 +94,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 18, + "column": 16, + "endLine": 18, + "endColumn": 28, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 19, "column": 1, @@ -94,6 +114,36 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 19, + "column": 1, + "endLine": 19, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 1, + "endLine": 21, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 21, "column": 10, @@ -154,6 +204,26 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 28, + "column": 9, + "endLine": 28, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 21, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 32, "column": 1, @@ -184,6 +254,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 37, + "column": 1, + "endLine": 37, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 38, "column": 1, @@ -194,6 +274,26 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 14, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 1, + "endLine": 39, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 39, "column": 5, @@ -204,6 +304,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 40, + "column": 1, + "endLine": 40, + "endColumn": 14, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 40, "column": 5, @@ -234,6 +344,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 42, + "column": 1, + "endLine": 42, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 42, "column": 5, @@ -244,6 +364,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 44, + "column": 1, + "endLine": 44, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 44, "column": 5, @@ -254,6 +384,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 45, + "column": 1, + "endLine": 45, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 45, "column": 5, @@ -264,6 +404,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 47, + "column": 1, + "endLine": 47, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 47, "column": 5, @@ -274,6 +424,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 48, + "column": 1, + "endLine": 48, + "endColumn": 14, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 48, "column": 5, @@ -294,6 +454,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 50, + "column": 1, + "endLine": 50, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 50, "column": 5, @@ -314,6 +484,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 52, + "column": 1, + "endLine": 52, + "endColumn": 15, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 52, "column": 5, @@ -324,6 +504,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 53, + "column": 1, + "endLine": 53, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 53, "column": 5, @@ -344,6 +534,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 54, + "column": 1, + "endLine": 54, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 54, "column": 5, @@ -354,6 +554,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 56, + "column": 1, + "endLine": 56, + "endColumn": 31, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 56, "column": 6, @@ -374,6 +584,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 57, + "column": 1, + "endLine": 57, + "endColumn": 29, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 57, "column": 5, @@ -384,6 +604,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 58, + "column": 1, + "endLine": 58, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 58, "column": 5, @@ -394,6 +624,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 59, + "column": 1, + "endLine": 59, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 59, "column": 5, @@ -414,6 +654,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 60, + "column": 1, + "endLine": 60, + "endColumn": 17, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 60, "column": 5, @@ -434,6 +684,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 61, + "column": 1, + "endLine": 61, + "endColumn": 16, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 61, "column": 5, @@ -454,6 +714,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 63, + "column": 1, + "endLine": 63, + "endColumn": 31, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 63, "column": 6, @@ -464,6 +734,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 31, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 65, "column": 1, @@ -474,6 +754,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 65, + "column": 1, + "endLine": 65, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 65, "column": 5, @@ -494,6 +784,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 66, + "column": 1, + "endLine": 66, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 66, "column": 5, @@ -514,6 +814,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 68, + "column": 1, + "endLine": 68, + "endColumn": 31, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 68, "column": 5, @@ -524,6 +834,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 69, + "column": 1, + "endLine": 69, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 69, "column": 5, @@ -534,6 +854,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 70, "column": 5, @@ -554,6 +884,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 31, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 72, "column": 5, @@ -574,6 +914,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 73, "column": 5, @@ -724,6 +1074,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 80, + "column": 1, + "endLine": 80, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 80, "column": 5, @@ -734,6 +1094,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 81, "column": 5, @@ -754,6 +1124,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 82, + "column": 1, + "endLine": 82, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 82, "column": 5, @@ -774,6 +1154,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 83, + "column": 1, + "endLine": 83, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 83, "column": 5, @@ -784,6 +1174,16 @@ "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", "severity": "ERROR" }, + { + "line": 84, + "column": 1, + "endLine": 84, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 84, "column": 5, @@ -804,6 +1204,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 85, + "column": 1, + "endLine": 85, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 85, "column": 5, @@ -844,6 +1254,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 87, + "column": 1, + "endLine": 87, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 87, "column": 5, @@ -858,7 +1278,7 @@ "line": 88, "column": 5, "endLine": 88, - "endColumn": 7, + "endColumn": 17, "problem": "ArrayIndexExprType", "suggest": "", "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", @@ -874,11 +1294,21 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 89, + "column": 1, + "endLine": 89, + "endColumn": 18, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 89, "column": 5, "endLine": 89, - "endColumn": 7, + "endColumn": 17, "problem": "ArrayIndexExprType", "suggest": "", "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", @@ -898,7 +1328,7 @@ "line": 90, "column": 5, "endLine": 90, - "endColumn": 7, + "endColumn": 17, "problem": "ArrayIndexExprType", "suggest": "", "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", @@ -924,6 +1354,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 91, + "column": 1, + "endLine": 91, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 91, "column": 5, @@ -944,6 +1384,16 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 92, + "column": 1, + "endLine": 92, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 92, "column": 5, @@ -974,6 +1424,26 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 96, + "column": 11, + "endLine": 96, + "endColumn": 24, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 11, + "endLine": 97, + "endColumn": 25, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 97, "column": 15, @@ -1014,11 +1484,21 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 99, + "column": 1, + "endLine": 99, + "endColumn": 25, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 99, "column": 5, "endLine": 99, - "endColumn": 14, + "endColumn": 24, "problem": "ArrayIndexExprType", "suggest": "", "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", @@ -1034,11 +1514,21 @@ "rule": "The index expression must be zero or positive value.(arkts-array-index-negative)", "severity": "ERROR" }, + { + "line": 100, + "column": 1, + "endLine": 100, + "endColumn": 19, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 100, "column": 5, "endLine": 100, - "endColumn": 8, + "endColumn": 18, "problem": "ArrayIndexExprType", "suggest": "", "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", 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 953e84542d..37724c0f17 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.arkts2.json @@ -81,7 +81,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -161,7 +161,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -171,7 +171,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -181,7 +181,7 @@ "endColumn": 18, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AnimatableExtend\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -191,7 +191,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -201,7 +201,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -211,7 +211,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ "endColumn": 44, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ImageFit\" should be imported before it is used (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 deacf76eb3..3379f754c7 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json @@ -158,7 +158,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -179,7 +179,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -200,7 +200,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -242,7 +242,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -263,7 +263,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -284,7 +284,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -305,7 +305,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -326,7 +326,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -347,7 +347,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -368,7 +368,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AnimatableExtend\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -389,7 +389,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -410,7 +410,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -431,7 +431,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -452,7 +452,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ImageFit\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/interface_import_3.ets.arkts2.json b/ets2panda/linter/test/main/interface_import_3.ets.arkts2.json index 680b868bc1..1f8aa52d84 100644 --- a/ets2panda/linter/test/main/interface_import_3.ets.arkts2.json +++ b/ets2panda/linter/test/main/interface_import_3.ets.arkts2.json @@ -41,7 +41,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/interface_import_3.ets.autofix.json b/ets2panda/linter/test/main/interface_import_3.ets.autofix.json index 8bb6863157..a149f61d6c 100644 --- a/ets2panda/linter/test/main/interface_import_3.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_3.ets.autofix.json @@ -52,7 +52,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -73,7 +73,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/interface_import_4.ets b/ets2panda/linter/test/main/interface_import_4.ets new file mode 100644 index 0000000000..f682328f82 --- /dev/null +++ b/ets2panda/linter/test/main/interface_import_4.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. + */ + +@Entry +@ComponentV2 +struct MyComponent { + @Local arr: Array = []; + scroller: Scroller = new Scroller(); + build() { + Column({ space: 5 }) { + List({ scroller: this.scroller, space: 5, initialIndex: 100 }) { + Repeat(this.arr) + .virtualScroll({ + onTotalCount: () => { return 1000; }, + onLazyLoading: (index: number) => { this.arr[index] = index.toString(); } + }) + .each((obj: RepeatItem) => { + ListItem() { + Row({ space: 5 }) { + Text(`${obj.index}: Item_${obj.item}`) + } + } + .height(50) + }) + } + .height('80%') + .border({ width: 1}) + Button('ScrollToIndex 500') + .onClick(() => { this.scroller.scrollToIndex(500); }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_4.ets.args.json b/ets2panda/linter/test/main/interface_import_4.ets.args.json new file mode 100644 index 0000000000..ef3938e967 --- /dev/null +++ b/ets2panda/linter/test/main/interface_import_4.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/interface_import_4.ets.arkts2.json b/ets2panda/linter/test/main/interface_import_4.ets.arkts2.json new file mode 100644 index 0000000000..846e6e009e --- /dev/null +++ b/ets2panda/linter/test/main/interface_import_4.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": 20, + "column": 28, + "endLine": 20, + "endColumn": 36, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 21, + "endLine": 22, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 46, + "endLine": 23, + "endColumn": 47, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 63, + "endLine": 23, + "endColumn": 66, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 42, + "endLine": 26, + "endColumn": 46, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 58, + "endLine": 27, + "endColumn": 63, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 28, + "endLine": 31, + "endColumn": 29, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 21, + "endLine": 35, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 24, + "endLine": 39, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 54, + "endLine": 41, + "endColumn": 57, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 4, + "endLine": 19, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 13, + "endLine": 20, + "endColumn": 21, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Scroller\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 28, + "endLine": 20, + "endColumn": 36, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Scroller\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 7, + "endLine": 23, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"List\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 9, + "endLine": 24, + "endColumn": 15, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Repeat\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 23, + "endLine": 29, + "endColumn": 33, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"RepeatItem\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 13, + "endLine": 30, + "endColumn": 21, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"ListItem\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 15, + "endLine": 31, + "endColumn": 18, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 17, + "endLine": 32, + "endColumn": 21, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/interface_import_4.ets.autofix.json b/ets2panda/linter/test/main/interface_import_4.ets.autofix.json new file mode 100644 index 0000000000..1ba9932fa3 --- /dev/null +++ b/ets2panda/linter/test/main/interface_import_4.ets.autofix.json @@ -0,0 +1,490 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 28, + "endLine": 20, + "endColumn": 36, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 21, + "endLine": 22, + "endColumn": 22, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 751, + "end": 752, + "replacementText": "5.0", + "line": 22, + "column": 21, + "endLine": 22, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 46, + "endLine": 23, + "endColumn": 47, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 803, + "end": 804, + "replacementText": "5.0", + "line": 23, + "column": 46, + "endLine": 23, + "endColumn": 47 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 63, + "endLine": 23, + "endColumn": 66, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 820, + "end": 823, + "replacementText": "100.0", + "line": 23, + "column": 63, + "endLine": 23, + "endColumn": 66 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 42, + "endLine": 26, + "endColumn": 46, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 922, + "end": 926, + "replacementText": "1000.0", + "line": 26, + "column": 42, + "endLine": 26, + "endColumn": 46 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 58, + "endLine": 27, + "endColumn": 63, + "problem": "ArrayIndexExprType", + "autofix": [ + { + "start": 988, + "end": 993, + "replacementText": "index as int", + "line": 27, + "column": 58, + "endLine": 27, + "endColumn": 63 + } + ], + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 28, + "endLine": 31, + "endColumn": 29, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1129, + "end": 1130, + "replacementText": "5.0", + "line": 31, + "column": 28, + "endLine": 31, + "endColumn": 29 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 21, + "endLine": 35, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1241, + "end": 1243, + "replacementText": "50.0", + "line": 35, + "column": 21, + "endLine": 35, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 24, + "endLine": 39, + "endColumn": 25, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1310, + "end": 1311, + "replacementText": "1.0", + "line": 39, + "column": 24, + "endLine": 39, + "endColumn": 25 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 54, + "endLine": 41, + "endColumn": 57, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1401, + "end": 1404, + "replacementText": "500.0", + "line": 41, + "column": 54, + "endLine": 41, + "endColumn": 57 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 4, + "endLine": 19, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 13, + "endLine": 20, + "endColumn": 21, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Scroller\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 28, + "endLine": 20, + "endColumn": 36, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Scroller\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 5, + "endLine": 22, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 7, + "endLine": 23, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"List\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 9, + "endLine": 24, + "endColumn": 15, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Repeat\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 23, + "endLine": 29, + "endColumn": 33, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"RepeatItem\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 13, + "endLine": 30, + "endColumn": 21, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"ListItem\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 15, + "endLine": 31, + "endColumn": 18, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 17, + "endLine": 32, + "endColumn": 21, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "line": 40, + "column": 7, + "endLine": 40, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "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/interface_import_4.ets.json similarity index 100% rename from ets2panda/linter/test/main/prop_name_from_value.ets.json rename to ets2panda/linter/test/main/interface_import_4.ets.json diff --git a/ets2panda/linter/test/main/interface_import_4.ets.migrate.ets b/ets2panda/linter/test/main/interface_import_4.ets.migrate.ets new file mode 100644 index 0000000000..0087934e5c --- /dev/null +++ b/ets2panda/linter/test/main/interface_import_4.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 { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct MyComponent { + @Local arr: Array = []; + scroller: Scroller = new Scroller(); + build() { + Column({ space: 5.0 }) { + List({ scroller: this.scroller, space: 5.0, initialIndex: 100.0 }) { + Repeat(this.arr) + .virtualScroll({ + onTotalCount: () => { return 1000.0; }, + onLazyLoading: (index: number) => { this.arr[index as int] = index.toString(); } + }) + .each((obj: RepeatItem) => { + ListItem() { + Row({ space: 5.0 }) { + Text(`${obj.index}: Item_${obj.item}`) + } + } + .height(50.0) + }) + } + .height('80%') + .border({ width: 1.0}) + Button('ScrollToIndex 500') + .onClick(() => { this.scroller.scrollToIndex(500.0); }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json b/ets2panda/linter/test/main/interface_import_4.ets.migrate.json similarity index 75% rename from ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json rename to ets2panda/linter/test/main/interface_import_4.ets.migrate.json index 4218268d31..1aecbf6f53 100644 --- a/ets2panda/linter/test/main/prop_name_from_value.ets.arkts2.json +++ b/ets2panda/linter/test/main/interface_import_4.ets.migrate.json @@ -15,13 +15,13 @@ ], "result": [ { - "line": 23, - "column": 13, - "endLine": 23, - "endColumn": 20, - "problem": "UnsupportPropNameFromValue", + "line": 22, + "column": 28, + "endLine": 22, + "endColumn": 36, + "problem": "DynamicCtorCall", "suggest": "", - "rule": "Enum cannot get member name by member value (arkts-unsupport-prop-name-from-value)", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json b/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json index 2999205f95..8d294f2636 100644 --- a/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json +++ b/ets2panda/linter/test/main/invalid_identifier.ets.arkts2.json @@ -24,6 +24,16 @@ "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 56, + "problem": "InterOpImportJs", + "suggest": "", + "rule": "Importing directly from \"JS\" module is not supported (arkts-interop-js2s-import-js)", + "severity": "ERROR" + }, { "line": 18, "column": 8, @@ -784,6 +794,16 @@ "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, + { + "line": 205, + "column": 12, + "endLine": 205, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 206, "column": 3, @@ -794,6 +814,16 @@ "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, + { + "line": 206, + "column": 9, + "endLine": 206, + "endColumn": 10, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 209, "column": 11, @@ -841,7 +871,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -851,7 +881,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -861,7 +891,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -871,7 +901,7 @@ "endColumn": 22, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"RelativeContainer\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -881,7 +911,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -891,7 +921,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -901,7 +931,7 @@ "endColumn": 22, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"RelativeContainer\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -911,7 +941,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/limit_void_type.ets b/ets2panda/linter/test/main/limit_void_type.ets index d6ae5d427f..7cb24cf7cf 100644 --- a/ets2panda/linter/test/main/limit_void_type.ets +++ b/ets2panda/linter/test/main/limit_void_type.ets @@ -15,48 +15,48 @@ // Example 1: Basic function -function func1(): void {} +function func1(): void { } let a: void = func1(); // Example 2: Arrow function -const func2 = (): void => {}; +const func2 = (): void => { }; let b: void = func2(); // Example 3: Class method class Demo { - method(): void {} + method(): void { } } let c: void = new Demo().method(); // Example 4: Immediately Invoked Function Expression (IIFE) -let d: void = (function(): void {})(); +let d: void = (function (): void { })(); // Example 5: Asynchronous function -async function asyncFunc(): Promise {} +async function asyncFunc(): Promise { } let e: void = await asyncFunc(); // Example 6: Function parameter function wrapper(fn: () => void) { let f: void = fn(); } // Example 7: Type assertion -function func3(): void {} +function func3(): void { } let g: void = func3() as void; // Example 8: Callback function -setTimeout((): void => {}, 1000); -let h: void = setTimeout(() => {}, 1000); +setTimeout((): void => { }, 1000); +let h: void = setTimeout(() => { }, 1000); // Example 9: Array operation -const funcArr: (() => void)[] = [() => {}]; +const funcArr: (() => void)[] = [() => { }]; let i: void = funcArr[0](); // Example 10: Object method const obj = { - action: (): void => {} + action: (): void => { } }; let j: void = obj.action(); // Example 11: Strict mode // @ts-strict -function func4(): void {} +function func4(): void { } let k: void = func4(); // Example 12: Module export -export function exportedFunc(): void {} +export function exportedFunc(): void { } let l: void = exportedFunc(); // Example 13: Generic function -function genericFunc(): void {} +function genericFunc(): void { } let m: void = genericFunc(); // Example 14: Function overloading function overloadFunc(): void; @@ -65,24 +65,24 @@ function overloadFunc(n?: number) { return n; } let n: void = overloadFunc(); // Example 15: Type alias type VoidFunc = () => void; -const aliasFunc: VoidFunc = () => {}; +const aliasFunc: VoidFunc = () => { }; let o: void = aliasFunc(); // Example 16: Interface implementation interface Task { run(): void; } class Printer implements Task { - run(): void {} + run(): void { } } let p: void = new Printer().run(); // Example 17: Optional parameter -function withParam(param?: string): void {} +function withParam(param?: string): void { } let q: void = withParam(); // Example 18: Rest parameter -function sum(...nums: number[]): void {} +function sum(...nums: number[]): void { } let r: void = sum(1, 2, 3); // Example 19: This parameter -function withThis(this: Window): void {} +function withThis(this: Window): void { } let s: void = withThis.call(window); // Example 20: Generator function function* genFunc(): Generator { @@ -90,31 +90,31 @@ function* genFunc(): Generator { } let u: void = genFunc().next().value; // Example 21: Function currying -const curry = () => (): void => {}; +const curry = () => (): void => { }; let w: void = curry()(); // Example 22: Method chaining class Chain { first(): this { return this; } - last(): void {} + last(): void { } } let x: void = new Chain().first().last(); // Example 23: Destructuring assignment -const [func] = [(): void => {}]; +const [func] = [(): void => { }]; let y: void = func(); // Example 24: Type mapping type Wrapper = { value: T }; -const wrapped: Wrapper<() => void> = { value: () => {} }; +const wrapped: Wrapper<() => void> = { value: () => { } }; let z: void = wrapped.value(); // Example 25: Conditional type type Conditional = T extends boolean ? () => void : never; -const condFunc: Conditional = () => {}; +const condFunc: Conditional = () => { }; let aa: void = condFunc(); // Example 26: Mixed type interface Mixed { (): void; prop: string; } -const mixed: Mixed = Object.assign(() => {}, { prop: "" }); +const mixed: Mixed = Object.assign(() => { }, { prop: "" }); let ab: void = mixed(); // Example 27: Recursive call function recursive(): void { @@ -123,13 +123,13 @@ function recursive(): void { let ac: void = recursive(); // Example 28: Decorator function function decorator() { - return function(target: any) {}; + return function (target: any) { }; } @decorator() -class Decorated {} +class Decorated { } let ad: void = decorator()(Decorated); -function f1(): void {} +function f1(): void { } let a1 = f1(); // type `void` is used as value @@ -145,24 +145,24 @@ a3[0] = f1(); // type `void` is used as value let a4: void = f1(); // type `void` is used as type annotation -function f2(a: void) {} // type `void` is used as type annotation +function f2(a: void) { } // type `void` is used as type annotation f2(f1()); // type `void` is used as value class A { f: void; // type `void` is used as type annotation - m(p: void) {} // type `void` is used as type annotation + m(p: void) { } // type `void` is used as type annotation constructor(a: void) { // type `void` is used as type annotation this.f = a; } } -function f3(): void | Promise {} // type `void` is not allowed in union type +function f3(): void | Promise { } // type `void` is not allowed in union type class B { - m(): void | number {} // type `void` is not allowed in union type + m(): void | number { } // type `void` is not allowed in union type } type ss = void; @@ -178,20 +178,20 @@ interface BT { } class C { - private cc?:BT; + private cc?: BT; - private d():void { + private d(): void { this.cc = { - qaq: (caller?:string):void => this.qaqq(caller) + qaq: (caller?: string): void => this.qaqq(caller) } } - private qaqq(caller?:string):void { + private qaqq(caller?: string): void { return; } } -function foo(): void {} -function bar(): void {} +function foo(): void { } +function bar(): void { } let aa = '1'; let bb = aa === '1' ? foo() : bar(); // Error @@ -199,7 +199,65 @@ 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; +interface testB { + u: void; // Error + fooIf(): void; +} + +function foo1():void{ + return foo(); // No Error +} + +function foocfe(a: number): string | void { + if (a >= 0) { + return "a >= 0"; + } +} + +function foocfe2(a: number): string | void { + if (a < 0) { + return; + } + return "a >= 0"; +} +function fooefc(): void { } +let ss: void = foo() +let t: void | number = foo() +let t2: void | number = 1; + +function greet(hour: number): string | void { + if (hour < 12) { + return; + } else if (hour < 18) { + return "Good afternoon"; + } else { + return; + } +} + +function logOrReturn(flag: boolean): string | void { + if (flag) { + return "Flag is true"; + } + console.log("Flag is false"); + return; +} + +function justLogs(): string | void { + console.log("Hello!"); +} + +function getStatus(code: number): string | void { + switch (code) { + case 1: return "OK"; + case 2: return "Warning"; + } +} + +function tryThing(): string | void { + try { + return "Worked!"; + } catch (e) { + console.error(e); + } } \ No newline at end of file diff --git a/ets2panda/linter/test/main/limit_void_type.ets.args.json b/ets2panda/linter/test/main/limit_void_type.ets.args.json index 948b846fe0..571ee6bb76 100644 --- a/ets2panda/linter/test/main/limit_void_type.ets.args.json +++ b/ets2panda/linter/test/main/limit_void_type.ets.args.json @@ -1,19 +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": "" - } + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT 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/limit_void_type.ets.arkts2.json b/ets2panda/linter/test/main/limit_void_type.ets.arkts2.json index 39d24845a6..0ae2dd16e4 100644 --- a/ets2panda/linter/test/main/limit_void_type.ets.arkts2.json +++ b/ets2panda/linter/test/main/limit_void_type.ets.arkts2.json @@ -88,7 +88,7 @@ "line": 29, "column": 15, "endLine": 29, - "endColumn": 38, + "endColumn": 40, "problem": "LimitedVoidType", "suggest": "", "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", @@ -98,7 +98,7 @@ "line": 29, "column": 16, "endLine": 29, - "endColumn": 35, + "endColumn": 37, "problem": "FunctionExpression", "suggest": "", "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", @@ -156,9 +156,9 @@ }, { "line": 41, - "column": 28, + "column": 29, "endLine": 41, - "endColumn": 32, + "endColumn": 33, "problem": "NumericSemantics", "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", @@ -176,9 +176,9 @@ }, { "line": 42, - "column": 36, + "column": 37, "endLine": 42, - "endColumn": 40, + "endColumn": 41, "problem": "NumericSemantics", "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", @@ -204,6 +204,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 45, + "column": 15, + "endLine": 45, + "endColumn": 25, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 47, "column": 13, @@ -588,7 +598,7 @@ "line": 102, "column": 7, "endLine": 102, - "endColumn": 32, + "endColumn": 33, "problem": "DestructuringDeclaration", "suggest": "", "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", @@ -706,9 +716,9 @@ }, { "line": 117, - "column": 46, + "column": 47, "endLine": 117, - "endColumn": 47, + "endColumn": 48, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", @@ -768,7 +778,7 @@ "line": 126, "column": 10, "endLine": 126, - "endColumn": 34, + "endColumn": 36, "problem": "FunctionExpression", "suggest": "", "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", @@ -776,9 +786,9 @@ }, { "line": 126, - "column": 27, + "column": 28, "endLine": 126, - "endColumn": 30, + "endColumn": 31, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -884,6 +894,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 144, + "column": 1, + "endLine": 144, + "endColumn": 6, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 144, "column": 9, @@ -964,6 +984,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 162, + "column": 16, + "endLine": 162, + "endColumn": 36, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 162, "column": 16, @@ -974,6 +1004,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 165, + "column": 8, + "endLine": 165, + "endColumn": 21, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 165, "column": 8, @@ -984,6 +1024,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 168, + "column": 6, + "endLine": 168, + "endColumn": 8, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, { "line": 168, "column": 11, @@ -1066,9 +1116,309 @@ }, { "line": 203, - "column": 5, + "column": 6, "endLine": 203, - "endColumn": 9, + "endColumn": 10, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 211, + "column": 29, + "endLine": 211, + "endColumn": 42, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 211, + "column": 38, + "endLine": 211, + "endColumn": 42, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 212, + "column": 12, + "endLine": 212, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 30, + "endLine": 217, + "endColumn": 43, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 39, + "endLine": 217, + "endColumn": 43, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 218, + "column": 11, + "endLine": 218, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 5, + "endLine": 224, + "endColumn": 7, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 9, + "endLine": 224, + "endColumn": 13, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 16, + "endLine": 224, + "endColumn": 21, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 8, + "endLine": 225, + "endColumn": 21, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 8, + "endLine": 225, + "endColumn": 12, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 24, + "endLine": 225, + "endColumn": 29, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 9, + "endLine": 226, + "endColumn": 22, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 9, + "endLine": 226, + "endColumn": 13, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 25, + "endLine": 226, + "endColumn": 26, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 228, + "column": 31, + "endLine": 228, + "endColumn": 44, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 228, + "column": 40, + "endLine": 228, + "endColumn": 44, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 229, + "column": 14, + "endLine": 229, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 231, + "column": 21, + "endLine": 231, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 238, + "column": 38, + "endLine": 238, + "endColumn": 51, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 238, + "column": 47, + "endLine": 238, + "endColumn": 51, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 246, + "column": 22, + "endLine": 246, + "endColumn": 35, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 246, + "column": 31, + "endLine": 246, + "endColumn": 35, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 250, + "column": 35, + "endLine": 250, + "endColumn": 48, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 250, + "column": 44, + "endLine": 250, + "endColumn": 48, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 251, + "column": 11, + "endLine": 251, + "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": 252, + "column": 10, + "endLine": 252, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 253, + "column": 10, + "endLine": 253, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 257, + "column": 22, + "endLine": 257, + "endColumn": 35, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 257, + "column": 31, + "endLine": 257, + "endColumn": 35, "problem": "LimitedVoidType", "suggest": "", "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", diff --git a/ets2panda/linter/test/main/limit_void_type.ets.autofix.json b/ets2panda/linter/test/main/limit_void_type.ets.autofix.json new file mode 100644 index 0000000000..34bbf47a13 --- /dev/null +++ b/ets2panda/linter/test/main/limit_void_type.ets.autofix.json @@ -0,0 +1,2182 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 8, + "endLine": 19, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 666, + "end": 683, + "replacementText": "a: undefined = ((): undefined => { func1(); return undefined; })()", + "line": 19, + "column": 8, + "endLine": 19, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 15, + "endLine": 19, + "endColumn": 22, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 8, + "endLine": 22, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 749, + "end": 766, + "replacementText": "b: undefined = ((): undefined => { func2(); return undefined; })()", + "line": 22, + "column": 8, + "endLine": 22, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 15, + "endLine": 22, + "endColumn": 22, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 8, + "endLine": 27, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 835, + "end": 864, + "replacementText": "c: undefined = ((): undefined => { new Demo().method(); return undefined; })()", + "line": 27, + "column": 8, + "endLine": 27, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 15, + "endLine": 27, + "endColumn": 34, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 8, + "endLine": 29, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 931, + "end": 966, + "replacementText": "d: undefined = ((): undefined => { (function (): void { })(); return undefined; })()", + "line": 29, + "column": 8, + "endLine": 29, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 15, + "endLine": 29, + "endColumn": 40, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 37, + "problem": "FunctionExpression", + "autofix": [ + { + "start": 942, + "end": 963, + "replacementText": "(): void => { }", + "line": 29, + "column": 16, + "endLine": 29, + "endColumn": 37 + } + ], + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 8, + "endLine": 32, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1054, + "end": 1081, + "replacementText": "e: undefined = ((): undefined => { await asyncFunc(); return undefined; })()", + "line": 32, + "column": 8, + "endLine": 32, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 10, + "endLine": 35, + "endColumn": 14, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1157, + "end": 1171, + "replacementText": "f: undefined = ((): undefined => { fn(); return undefined; })()", + "line": 35, + "column": 10, + "endLine": 35, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 17, + "endLine": 35, + "endColumn": 21, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 8, + "endLine": 39, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1235, + "end": 1260, + "replacementText": "g: undefined = ((): undefined => { func3() as void; return undefined; })()", + "line": 39, + "column": 8, + "endLine": 39, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 15, + "endLine": 39, + "endColumn": 22, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 29, + "endLine": 41, + "endColumn": 33, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1322, + "end": 1326, + "replacementText": "1000.0", + "line": 41, + "column": 29, + "endLine": 41, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 8, + "endLine": 42, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1333, + "end": 1370, + "replacementText": "h: undefined = ((): undefined => { setTimeout(() => { }, 1000); return undefined; })()", + "line": 42, + "column": 8, + "endLine": 42, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 37, + "endLine": 42, + "endColumn": 41, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1365, + "end": 1369, + "replacementText": "1000.0", + "line": 42, + "column": 37, + "endLine": 42, + "endColumn": 41 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 8, + "endLine": 45, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1451, + "end": 1473, + "replacementText": "i: undefined = ((): undefined => { funcArr[0](); return undefined; })()", + "line": 45, + "column": 8, + "endLine": 45, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 15, + "endLine": 45, + "endColumn": 27, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 15, + "endLine": 45, + "endColumn": 25, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 13, + "endLine": 47, + "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": 50, + "column": 8, + "endLine": 50, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1551, + "end": 1573, + "replacementText": "j: undefined = ((): undefined => { obj.action(); return undefined; })()", + "line": 50, + "column": 8, + "endLine": 50, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 15, + "endLine": 50, + "endColumn": 27, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 8, + "endLine": 54, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1647, + "end": 1664, + "replacementText": "k: undefined = ((): undefined => { func4(); return undefined; })()", + "line": 54, + "column": 8, + "endLine": 54, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 15, + "endLine": 54, + "endColumn": 22, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 8, + "endLine": 57, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1740, + "end": 1764, + "replacementText": "l: undefined = ((): undefined => { exportedFunc(); return undefined; })()", + "line": 57, + "column": 8, + "endLine": 57, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 15, + "endLine": 57, + "endColumn": 29, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 8, + "endLine": 60, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 1838, + "end": 1861, + "replacementText": "m: undefined = ((): undefined => { genericFunc(); return undefined; })()", + "line": 60, + "column": 8, + "endLine": 60, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 15, + "endLine": 60, + "endColumn": 28, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 15, + "endLine": 60, + "endColumn": 28, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 1, + "endLine": 62, + "endColumn": 31, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 1, + "endLine": 63, + "endColumn": 42, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 48, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 8, + "endLine": 65, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2024, + "end": 2048, + "replacementText": "n: undefined = ((): undefined => { overloadFunc(); return undefined; })()", + "line": 65, + "column": 8, + "endLine": 65, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 15, + "endLine": 65, + "endColumn": 29, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 8, + "endLine": 69, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2147, + "end": 2168, + "replacementText": "o: undefined = ((): undefined => { aliasFunc(); return undefined; })()", + "line": 69, + "column": 8, + "endLine": 69, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 15, + "endLine": 69, + "endColumn": 26, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 8, + "endLine": 77, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2300, + "end": 2329, + "replacementText": "p: undefined = ((): undefined => { new Printer().run(); return undefined; })()", + "line": 77, + "column": 8, + "endLine": 77, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 15, + "endLine": 77, + "endColumn": 34, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 8, + "endLine": 80, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2414, + "end": 2435, + "replacementText": "q: undefined = ((): undefined => { withParam(); return undefined; })()", + "line": 80, + "column": 8, + "endLine": 80, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 15, + "endLine": 80, + "endColumn": 26, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 8, + "endLine": 83, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2513, + "end": 2535, + "replacementText": "r: undefined = ((): undefined => { sum(1, 2, 3); return undefined; })()", + "line": 83, + "column": 8, + "endLine": 83, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 15, + "endLine": 83, + "endColumn": 27, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 19, + "endLine": 83, + "endColumn": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2527, + "end": 2528, + "replacementText": "1.0", + "line": 83, + "column": 19, + "endLine": 83, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 22, + "endLine": 83, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2530, + "end": 2531, + "replacementText": "2.0", + "line": 83, + "column": 22, + "endLine": 83, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 25, + "endLine": 83, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2533, + "end": 2534, + "replacementText": "3.0", + "line": 83, + "column": 25, + "endLine": 83, + "endColumn": 26 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 19, + "endLine": 85, + "endColumn": 23, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 8, + "endLine": 86, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2613, + "end": 2644, + "replacementText": "s: undefined = ((): undefined => { withThis.call(window); return undefined; })()", + "line": 86, + "column": 8, + "endLine": 86, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 24, + "endLine": 86, + "endColumn": 28, + "problem": "FunctionApplyCall", + "suggest": "", + "rule": "'Function.apply', 'Function.call' are not supported (arkts-no-func-apply-call)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 1, + "endLine": 90, + "endColumn": 2, + "problem": "GeneratorFunction", + "suggest": "", + "rule": "Generator functions are not supported (arkts-no-generators)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 3, + "endLine": 89, + "endColumn": 8, + "problem": "YieldExpression", + "suggest": "", + "rule": "Generator functions are not supported (arkts-no-generators)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 8, + "endLine": 91, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2734, + "end": 2766, + "replacementText": "u: undefined = ((): undefined => { genFunc().next().value; return undefined; })()", + "line": 91, + "column": 8, + "endLine": 91, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 15, + "endLine": 91, + "endColumn": 37, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 8, + "endLine": 94, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2842, + "end": 2861, + "replacementText": "w: undefined = ((): undefined => { curry()(); return undefined; })()", + "line": 94, + "column": 8, + "endLine": 94, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 15, + "endLine": 94, + "endColumn": 24, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 12, + "endLine": 97, + "endColumn": 16, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + }, + { + "line": 100, + "column": 8, + "endLine": 100, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 2966, + "end": 3002, + "replacementText": "x: undefined = ((): undefined => { new Chain().first().last(); return undefined; })()", + "line": 100, + "column": 8, + "endLine": 100, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 100, + "column": 15, + "endLine": 100, + "endColumn": 41, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 102, + "column": 7, + "endLine": 102, + "endColumn": 33, + "problem": "DestructuringDeclaration", + "autofix": [ + { + "replacementText": "GeneratedDestructArray_1", + "start": 3050, + "end": 3056, + "line": 102, + "column": 7, + "endLine": 102, + "endColumn": 33 + }, + { + "replacementText": "\nconst func = GeneratedDestructArray_1[0];\n", + "start": 3077, + "end": 3077, + "line": 102, + "column": 7, + "endLine": 102, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 8, + "endLine": 103, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 3082, + "end": 3098, + "replacementText": "y: undefined = ((): undefined => { func(); return undefined; })()", + "line": 103, + "column": 8, + "endLine": 103, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 15, + "endLine": 103, + "endColumn": 21, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 19, + "endLine": 105, + "endColumn": 20, + "problem": "ObjectTypeLiteral", + "autofix": [ + { + "start": 3128, + "end": 3159, + "replacementText": "interface Wrapper {\n value: T;\n}", + "line": 105, + "column": 19, + "endLine": 105, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types)", + "severity": "ERROR" + }, + { + "line": 106, + "column": 38, + "endLine": 106, + "endColumn": 39, + "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": 8, + "endLine": 107, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 3223, + "end": 3248, + "replacementText": "z: undefined = ((): undefined => { wrapped.value(); return undefined; })()", + "line": 107, + "column": 8, + "endLine": 107, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 15, + "endLine": 107, + "endColumn": 30, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 23, + "endLine": 109, + "endColumn": 61, + "problem": "ConditionalType", + "suggest": "", + "rule": "Conditional types are not supported (arkts-no-conditional-types)", + "severity": "ERROR" + }, + { + "line": 111, + "column": 9, + "endLine": 111, + "endColumn": 13, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 3398, + "end": 3419, + "replacementText": "aa: undefined = ((): undefined => { condFunc(); return undefined; })()", + "line": 111, + "column": 9, + "endLine": 111, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 111, + "column": 16, + "endLine": 111, + "endColumn": 26, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 3, + "endLine": 114, + "endColumn": 12, + "problem": "CallSignature", + "suggest": "", + "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 29, + "endLine": 117, + "endColumn": 35, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 47, + "endLine": 117, + "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": 118, + "column": 9, + "endLine": 118, + "endColumn": 13, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 3560, + "end": 3578, + "replacementText": "ab: undefined = ((): undefined => { mixed(); return undefined; })()", + "line": 118, + "column": 9, + "endLine": 118, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 118, + "column": 16, + "endLine": 118, + "endColumn": 23, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 10, + "endLine": 121, + "endColumn": 21, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 9, + "endLine": 123, + "endColumn": 13, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 3667, + "end": 3689, + "replacementText": "ac: undefined = ((): undefined => { recursive(); return undefined; })()", + "line": 123, + "column": 9, + "endLine": 123, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 16, + "endLine": 123, + "endColumn": 27, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 10, + "endLine": 126, + "endColumn": 36, + "problem": "FunctionExpression", + "autofix": [ + { + "start": 3757, + "end": 3783, + "replacementText": "(target: any) => { }", + "line": 126, + "column": 10, + "endLine": 126, + "endColumn": 36 + } + ], + "suggest": "", + "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 28, + "endLine": 126, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 1, + "endLine": 128, + "endColumn": 13, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 9, + "endLine": 130, + "endColumn": 13, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 3824, + "end": 3857, + "replacementText": "ad: undefined = ((): undefined => { decorator()(Decorated); return undefined; })()", + "line": 130, + "column": 9, + "endLine": 130, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 16, + "endLine": 130, + "endColumn": 38, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 28, + "endLine": 130, + "endColumn": 37, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 10, + "endLine": 134, + "endColumn": 14, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 6, + "endLine": 136, + "endColumn": 10, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 9, + "endLine": 138, + "endColumn": 13, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 3981, + "end": 3989, + "replacementText": "a2: undefined = undefined", + "line": 138, + "column": 9, + "endLine": 138, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 9, + "endLine": 140, + "endColumn": 13, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 19, + "endLine": 140, + "endColumn": 23, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 7, + "endLine": 142, + "endColumn": 11, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 144, + "column": 1, + "endLine": 144, + "endColumn": 6, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 144, + "column": 9, + "endLine": 144, + "endColumn": 13, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 9, + "endLine": 146, + "endColumn": 13, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 4199, + "end": 4214, + "replacementText": "a4: undefined = ((): undefined => { f1(); return undefined; })()", + "line": 146, + "column": 9, + "endLine": 146, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 16, + "endLine": 146, + "endColumn": 20, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 16, + "endLine": 148, + "endColumn": 20, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 4271, + "end": 4278, + "replacementText": "a: undefined", + "line": 148, + "column": 16, + "endLine": 148, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 4, + "endLine": 150, + "endColumn": 8, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 153, + "column": 6, + "endLine": 153, + "endColumn": 10, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 4382, + "end": 4390, + "replacementText": "f: undefined = undefined;", + "line": 153, + "column": 6, + "endLine": 153, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 8, + "endLine": 155, + "endColumn": 12, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 4438, + "end": 4445, + "replacementText": "p: undefined", + "line": 155, + "column": 8, + "endLine": 155, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 157, + "column": 18, + "endLine": 157, + "endColumn": 22, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 4508, + "end": 4515, + "replacementText": "a: undefined", + "line": 157, + "column": 18, + "endLine": 157, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 162, + "column": 16, + "endLine": 162, + "endColumn": 36, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 4599, + "end": 4619, + "replacementText": "undefined | Promise", + "line": 162, + "column": 16, + "endLine": 162, + "endColumn": 36 + }, + { + "start": 4622, + "end": 4622, + "replacementText": "\nreturn undefined;\n", + "line": 162, + "column": 16, + "endLine": 162, + "endColumn": 36 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 162, + "column": 16, + "endLine": 162, + "endColumn": 20, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 165, + "column": 8, + "endLine": 165, + "endColumn": 21, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 4686, + "end": 4699, + "replacementText": "undefined | number", + "line": 165, + "column": 8, + "endLine": 165, + "endColumn": 21 + }, + { + "start": 4702, + "end": 4702, + "replacementText": "\nreturn undefined;\n", + "line": 165, + "column": 8, + "endLine": 165, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 165, + "column": 8, + "endLine": 165, + "endColumn": 12, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 168, + "column": 6, + "endLine": 168, + "endColumn": 8, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 168, + "column": 11, + "endLine": 168, + "endColumn": 15, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 169, + "column": 12, + "endLine": 169, + "endColumn": 14, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 174, + "column": 22, + "endLine": 174, + "endColumn": 26, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "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": 6, + "endLine": 203, + "endColumn": 10, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 211, + "column": 29, + "endLine": 211, + "endColumn": 42, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 5432, + "end": 5445, + "replacementText": "string | undefined", + "line": 211, + "column": 29, + "endLine": 211, + "endColumn": 42 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 211, + "column": 38, + "endLine": 211, + "endColumn": 42, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 212, + "column": 12, + "endLine": 212, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5459, + "end": 5460, + "replacementText": "0.0", + "line": 212, + "column": 12, + "endLine": 212, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 30, + "endLine": 217, + "endColumn": 43, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 5521, + "end": 5534, + "replacementText": "string | undefined", + "line": 217, + "column": 30, + "endLine": 217, + "endColumn": 43 + }, + { + "start": 5556, + "end": 5563, + "replacementText": "return undefined;", + "line": 217, + "column": 30, + "endLine": 217, + "endColumn": 43 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 39, + "endLine": 217, + "endColumn": 43, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 218, + "column": 11, + "endLine": 218, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5547, + "end": 5548, + "replacementText": "0.0", + "line": 218, + "column": 11, + "endLine": 218, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 5, + "endLine": 224, + "endColumn": 7, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 9, + "endLine": 224, + "endColumn": 13, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 5621, + "end": 5637, + "replacementText": "ss: undefined = ((): undefined => { foo(); return undefined; })()", + "line": 224, + "column": 9, + "endLine": 224, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 16, + "endLine": 224, + "endColumn": 21, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 8, + "endLine": 225, + "endColumn": 21, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 5642, + "end": 5666, + "replacementText": "t: undefined | number = ((): undefined | number => { foo(); return undefined; })()", + "line": 225, + "column": 8, + "endLine": 225, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 8, + "endLine": 225, + "endColumn": 12, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 24, + "endLine": 225, + "endColumn": 29, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 9, + "endLine": 226, + "endColumn": 22, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 5671, + "end": 5692, + "replacementText": "t2: undefined | number = ((): undefined | number => { 1; return undefined; })()", + "line": 226, + "column": 9, + "endLine": 226, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 9, + "endLine": 226, + "endColumn": 13, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 25, + "endLine": 226, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5691, + "end": 5692, + "replacementText": "1.0", + "line": 226, + "column": 25, + "endLine": 226, + "endColumn": 26 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 228, + "column": 31, + "endLine": 228, + "endColumn": 44, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 5725, + "end": 5738, + "replacementText": "string | undefined", + "line": 228, + "column": 31, + "endLine": 228, + "endColumn": 44 + }, + { + "start": 5764, + "end": 5771, + "replacementText": "return undefined;", + "line": 228, + "column": 31, + "endLine": 228, + "endColumn": 44 + }, + { + "start": 5842, + "end": 5849, + "replacementText": "return undefined;", + "line": 228, + "column": 31, + "endLine": 228, + "endColumn": 44 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 228, + "column": 40, + "endLine": 228, + "endColumn": 44, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 229, + "column": 14, + "endLine": 229, + "endColumn": 16, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5754, + "end": 5756, + "replacementText": "12.0", + "line": 229, + "column": 14, + "endLine": 229, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 231, + "column": 21, + "endLine": 231, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5792, + "end": 5794, + "replacementText": "18.0", + "line": 231, + "column": 21, + "endLine": 231, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 238, + "column": 38, + "endLine": 238, + "endColumn": 51, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 5894, + "end": 5907, + "replacementText": "string | undefined", + "line": 238, + "column": 38, + "endLine": 238, + "endColumn": 51 + }, + { + "start": 5989, + "end": 5996, + "replacementText": "return undefined;", + "line": 238, + "column": 38, + "endLine": 238, + "endColumn": 51 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 238, + "column": 47, + "endLine": 238, + "endColumn": 51, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 246, + "column": 22, + "endLine": 246, + "endColumn": 35, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 6021, + "end": 6034, + "replacementText": "string | undefined", + "line": 246, + "column": 22, + "endLine": 246, + "endColumn": 35 + }, + { + "start": 6062, + "end": 6062, + "replacementText": "\nreturn undefined;\n", + "line": 246, + "column": 22, + "endLine": 246, + "endColumn": 35 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 246, + "column": 31, + "endLine": 246, + "endColumn": 35, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 250, + "column": 35, + "endLine": 250, + "endColumn": 48, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 6099, + "end": 6112, + "replacementText": "string | undefined", + "line": 250, + "column": 35, + "endLine": 250, + "endColumn": 48 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 250, + "column": 44, + "endLine": 250, + "endColumn": 48, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 251, + "column": 11, + "endLine": 251, + "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": 252, + "column": 10, + "endLine": 252, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 6142, + "end": 6143, + "replacementText": "1.0", + "line": 252, + "column": 10, + "endLine": 252, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 253, + "column": 10, + "endLine": 253, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 6167, + "end": 6168, + "replacementText": "2.0", + "line": 253, + "column": 10, + "endLine": 253, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 257, + "column": 22, + "endLine": 257, + "endColumn": 35, + "problem": "LimitedVoidType", + "autofix": [ + { + "start": 6216, + "end": 6229, + "replacementText": "string | undefined", + "line": 257, + "column": 22, + "endLine": 257, + "endColumn": 35 + } + ], + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 257, + "column": 31, + "endLine": 257, + "endColumn": 35, + "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/limit_void_type.ets.json b/ets2panda/linter/test/main/limit_void_type.ets.json index c23430e5d2..1e0934e13b 100644 --- a/ets2panda/linter/test/main/limit_void_type.ets.json +++ b/ets2panda/linter/test/main/limit_void_type.ets.json @@ -18,7 +18,7 @@ "line": 29, "column": 16, "endLine": 29, - "endColumn": 35, + "endColumn": 37, "problem": "FunctionExpression", "suggest": "", "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", @@ -88,7 +88,7 @@ "line": 102, "column": 7, "endLine": 102, - "endColumn": 32, + "endColumn": 33, "problem": "DestructuringDeclaration", "suggest": "", "rule": "Destructuring variable declarations are not supported (arkts-no-destruct-decls)", @@ -138,7 +138,7 @@ "line": 117, "column": 22, "endLine": 117, - "endColumn": 59, + "endColumn": 60, "problem": "LimitedStdLibApi", "suggest": "", "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", @@ -146,9 +146,9 @@ }, { "line": 117, - "column": 46, + "column": 47, "endLine": 117, - "endColumn": 47, + "endColumn": 48, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", @@ -158,7 +158,7 @@ "line": 126, "column": 10, "endLine": 126, - "endColumn": 34, + "endColumn": 36, "problem": "FunctionExpression", "suggest": "", "rule": "Use arrow functions instead of function expressions (arkts-no-func-expressions)", @@ -166,9 +166,9 @@ }, { "line": 126, - "column": 27, + "column": 28, "endLine": 126, - "endColumn": 30, + "endColumn": 31, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -184,6 +184,16 @@ "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", "severity": "WARNING" }, + { + "line": 168, + "column": 6, + "endLine": 168, + "endColumn": 8, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, { "line": 200, "column": 5, @@ -193,6 +203,16 @@ "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" + }, + { + "line": 224, + "column": 5, + "endLine": 224, + "endColumn": 7, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/limit_void_type.ets.migrate.ets b/ets2panda/linter/test/main/limit_void_type.ets.migrate.ets new file mode 100644 index 0000000000..8873cd3602 --- /dev/null +++ b/ets2panda/linter/test/main/limit_void_type.ets.migrate.ets @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +// Example 1: Basic function +function func1(): void { } +let a: undefined = ((): undefined => { func1(); return undefined; })(); +// Example 2: Arrow function +const func2 = (): void => { }; +let b: undefined = ((): undefined => { func2(); return undefined; })(); +// Example 3: Class method +class Demo { + method(): void { } +} +let c: undefined = ((): undefined => { new Demo().method(); return undefined; })(); +// Example 4: Immediately Invoked Function Expression (IIFE) +let d: undefined = ((): undefined => { ((): void => { })(); return undefined; })(); +// Example 5: Asynchronous function +async function asyncFunc(): Promise { } +let e: undefined = ((): undefined => { await asyncFunc(); return undefined; })(); +// Example 6: Function parameter +function wrapper(fn: () => void) { + let f: undefined = ((): undefined => { fn(); return undefined; })(); +} +// Example 7: Type assertion +function func3(): void { } +let g: undefined = ((): undefined => { func3() as void; return undefined; })(); +// Example 8: Callback function +setTimeout((): void => { }, 1000.0); +let h: undefined = ((): undefined => { setTimeout(() => { }, 1000.0); return undefined; })(); +// Example 9: Array operation +const funcArr: (() => void)[] = [() => { }]; +let i: undefined = ((): undefined => { funcArr[0](); return undefined; })(); +// Example 10: Object method +const obj = { + action: (): void => { } +}; +let j: undefined = ((): undefined => { obj.action(); return undefined; })(); +// Example 11: Strict mode +// @ts-strict +function func4(): void { } +let k: undefined = ((): undefined => { func4(); return undefined; })(); +// Example 12: Module export +export function exportedFunc(): void { } +let l: undefined = ((): undefined => { exportedFunc(); return undefined; })(); +// Example 13: Generic function +function genericFunc(): void { } +let m: undefined = ((): undefined => { genericFunc(); return undefined; })(); +// Example 14: Function overloading +function overloadFunc(): void; +function overloadFunc(n: number): number; +function overloadFunc(n?: number) { return n; } +let n: undefined = ((): undefined => { overloadFunc(); return undefined; })(); +// Example 15: Type alias +type VoidFunc = () => void; +const aliasFunc: VoidFunc = () => { }; +let o: undefined = ((): undefined => { aliasFunc(); return undefined; })(); +// Example 16: Interface implementation +interface Task { + run(): void; +} +class Printer implements Task { + run(): void { } +} +let p: undefined = ((): undefined => { new Printer().run(); return undefined; })(); +// Example 17: Optional parameter +function withParam(param?: string): void { } +let q: undefined = ((): undefined => { withParam(); return undefined; })(); +// Example 18: Rest parameter +function sum(...nums: number[]): void { } +let r: undefined = ((): undefined => { sum(1.0, 2.0, 3.0); return undefined; })(); +// Example 19: This parameter +function withThis(this: Window): void { } +let s: undefined = ((): undefined => { withThis.call(window); return undefined; })(); +// Example 20: Generator function +function* genFunc(): Generator { + yield; +} +let u: undefined = ((): undefined => { genFunc().next().value; return undefined; })(); +// Example 21: Function currying +const curry = () => (): void => { }; +let w: undefined = ((): undefined => { curry()(); return undefined; })(); +// Example 22: Method chaining +class Chain { + first(): this { return this; } + last(): void { } +} +let x: undefined = ((): undefined => { new Chain().first().last(); return undefined; })(); +// Example 23: Destructuring assignment +const GeneratedDestructArray_1 = [(): void => { }]; +const func = GeneratedDestructArray_1[0]; + +let y: undefined = ((): undefined => { func(); return undefined; })(); +// Example 24: Type mapping +interface Wrapper { + value: T; +} +const wrapped: Wrapper<() => void> = { value: () => { } }; +let z: undefined = ((): undefined => { wrapped.value(); return undefined; })(); +// Example 25: Conditional type +type Conditional = T extends boolean ? () => void : never; +const condFunc: Conditional = () => { }; +let aa: undefined = ((): undefined => { condFunc(); return undefined; })(); +// Example 26: Mixed type +interface Mixed { + (): void; + prop: string; +} +const mixed: Mixed = Object.assign(() => { }, { prop: "" }); +let ab: undefined = ((): undefined => { mixed(); return undefined; })(); +// Example 27: Recursive call +function recursive(): void { + return recursive(); +} +let ac: undefined = ((): undefined => { recursive(); return undefined; })(); +// Example 28: Decorator function +function decorator() { + return (target: any) => { }; +} +@decorator() +class Decorated { } +let ad: undefined = ((): undefined => { decorator()(Decorated); return undefined; })(); + +function f1(): void { } + +let a1 = f1(); // type `void` is used as value + +a1 = f1(); // type `void` is used as value + +let a2: undefined = undefined; // type `void` is used as type annotation + +let a3: void[] = [f1()]; // type `void` is used as type annotation + +a3 = [f1()]; // type `void` is used as value + +a3[0] = f1(); // type `void` is used as value + +let a4: undefined = ((): undefined => { f1(); return undefined; })(); // type `void` is used as type annotation + +function f2(a: undefined) { } // type `void` is used as type annotation + +f2(f1()); // type `void` is used as value + +class A { + f: undefined = undefined; // type `void` is used as type annotation + + m(p: undefined) { } // type `void` is used as type annotation + + constructor(a: undefined) { // type `void` is used as type annotation + this.f = a; + } +} + +function f3(): undefined | Promise { +return undefined; +} // type `void` is not allowed in union type + +class B { + m(): undefined | number { +return undefined; +} // type `void` is not allowed in union type +} + +type ss = void; +let sspar: ss; + +type ff = string; +let ffpar: ff; + +let sread: readonly [void] = [undefined]; + +interface BT { + qaq: Function; +} + +class C { + private cc?: BT; + + private d(): void { + this.cc = { + qaq: (caller?: string): void => this.qaqq(caller) + } + } + private qaqq(caller?: string): void { + 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; +} + +function foo1():void{ + return foo(); // No Error +} + +function foocfe(a: number): string | undefined { + if (a >= 0.0) { + return "a >= 0"; + } +} + +function foocfe2(a: number): string | undefined { + if (a < 0.0) { + return undefined; + } + return "a >= 0"; +} +function fooefc(): void { } +let ss: undefined = ((): undefined => { foo(); return undefined; })() +let t: undefined | number = ((): undefined | number => { foo(); return undefined; })() +let t2: undefined | number = ((): undefined | number => { 1.0; return undefined; })(); + +function greet(hour: number): string | undefined { + if (hour < 12.0) { + return undefined; + } else if (hour < 18.0) { + return "Good afternoon"; + } else { + return undefined; + } +} + +function logOrReturn(flag: boolean): string | undefined { + if (flag) { + return "Flag is true"; + } + console.log("Flag is false"); + return undefined; +} + +function justLogs(): string | undefined { + console.log("Hello!"); + +return undefined; +} + +function getStatus(code: number): string | undefined { + switch (code) { + case 1.0: return "OK"; + case 2.0: return "Warning"; + } +} + +function tryThing(): string | undefined { + try { + return "Worked!"; + } catch (e) { + console.error(e); + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/limit_void_type.ets.migrate.json b/ets2panda/linter/test/main/limit_void_type.ets.migrate.json new file mode 100644 index 0000000000..ca74c32559 --- /dev/null +++ b/ets2panda/linter/test/main/limit_void_type.ets.migrate.json @@ -0,0 +1,468 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", + "See the License for the specific language governing permissions and", + "limitations under the License." + ], + "result": [ + { + "line": 39, + "column": 40, + "endLine": 39, + "endColumn": 47, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 40, + "endLine": 45, + "endColumn": 50, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 13, + "endLine": 47, + "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": 60, + "column": 40, + "endLine": 60, + "endColumn": 53, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 1, + "endLine": 62, + "endColumn": 31, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 1, + "endLine": 63, + "endColumn": 42, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 1, + "endLine": 64, + "endColumn": 48, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 19, + "endLine": 85, + "endColumn": 23, + "problem": "InvalidIdentifier", + "suggest": "", + "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 49, + "endLine": 86, + "endColumn": 53, + "problem": "FunctionApplyCall", + "suggest": "", + "rule": "'Function.apply', 'Function.call' are not supported (arkts-no-func-apply-call)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 1, + "endLine": 90, + "endColumn": 2, + "problem": "GeneratorFunction", + "suggest": "", + "rule": "Generator functions are not supported (arkts-no-generators)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 3, + "endLine": 89, + "endColumn": 8, + "problem": "YieldExpression", + "suggest": "", + "rule": "Generator functions are not supported (arkts-no-generators)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 40, + "endLine": 91, + "endColumn": 62, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 12, + "endLine": 97, + "endColumn": 16, + "problem": "ThisType", + "suggest": "", + "rule": "Type notation using \"this\" is not supported (arkts-no-typing-with-this)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 14, + "endLine": 103, + "endColumn": 41, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 23, + "endLine": 113, + "endColumn": 61, + "problem": "ConditionalType", + "suggest": "", + "rule": "Conditional types are not supported (arkts-no-conditional-types)", + "severity": "ERROR" + }, + { + "line": 118, + "column": 3, + "endLine": 118, + "endColumn": 12, + "problem": "CallSignature", + "suggest": "", + "rule": "Use \"class\" instead of a type with call signature (arkts-no-call-signatures)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 29, + "endLine": 121, + "endColumn": 35, + "problem": "LimitedStdLibApi", + "suggest": "", + "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 47, + "endLine": 121, + "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": 125, + "column": 10, + "endLine": 125, + "endColumn": 21, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 19, + "endLine": 130, + "endColumn": 22, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 1, + "endLine": 132, + "endColumn": 13, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 53, + "endLine": 134, + "endColumn": 62, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 10, + "endLine": 138, + "endColumn": 14, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 140, + "column": 6, + "endLine": 140, + "endColumn": 10, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 144, + "column": 9, + "endLine": 144, + "endColumn": 13, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 144, + "column": 19, + "endLine": 144, + "endColumn": 23, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 7, + "endLine": 146, + "endColumn": 11, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 1, + "endLine": 148, + "endColumn": 6, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 9, + "endLine": 148, + "endColumn": 13, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 4, + "endLine": 154, + "endColumn": 8, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 176, + "column": 6, + "endLine": 176, + "endColumn": 8, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 176, + "column": 11, + "endLine": 176, + "endColumn": 15, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 177, + "column": 12, + "endLine": 177, + "endColumn": 14, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 22, + "endLine": 182, + "endColumn": 26, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 23, + "endLine": 205, + "endColumn": 28, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 205, + "column": 31, + "endLine": 205, + "endColumn": 36, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 208, + "column": 5, + "endLine": 208, + "endColumn": 7, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 209, + "column": 19, + "endLine": 209, + "endColumn": 24, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 209, + "column": 27, + "endLine": 209, + "endColumn": 32, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 211, + "column": 6, + "endLine": 211, + "endColumn": 10, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 232, + "column": 5, + "endLine": 232, + "endColumn": 7, + "problem": "DeclWithDuplicateName", + "suggest": "", + "rule": "Use unique names for types and namespaces. (arkts-unique-names)", + "severity": "ERROR" + }, + { + "line": 261, + "column": 11, + "endLine": 261, + "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": 219, + "column": 29, + "endLine": 219, + "endColumn": 47, + "problem": "StrictDiagnostic", + "suggest": "Not all code paths return a value.", + "rule": "Not all code paths return a value.", + "severity": "ERROR" + }, + { + "line": 260, + "column": 35, + "endLine": 260, + "endColumn": 53, + "problem": "StrictDiagnostic", + "suggest": "Not all code paths return a value.", + "rule": "Not all code paths return a value.", + "severity": "ERROR" + }, + { + "line": 267, + "column": 22, + "endLine": 267, + "endColumn": 40, + "problem": "StrictDiagnostic", + "suggest": "Not all code paths return a value.", + "rule": "Not all code paths return a value.", + "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 affb940597..e7bcfd0d2d 100644 --- a/ets2panda/linter/test/main/limited_stdlib_api.ets.arkts2.json +++ b/ets2panda/linter/test/main/limited_stdlib_api.ets.arkts2.json @@ -354,6 +354,16 @@ "rule": "Using \"Object.getOwnPropertyNames\" is not allowed in this API (arkts-builtin-object-getOwnPropertyNames))", "severity": "ERROR" }, + { + "line": 85, + "column": 1, + "endLine": 85, + "endColumn": 51, + "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": 85, "column": 9, @@ -364,6 +374,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 86, + "column": 1, + "endLine": 86, + "endColumn": 39, + "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": 86, "column": 9, @@ -384,6 +404,16 @@ "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", "severity": "ERROR" }, + { + "line": 87, + "column": 1, + "endLine": 87, + "endColumn": 36, + "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": 87, "column": 9, @@ -404,6 +434,16 @@ "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, + { + "line": 88, + "column": 1, + "endLine": 88, + "endColumn": 34, + "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": 88, "column": 9, @@ -414,6 +454,26 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 89, + "column": 1, + "endLine": 89, + "endColumn": 32, + "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": 90, + "column": 1, + "endLine": 90, + "endColumn": 53, + "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": 90, "column": 9, @@ -424,6 +484,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 91, + "column": 1, + "endLine": 91, + "endColumn": 27, + "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": 91, "column": 9, @@ -434,6 +504,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 92, + "column": 1, + "endLine": 92, + "endColumn": 25, + "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": 92, "column": 9, @@ -444,6 +524,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 93, + "column": 1, + "endLine": 93, + "endColumn": 30, + "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": 93, "column": 9, @@ -454,6 +544,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 94, + "column": 1, + "endLine": 94, + "endColumn": 30, + "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": 94, "column": 9, @@ -464,6 +564,66 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 95, + "column": 1, + "endLine": 95, + "endColumn": 39, + "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": 96, + "column": 1, + "endLine": 96, + "endColumn": 46, + "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": 97, + "column": 1, + "endLine": 97, + "endColumn": 39, + "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": 98, + "column": 1, + "endLine": 98, + "endColumn": 39, + "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": 99, + "column": 1, + "endLine": 99, + "endColumn": 38, + "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": 100, + "column": 1, + "endLine": 100, + "endColumn": 31, + "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": 100, "column": 27, @@ -474,6 +634,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 101, + "column": 1, + "endLine": 101, + "endColumn": 29, + "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": 101, "column": 19, diff --git a/ets2panda/linter/test/main/limited_stdlib_api.ets.json b/ets2panda/linter/test/main/limited_stdlib_api.ets.json index 0b436b2d76..75f3d7b10e 100644 --- a/ets2panda/linter/test/main/limited_stdlib_api.ets.json +++ b/ets2panda/linter/test/main/limited_stdlib_api.ets.json @@ -274,6 +274,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 85, + "column": 1, + "endLine": 85, + "endColumn": 51, + "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": 86, "column": 1, @@ -284,6 +294,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 86, + "column": 1, + "endLine": 86, + "endColumn": 39, + "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": 86, "column": 32, @@ -304,6 +324,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 87, + "column": 1, + "endLine": 87, + "endColumn": 36, + "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": 87, "column": 32, @@ -324,6 +354,26 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 88, + "column": 1, + "endLine": 88, + "endColumn": 34, + "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": 89, + "column": 1, + "endLine": 89, + "endColumn": 32, + "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": 90, "column": 1, @@ -334,6 +384,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 90, + "column": 1, + "endLine": 90, + "endColumn": 53, + "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": 91, "column": 1, @@ -344,6 +404,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 91, + "column": 1, + "endLine": 91, + "endColumn": 27, + "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": 92, "column": 1, @@ -354,6 +424,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 92, + "column": 1, + "endLine": 92, + "endColumn": 25, + "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": 93, "column": 1, @@ -364,6 +444,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 93, + "column": 1, + "endLine": 93, + "endColumn": 30, + "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": 94, "column": 1, @@ -374,6 +464,86 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 94, + "column": 1, + "endLine": 94, + "endColumn": 30, + "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": 95, + "column": 1, + "endLine": 95, + "endColumn": 39, + "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": 96, + "column": 1, + "endLine": 96, + "endColumn": 46, + "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": 97, + "column": 1, + "endLine": 97, + "endColumn": 39, + "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": 98, + "column": 1, + "endLine": 98, + "endColumn": 39, + "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": 99, + "column": 1, + "endLine": 99, + "endColumn": 38, + "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": 100, + "column": 1, + "endLine": 100, + "endColumn": 31, + "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": 101, + "column": 1, + "endLine": 101, + "endColumn": 29, + "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": 104, "column": 32, diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets b/ets2panda/linter/test/main/literals_as_prop_names.ets index c994718102..114339394c 100755 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets @@ -128,11 +128,23 @@ class A{ let a:A = { "age": 30} -class B{ +class B { public 'age': number = 1 // error in arkts2 } let obj11: Record = { -['value']: 1, // 误扫 -'value2': 1 // ok -} \ No newline at end of file + ['value']: 1, // Error in arkts 2.0 + 'value2': 1 // ok +} + +class CompPropClass { + ['CompProp'] = 1; // Error in arkts 2.0 + [2] = 'CompProp2'; // Error in arkts 2.0 + [LiteralAsPropertyNameEnum.One] = 3; // Error in arkts 2.0 +} + +let compPropObj = { + ['CompProp']: 1, // Error in arkts 2.0 + [2]: 'CompProp2', // Error in arkts 2.0 + [LiteralAsPropertyNameEnum.One]: 3 // Error in arkts 2.0 +}; \ No newline at end of file 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 old mode 100755 new mode 100644 index 286fd756ff..f6d45915a0 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.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", @@ -274,6 +274,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 84, + "column": 12, + "endLine": 84, + "endColumn": 31, + "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + }, { "line": 84, "column": 36, @@ -294,6 +304,26 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 86, + "column": 1, + "endLine": 86, + "endColumn": 33, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 1, + "endLine": 88, + "endColumn": 40, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 92, "column": 4, @@ -304,6 +334,16 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 92, + "column": 9, + "endLine": 92, + "endColumn": 10, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 97, "column": 3, @@ -314,6 +354,16 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 97, + "column": 10, + "endLine": 97, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 98, "column": 3, @@ -324,6 +374,16 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 98, + "column": 13, + "endLine": 98, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 102, "column": 3, @@ -334,6 +394,16 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 102, + "column": 10, + "endLine": 102, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 103, "column": 3, @@ -344,6 +414,16 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 103, + "column": 13, + "endLine": 103, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 105, "column": 5, @@ -354,6 +434,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 105, + "column": 14, + "endLine": 105, + "endColumn": 31, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 106, "column": 5, @@ -364,6 +454,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 106, + "column": 15, + "endLine": 106, + "endColumn": 35, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 109, "column": 1, @@ -374,6 +474,16 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 109, + "column": 8, + "endLine": 109, + "endColumn": 9, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 112, "column": 1, @@ -384,6 +494,26 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 112, + "column": 9, + "endLine": 112, + "endColumn": 10, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 118, + "column": 18, + "endLine": 118, + "endColumn": 35, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 125, "column": 22, @@ -434,11 +564,31 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 135, + "column": 37, + "endLine": 135, + "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": 136, - "column": 12, + "column": 3, "endLine": 136, - "endColumn": 13, + "endColumn": 12, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 14, + "endLine": 136, + "endColumn": 15, "problem": "NumericSemantics", "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", @@ -446,9 +596,139 @@ }, { "line": 137, - "column": 11, + "column": 13, "endLine": 137, - "endColumn": 12, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 3, + "endLine": 141, + "endColumn": 15, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 18, + "endLine": 141, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 3, + "endLine": 142, + "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": 142, + "column": 4, + "endLine": 142, + "endColumn": 5, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 3, + "endLine": 143, + "endColumn": 34, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 37, + "endLine": 143, + "endColumn": 38, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 19, + "endLine": 146, + "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": 147, + "column": 3, + "endLine": 147, + "endColumn": 15, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 147, + "column": 17, + "endLine": 147, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 3, + "endLine": 148, + "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": 148, + "column": 4, + "endLine": 148, + "endColumn": 5, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 3, + "endLine": 149, + "endColumn": 34, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 36, + "endLine": 149, + "endColumn": 37, "problem": "NumericSemantics", "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", @@ -461,7 +741,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -471,7 +751,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (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 282458e4e5..c006698019 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) 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", @@ -656,6 +656,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 84, + "column": 12, + "endLine": 84, + "endColumn": 31, + "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + }, { "line": 84, "column": 36, @@ -687,6 +697,26 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 86, + "column": 1, + "endLine": 86, + "endColumn": 33, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 88, + "column": 1, + "endLine": 88, + "endColumn": 40, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 92, "column": 4, @@ -708,6 +738,27 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 92, + "column": 9, + "endLine": 92, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1996, + "end": 1997, + "replacementText": "1.0", + "line": 92, + "column": 9, + "endLine": 92, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 97, "column": 3, @@ -729,6 +780,27 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 97, + "column": 10, + "endLine": 97, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2040, + "end": 2041, + "replacementText": "1.0", + "line": 97, + "column": 10, + "endLine": 97, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 98, "column": 3, @@ -750,6 +822,27 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 98, + "column": 13, + "endLine": 98, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2055, + "end": 2056, + "replacementText": "1.0", + "line": 98, + "column": 13, + "endLine": 98, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 102, "column": 3, @@ -780,6 +873,27 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 102, + "column": 10, + "endLine": 102, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2095, + "end": 2096, + "replacementText": "1.0", + "line": 102, + "column": 10, + "endLine": 102, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 103, "column": 3, @@ -810,6 +924,27 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 103, + "column": 13, + "endLine": 103, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2110, + "end": 2111, + "replacementText": "1.0", + "line": 103, + "column": 13, + "endLine": 103, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 105, "column": 5, @@ -831,6 +966,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 105, + "column": 14, + "endLine": 105, + "endColumn": 31, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 106, "column": 5, @@ -852,6 +997,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 106, + "column": 15, + "endLine": 106, + "endColumn": 35, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 109, "column": 1, @@ -882,6 +1037,27 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 109, + "column": 8, + "endLine": 109, + "endColumn": 9, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2214, + "end": 2215, + "replacementText": "1.0", + "line": 109, + "column": 8, + "endLine": 109, + "endColumn": 9 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 112, "column": 1, @@ -903,6 +1079,37 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 112, + "column": 9, + "endLine": 112, + "endColumn": 10, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2252, + "end": 2253, + "replacementText": "1.0", + "line": 112, + "column": 9, + "endLine": 112, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 118, + "column": 18, + "endLine": 118, + "endColumn": 35, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 125, "column": 22, @@ -975,8 +1182,8 @@ "autofix": [ { "replacementText": "age", - "start": 2465, - "end": 2470, + "start": 2466, + "end": 2471, "line": 132, "column": 10, "endLine": 132, @@ -995,8 +1202,8 @@ "problem": "NumericSemantics", "autofix": [ { - "start": 2481, - "end": 2482, + "start": 2482, + "end": 2483, "replacementText": "1.0", "line": 132, "column": 26, @@ -1008,21 +1215,41 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 135, + "column": 37, + "endLine": 135, + "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": 136, - "column": 12, + "column": 3, "endLine": 136, - "endColumn": 13, + "endColumn": 12, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 14, + "endLine": 136, + "endColumn": 15, "problem": "NumericSemantics", "autofix": [ { - "start": 2554, - "end": 2555, + "start": 2557, + "end": 2558, "replacementText": "1.0", "line": 136, - "column": 12, + "column": 14, "endLine": 136, - "endColumn": 13 + "endColumn": 15 } ], "suggest": "", @@ -1031,19 +1258,215 @@ }, { "line": 137, - "column": 11, + "column": 13, "endLine": 137, - "endColumn": 12, + "endColumn": 14, "problem": "NumericSemantics", "autofix": [ { - "start": 2573, - "end": 2574, + "start": 2594, + "end": 2595, "replacementText": "1.0", "line": 137, - "column": 11, + "column": 13, "endLine": 137, - "endColumn": 12 + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 3, + "endLine": 141, + "endColumn": 15, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 18, + "endLine": 141, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2644, + "end": 2645, + "replacementText": "1.0", + "line": 141, + "column": 18, + "endLine": 141, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 3, + "endLine": 142, + "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": 142, + "column": 4, + "endLine": 142, + "endColumn": 5, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2672, + "end": 2673, + "replacementText": "2.0", + "line": 142, + "column": 4, + "endLine": 142, + "endColumn": 5 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 3, + "endLine": 143, + "endColumn": 34, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 37, + "endLine": 143, + "endColumn": 38, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2748, + "end": 2749, + "replacementText": "3.0", + "line": 143, + "column": 37, + "endLine": 143, + "endColumn": 38 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 19, + "endLine": 146, + "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": 147, + "column": 3, + "endLine": 147, + "endColumn": 15, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 147, + "column": 17, + "endLine": 147, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2812, + "end": 2813, + "replacementText": "1.0", + "line": 147, + "column": 17, + "endLine": 147, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 3, + "endLine": 148, + "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": 148, + "column": 4, + "endLine": 148, + "endColumn": 5, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2840, + "end": 2841, + "replacementText": "2.0", + "line": 148, + "column": 4, + "endLine": 148, + "endColumn": 5 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 3, + "endLine": 149, + "endColumn": 34, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 36, + "endLine": 149, + "endColumn": 37, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2914, + "end": 2915, + "replacementText": "3.0", + "line": 149, + "column": 36, + "endLine": 149, + "endColumn": 37 } ], "suggest": "", @@ -1068,7 +1491,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1089,7 +1512,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { 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 7e721f74f1..dfce9f6d57 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.json @@ -144,6 +144,36 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 142, + "column": 3, + "endLine": 142, + "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": 146, + "column": 19, + "endLine": 146, + "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": 148, + "column": 3, + "endLine": 148, + "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": 42, "column": 11, diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets index 54ed22aed8..5c91b9deba 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets @@ -95,27 +95,27 @@ LiteralAsPropertyNameEnum.PrivateTwo; { const enum Direction { - __empty = 1, + __empty = 1.0, } } const enum Direction16 { - ___x5c = 1, - __x5c = 1, + ___x5c = 1.0, + __x5c = 1.0, } const enum Direction17 { - ___x5c = 1, - __x5c = 1, + ___x5c = 1.0, + __x5c = 1.0, } let case17: number = Direction17.___x5c let case172: number = Direction17.__x5c const enum Direction11 { -__x21x21 = 1, +__x21x21 = 1.0, } const enum Direction23 { -aaa = 1, +aaa = 1.0, } // ArkUI @Component @@ -134,11 +134,23 @@ class A{ let a:A = { age: 30.0} -class B{ +class B { public age: number = 1.0 // error in arkts2 } let obj11: Record = { -['value']: 1.0, // 误扫 -'value2': 1.0 // ok -} \ No newline at end of file + ['value']: 1.0, // Error in arkts 2.0 + 'value2': 1.0 // ok +} + +class CompPropClass { + ['CompProp'] = 1.0; // Error in arkts 2.0 + [2.0] = 'CompProp2'; // Error in arkts 2.0 + [LiteralAsPropertyNameEnum.One] = 3.0; // Error in arkts 2.0 +} + +let compPropObj = { + ['CompProp']: 1.0, // Error in arkts 2.0 + [2.0]: 'CompProp2', // Error in arkts 2.0 + [LiteralAsPropertyNameEnum.One]: 3.0 // Error in arkts 2.0 +}; \ No newline at end of file diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json index 7756bd5397..2597882d05 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json @@ -74,6 +74,16 @@ "rule": "This keyword cannot be used as identifiers (arkts-invalid-identifier)", "severity": "ERROR" }, + { + "line": 90, + "column": 12, + "endLine": 90, + "endColumn": 31, + "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + }, { "line": 90, "column": 36, @@ -84,6 +94,106 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 92, + "column": 1, + "endLine": 92, + "endColumn": 33, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 141, + "column": 37, + "endLine": 141, + "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": 142, + "column": 3, + "endLine": 142, + "endColumn": 12, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 147, + "column": 3, + "endLine": 147, + "endColumn": 15, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 3, + "endLine": 148, + "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": 149, + "column": 3, + "endLine": 149, + "endColumn": 34, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 19, + "endLine": 152, + "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": 153, + "column": 3, + "endLine": 153, + "endColumn": 15, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 3, + "endLine": 154, + "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": 155, + "column": 3, + "endLine": 155, + "endColumn": 34, + "problem": "ComputedPropertyName", + "suggest": "", + "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", + "severity": "ERROR" + }, { "line": 28, "column": 11, diff --git a/ets2panda/linter/test/main/localBuilder_1.ets.arkts2.json b/ets2panda/linter/test/main/localBuilder_1.ets.arkts2.json index d25d1a3cb3..2476b27017 100644 --- a/ets2panda/linter/test/main/localBuilder_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/localBuilder_1.ets.arkts2.json @@ -31,7 +31,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 8, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json b/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json index 03374a941a..70cdea3625 100644 --- a/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json +++ b/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json @@ -24,7 +24,11 @@ { "start": 676, "end": 689, - "replacementText": "@Builder" + "replacementText": "@Builder", + "line": 21, + "column": 3, + "endLine": 21, + "endColumn": 16 } ], "suggest": "", @@ -41,11 +45,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -58,11 +66,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -75,11 +87,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -92,11 +108,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -109,11 +129,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -126,11 +150,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "line": 29, + "column": 5, + "endLine": 29, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/make_observed_1.ets.arkts2.json b/ets2panda/linter/test/main/make_observed_1.ets.arkts2.json index 10dbf86c48..2abf7a1421 100644 --- a/ets2panda/linter/test/main/make_observed_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/make_observed_1.ets.arkts2.json @@ -81,7 +81,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/make_observed_2.ets.arkts2.json b/ets2panda/linter/test/main/make_observed_2.ets.arkts2.json index acf1d0da2e..7a2f092704 100644 --- a/ets2panda/linter/test/main/make_observed_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/make_observed_2.ets.arkts2.json @@ -81,7 +81,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/make_observed_3.ets.arkts2.json b/ets2panda/linter/test/main/make_observed_3.ets.arkts2.json index 7323b8589d..731dc882fb 100644 --- a/ets2panda/linter/test/main/make_observed_3.ets.arkts2.json +++ b/ets2panda/linter/test/main/make_observed_3.ets.arkts2.json @@ -71,7 +71,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ComponentV2\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Local\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/method_inheritance.ets b/ets2panda/linter/test/main/method_inheritance.ets index ff1895fc91..c92fa1f0d9 100644 --- a/ets2panda/linter/test/main/method_inheritance.ets +++ b/ets2panda/linter/test/main/method_inheritance.ets @@ -18,7 +18,7 @@ abstract class Y { } class X extends Y { - async getDataByName(name: string, albumUri: string): Promise { + async getDataByName(name: string, albumUri: string): Promise { // error 2 return; } } @@ -38,7 +38,7 @@ abstract class W { } class Q extends W { - async getDataByName(name: string | number, albumUri: string | number): Promise { + async getDataByName(name: string | number, albumUri: string | number): Promise {// error 1 return; }; } @@ -48,7 +48,7 @@ abstract class BaseClass3 { } class IncorrectWiderReturn extends BaseClass3 { - compute(value: string): string | number { + compute(value: string): string | number {// error 1 return value.length > 5 ? value : 0; } } @@ -58,7 +58,7 @@ abstract class BaseClass4 { } class IncorrectMultipleParamMismatch extends BaseClass4 { - setValues(x: string, y: boolean): void { + setValues(x: string, y: boolean): void {// error 2 console.log(x, y); } } @@ -68,7 +68,7 @@ abstract class BaseClass5 { } class IncorrectBothMismatch extends BaseClass5 { - transform(data: number): number | string { + transform(data: number): number | string {// error 2 return data > 10 ? data : "too small"; } } @@ -97,3 +97,122 @@ class CorrectBothWiderParamNarrowReturn extends BaseClass { } +class A1 { + a: number = 0 +} +class B1 { + a: number = 0 +} +class C { + a: number = 0 +} + +class Base { + foo(obj: A1 | B1): void { + console.log("base") + } + foo2(obj: A1 | B1): void { + console.log("base") + } + foo3(obj: A1 | B1 | C): void { + console.log("base") + } +} + +// extends +class Derived extends Base { + foo(obj: A1): void { // error 1 + console.log("Derived:" + obj.a) + } + foo2(): void { // error 1 + console.log("Derived:") + } + foo3(obj: A1 | B1): void { // error 1 + console.log("Derived:") + } +} + +interface BaseI { + foo(obj: A1 | B1):void; + foo2(obj: A1): void; + foo3(obj: A1 | B1 | C): void; +} + +// implements +class Derived2 implements BaseI { + foo(obj: A1): void { // error 1 + console.log("Drived"); + } + foo2(): void { // error 1 + console.log("Drived"); + } + foo3(obj: A1 | B1): void { // error 1 + console.log("Drived"); + } +} + +class Base2 { + foo(): A1|B1 { + console.log("base") + return new A1(); + } + foo2(){ + console.log("base") + // return new A(); + } + foo3(): A1 { + console.log("base") + return new A1(); + } + foo4():void{ + console.log("base") + // return new A(); + } +} + +//extends +class Derived3 extends Base2 { + foo(): A1|B1|C{ // error 1 + console.log("Derived:") + return new A1(); + } + + foo2(): A1{ // error 1 + console.log("Derived:") + return new A1(); + } + + foo3(): A1|B1 { // error 1 + console.log("Derived:") + return new A1(); + } + foo4(): A1{ // error 1 + console.log("Derived:") + return new A1(); + } +} + + +interface Base3 { + foo(): A1|B1 ; + foo2(): void; + foo3(): A1; +} + +// implements +class Derived4 implements Base3 { + foo(): A1|B1|C{ // error 1 + console.log("Derived:") + return new A1(); + } + + foo2(): A1{ // error 1 + console.log("Derived:") + return new A1(); + } + + foo3(): A1|B1 { // error 1 + console.log("Derived:") + return new A1(); + } +} diff --git a/ets2panda/linter/test/main/method_inheritance.ets.arkts2.json b/ets2panda/linter/test/main/method_inheritance.ets.arkts2.json index 717bb1ec00..a25dd05807 100644 --- a/ets2panda/linter/test/main/method_inheritance.ets.arkts2.json +++ b/ets2panda/linter/test/main/method_inheritance.ets.arkts2.json @@ -133,6 +133,166 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 101, + "column": 15, + "endLine": 101, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 15, + "endLine": 104, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 15, + "endLine": 107, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 7, + "endLine": 124, + "endColumn": 14, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 3, + "endLine": 127, + "endColumn": 7, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 8, + "endLine": 130, + "endColumn": 20, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 143, + "column": 7, + "endLine": 143, + "endColumn": 14, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 146, + "column": 3, + "endLine": 146, + "endColumn": 7, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 8, + "endLine": 149, + "endColumn": 20, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 175, + "column": 10, + "endLine": 175, + "endColumn": 17, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 180, + "column": 11, + "endLine": 180, + "endColumn": 13, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 185, + "column": 11, + "endLine": 185, + "endColumn": 16, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 189, + "column": 11, + "endLine": 189, + "endColumn": 13, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 204, + "column": 10, + "endLine": 204, + "endColumn": 17, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 209, + "column": 11, + "endLine": 209, + "endColumn": 13, + "problem": "MethodInheritRule", + "suggest": "", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", + "severity": "ERROR" + }, + { + "line": 214, + "column": 11, + "endLine": 214, + "endColumn": 16, + "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/no_sparse_array.ets b/ets2panda/linter/test/main/no_sparse_array.ets index 3298c36c92..a543274d46 100644 --- a/ets2panda/linter/test/main/no_sparse_array.ets +++ b/ets2panda/linter/test/main/no_sparse_array.ets @@ -14,4 +14,5 @@ */ let a = [1, , , 3]; -let b = []; \ No newline at end of file +let b = []; +let c:number[] = []; \ 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 index 2a8c937e9f..edf83e80e8 100644 --- a/ets2panda/linter/test/main/no_sparse_array.ets.arkts2.json +++ b/ets2panda/linter/test/main/no_sparse_array.ets.arkts2.json @@ -53,6 +53,16 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 17, + "column": 9, + "endLine": 17, + "endColumn": 11, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" } ] } \ 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 index 3a4d7ee28d..65ad923c30 100755 --- a/ets2panda/linter/test/main/no_ts_like_smart_type.ets +++ b/ets2panda/linter/test/main/no_ts_like_smart_type.ets @@ -12,29 +12,53 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// static + +class A { + private static instance:A = new A(); + static get():A { + return A.instance; // + } +} + +class AA { + public static instance?: number; + + getInstance(): number { + if (!AA.instance) { + return 0; + } + return AA.instance; // Error + } +} + class AA1 { - public static instance : number | string; - getInstance(): number { - if (AA1.instance instanceof string) { - return 0; - } - return AA1.instance; // Error + public static instance : Number | String | Object = "smart cast"; + getInstance(): Number { + if (!(AA1.instance instanceof Number)) { + 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 + public instance : Number | String | Object= 'smart cast'; + getInstance(): Number { + if (!(this.instance instanceof Number)) { + return 0; } + return this.instance; // Error + } } -class A { - private static instance:A = new A(); - static get():A { - return A.instance; + +class AA3 { + public instance : number | String | Object = 'string'; + getInstance(): number { + if (this.instance instanceof String) { + return 0; + } else if (this.instance instanceof Object) { + return 1; } + return this.instance; // Error + } } \ No newline at end of file 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 index 45fcc93425..d8dd2482a1 100755 --- 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 @@ -15,63 +15,93 @@ ], "result": [ { - "line": 22, - "column": 9, - "endLine": 22, - "endColumn": 29, + "line": 30, + "column": 5, + "endLine": 30, + "endColumn": 24, "problem": "NoTsLikeSmartType", "suggest": "", "rule": "Smart type differences (arkts-no-ts-like-smart-type)", "severity": "ERROR" }, { - "line": 17, + "line": 28, + "column": 14, + "endLine": 28, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 40, "column": 5, - "endLine": 17, - "endColumn": 46, - "problem": "ClassstaticInitialization", + "endLine": 40, + "endColumn": 25, + "problem": "NoTsLikeSmartType", "suggest": "", - "rule": "The static property has no initializer (arkts-class-static-initialization)", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", "severity": "ERROR" }, { - "line": 20, - "column": 20, - "endLine": 20, - "endColumn": 21, + "line": 38, + "column": 14, + "endLine": 38, + "endColumn": 15, "problem": "NumericSemantics", "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 32, - "column": 9, - "endLine": 32, - "endColumn": 30, + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 26, "problem": "NoTsLikeSmartType", "suggest": "", "rule": "Smart type differences (arkts-no-ts-like-smart-type)", "severity": "ERROR" }, { - "line": 30, - "column": 20, - "endLine": 30, - "endColumn": 21, + "line": 48, + "column": 14, + "endLine": 48, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 5, + "endLine": 62, + "endColumn": 26, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 14, + "endLine": 58, + "endColumn": 15, "problem": "NumericSemantics", "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "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.", + "line": 60, + "column": 14, + "endLine": 60, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" } ] 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 index b9d40bdd28..ca88f857e9 100755 --- a/ets2panda/linter/test/main/no_ts_like_smart_type.ets.json +++ b/ets2panda/linter/test/main/no_ts_like_smart_type.ets.json @@ -13,16 +13,5 @@ "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" - } - ] + "result": [] } \ 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 93ab572c51..1ebcd176a4 100644 --- a/ets2panda/linter/test/main/no_tuples_arrays.ets +++ b/ets2panda/linter/test/main/no_tuples_arrays.ets @@ -87,4 +87,44 @@ 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 +let array20: (number)[] = originalArray as (number)[] //error + +const inputArray: readonly [Record, [], () => void] = [ + {}, + [], + () => { + } +]; +const even = (element: Record | [] | (() => void)): boolean => { + return typeof element === 'function'; +}; +const res = inputArray.some(even); // error +console.log("res:" + JSON.stringify(res)); +console.log(''+inputArray.length) // error +console.log(inputArray.toString()) // error +typeof inputArray.toLocaleString(); // error +function getConcat() { + inputArray.concat(); // error + return inputArray.join(','); // error +} +class Demo{ + set(){ + inputArray.slice(1,2); // error + inputArray.indexOf([]); // error + } + get(){ + return inputArray.lastIndexOf([]); // error + } +} +inputArray.every(()=>{}) // error +inputArray.some(()=>{}) // error +inputArray.forEach(()=>{}) // error +inputArray.map(()=>{}) // error +inputArray.filter(()=>{}) // error +inputArray.reduce((acc, item) => acc + 1, 0); // error +inputArray.reduceRight((acc, item) => acc + 1, 0); // error +inputArray.find((item) => Array.isArray(item)); // error +inputArray.includes(() => {}); // error +inputArray.flat() // error +inputArray.flatMap((item) => [item]); // error +inputArray.findIndex((item) => typeof item === 'function'); // 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 f4753e594f..e578984b44 100644 --- a/ets2panda/linter/test/main/no_tuples_arrays.ets.arkts2.json +++ b/ets2panda/linter/test/main/no_tuples_arrays.ets.arkts2.json @@ -64,16 +64,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 29, "column": 30, @@ -94,6 +84,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 30, + "column": 16, + "endLine": 30, + "endColumn": 21, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 33, "column": 23, @@ -114,16 +114,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 63, "column": 43, @@ -154,16 +144,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 67, "column": 7, @@ -174,16 +154,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 68, "column": 7, @@ -194,16 +164,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 70, "column": 5, @@ -214,16 +174,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 73, "column": 5, @@ -234,16 +184,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 74, "column": 5, @@ -254,16 +194,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 75, "column": 5, @@ -274,16 +204,6 @@ "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 type is immutable in ArkTS1.2 (arkts-array-type-immutable)", - "severity": "ERROR" - }, { "line": 78, "column": 35, @@ -454,6 +374,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 88, + "column": 17, + "endLine": 88, + "endColumn": 34, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, { "line": 88, "column": 54, @@ -503,6 +433,276 @@ "suggest": "", "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", "severity": "ERROR" + }, + { + "line": 101, + "column": 13, + "endLine": 101, + "endColumn": 28, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 16, + "endLine": 103, + "endColumn": 33, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 13, + "endLine": 104, + "endColumn": 32, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 8, + "endLine": 105, + "endColumn": 33, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 3, + "endLine": 107, + "endColumn": 20, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 10, + "endLine": 108, + "endColumn": 25, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 5, + "endLine": 112, + "endColumn": 21, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 22, + "endLine": 112, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 24, + "endLine": 112, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 5, + "endLine": 113, + "endColumn": 23, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 12, + "endLine": 116, + "endColumn": 34, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 119, + "column": 1, + "endLine": 119, + "endColumn": 17, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 1, + "endLine": 120, + "endColumn": 16, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 1, + "endLine": 121, + "endColumn": 19, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 122, + "column": 1, + "endLine": 122, + "endColumn": 15, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 1, + "endLine": 123, + "endColumn": 18, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 1, + "endLine": 124, + "endColumn": 18, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 40, + "endLine": 124, + "endColumn": 41, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 43, + "endLine": 124, + "endColumn": 44, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 1, + "endLine": 125, + "endColumn": 23, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 45, + "endLine": 125, + "endColumn": 46, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 48, + "endLine": 125, + "endColumn": 49, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 126, + "column": 1, + "endLine": 126, + "endColumn": 16, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 127, + "column": 1, + "endLine": 127, + "endColumn": 20, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 1, + "endLine": 128, + "endColumn": 16, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 129, + "column": 1, + "endLine": 129, + "endColumn": 19, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" + }, + { + "line": 130, + "column": 1, + "endLine": 130, + "endColumn": 21, + "problem": "NoTuplesArrays", + "suggest": "", + "rule": "Array and tuple are different type(arkts-no-tuples-arrays)", + "severity": "ERROR" } ] } \ 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 e09d8b47cf..ff1a6aece7 100755 --- a/ets2panda/linter/test/main/numeric_semantics.ets +++ b/ets2panda/linter/test/main/numeric_semantics.ets @@ -202,4 +202,26 @@ for (let i:number = 0; i < 100; 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 +let arr1: Array = Array.from(new ArrayList()) + +let a:number = 0.000; + +const b:number = 0.000; + +export enum WalletStageValue { + DEFAULT = 0, + SWIPE_INIT = -1, + SELECT_CARD = 1, + SWIPE_DOING = 2, + SWIPE_SUCCEED = 3, + SWIPE_FAILED = 4, + SWIPE_FINISHED = 5, +} + +export enum AnimationStage { + INIT = 0, + ENTER = 1, + ROTATING = 2, + EXIT_START = 3, + EXIT_END = 4, +} \ 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 old mode 100755 new mode 100644 index d8d76c5ce8..569ac92a4c --- a/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.arkts2.json @@ -504,6 +504,26 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 112, + "column": 7, + "endLine": 112, + "endColumn": 8, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 7, + "endLine": 113, + "endColumn": 8, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 115, "column": 7, @@ -964,6 +984,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 183, + "column": 6, + "endLine": 183, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 185, "column": 5, @@ -1074,6 +1104,126 @@ "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" }, + { + "line": 212, + "column": 13, + "endLine": 212, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 213, + "column": 17, + "endLine": 213, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 214, + "column": 17, + "endLine": 214, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 215, + "column": 17, + "endLine": 215, + "endColumn": 18, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 216, + "column": 19, + "endLine": 216, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 18, + "endLine": 217, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 218, + "column": 20, + "endLine": 218, + "endColumn": 21, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 222, + "column": 10, + "endLine": 222, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 223, + "column": 11, + "endLine": 223, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 14, + "endLine": 224, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 16, + "endLine": 225, + "endColumn": 17, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 14, + "endLine": 226, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 117, "column": 2, @@ -1081,7 +1231,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1091,7 +1241,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1101,7 +1251,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1111,7 +1261,7 @@ "endColumn": 22, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"RelativeContainer\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1121,7 +1271,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1131,7 +1281,7 @@ "endColumn": 40, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1141,7 +1291,7 @@ "endColumn": 56, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1151,7 +1301,7 @@ "endColumn": 43, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -1161,7 +1311,7 @@ "endColumn": 44, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (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 148d39bc82..2c6c4de6cf 100644 --- a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json @@ -704,9 +704,9 @@ "problem": "NumericSemantics", "autofix": [ { - "start": 2067, + "start": 2066, "end": 2070, - "replacementText": "234.0", + "replacementText": "-234.0", "line": 85, "column": 11, "endLine": 85, @@ -1063,6 +1063,48 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 112, + "column": 7, + "endLine": 112, + "endColumn": 8, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2446, + "end": 2447, + "replacementText": "1.0", + "line": 112, + "column": 7, + "endLine": 112, + "endColumn": 8 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 7, + "endLine": 113, + "endColumn": 8, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2468, + "end": 2469, + "replacementText": "2.0", + "line": 113, + "column": 7, + "endLine": 113, + "endColumn": 8 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 115, "column": 7, @@ -1626,9 +1668,9 @@ "problem": "NumericSemantics", "autofix": [ { - "start": 3357, + "start": 3356, "end": 3358, - "replacementText": "1.0", + "replacementText": "-1.0", "line": 149, "column": 17, "endLine": 149, @@ -1647,9 +1689,9 @@ "problem": "NumericSemantics", "autofix": [ { - "start": 3361, + "start": 3360, "end": 3362, - "replacementText": "1.0", + "replacementText": "-1.0", "line": 149, "column": 21, "endLine": 149, @@ -1963,6 +2005,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 183, + "column": 6, + "endLine": 183, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 185, "column": 5, @@ -2150,6 +2202,258 @@ "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" }, + { + "line": 212, + "column": 13, + "endLine": 212, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5206, + "end": 5207, + "replacementText": "0.0", + "line": 212, + "column": 13, + "endLine": 212, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 213, + "column": 17, + "endLine": 213, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5225, + "end": 5227, + "replacementText": "-1.0", + "line": 213, + "column": 17, + "endLine": 213, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 214, + "column": 17, + "endLine": 214, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5246, + "end": 5247, + "replacementText": "1.0", + "line": 214, + "column": 17, + "endLine": 214, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 215, + "column": 17, + "endLine": 215, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5266, + "end": 5267, + "replacementText": "2.0", + "line": 215, + "column": 17, + "endLine": 215, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 216, + "column": 19, + "endLine": 216, + "endColumn": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5288, + "end": 5289, + "replacementText": "3.0", + "line": 216, + "column": 19, + "endLine": 216, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 217, + "column": 18, + "endLine": 217, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5309, + "end": 5310, + "replacementText": "4.0", + "line": 217, + "column": 18, + "endLine": 217, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 218, + "column": 20, + "endLine": 218, + "endColumn": 21, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5332, + "end": 5333, + "replacementText": "5.0", + "line": 218, + "column": 20, + "endLine": 218, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 222, + "column": 10, + "endLine": 222, + "endColumn": 11, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5380, + "end": 5381, + "replacementText": "0.0", + "line": 222, + "column": 10, + "endLine": 222, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 223, + "column": 11, + "endLine": 223, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5394, + "end": 5395, + "replacementText": "1.0", + "line": 223, + "column": 11, + "endLine": 223, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 224, + "column": 14, + "endLine": 224, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5411, + "end": 5412, + "replacementText": "2.0", + "line": 224, + "column": 14, + "endLine": 224, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 225, + "column": 16, + "endLine": 225, + "endColumn": 17, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5430, + "end": 5431, + "replacementText": "3.0", + "line": 225, + "column": 16, + "endLine": 225, + "endColumn": 17 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 14, + "endLine": 226, + "endColumn": 15, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 5447, + "end": 5448, + "replacementText": "4.0", + "line": 226, + "column": 14, + "endLine": 226, + "endColumn": 15 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 117, "column": 2, @@ -2168,7 +2472,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -2189,7 +2493,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -2210,7 +2514,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -2231,7 +2535,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"RelativeContainer\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -2252,7 +2556,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -2273,7 +2577,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -2294,7 +2598,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -2315,7 +2619,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -2336,7 +2640,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets index cecf097403..ba4df96e9d 100644 --- a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets +++ b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets @@ -112,8 +112,8 @@ let g: number = an_array[] const a: number = 1.0 enum Test { - A = 1, // 显式赋值为 1 - B = 2 // 显式赋值为 2 + A = 1.0, // 显式赋值为 1 + B = 2.0 // 显式赋值为 2 } const test: number = Test.A; @@ -208,4 +208,26 @@ for (let i:number = 0.0; i < 100.0; i++) { } let cancelIds:ArrayList = arr.subArrayList(6.0, 86.0) let a: Array = Array.from(cancelIds) -let arr1: Array = Array.from(new ArrayList()) \ No newline at end of file +let arr1: Array = Array.from(new ArrayList()) + +let a:number = 0.000; + +const b:number = 0.000; + +export enum WalletStageValue { + DEFAULT = 0.0, + SWIPE_INIT = -1.0, + SELECT_CARD = 1.0, + SWIPE_DOING = 2.0, + SWIPE_SUCCEED = 3.0, + SWIPE_FAILED = 4.0, + SWIPE_FINISHED = 5.0, +} + +export enum AnimationStage { + INIT = 0.0, + ENTER = 1.0, + ROTATING = 2.0, + EXIT_START = 3.0, + EXIT_END = 4.0, +} \ 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 index c86c2373e1..665c1dea05 100644 --- a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json @@ -74,6 +74,16 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 189, + "column": 6, + "endLine": 189, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 203, "column": 1, diff --git a/ets2panda/linter/test/main/numeric_semantics2.ets.arkts2.json b/ets2panda/linter/test/main/numeric_semantics2.ets.arkts2.json index 0b572f009a..8c2a778ec9 100755 --- a/ets2panda/linter/test/main/numeric_semantics2.ets.arkts2.json +++ b/ets2panda/linter/test/main/numeric_semantics2.ets.arkts2.json @@ -204,6 +204,46 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 44, + "column": 17, + "endLine": 44, + "endColumn": 19, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 17, + "endLine": 45, + "endColumn": 23, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 13, + "endLine": 62, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 13, + "endLine": 63, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 68, "column": 28, diff --git a/ets2panda/linter/test/main/numeric_semantics2.ets.autofix.json b/ets2panda/linter/test/main/numeric_semantics2.ets.autofix.json index e649323550..890005064b 100644 --- a/ets2panda/linter/test/main/numeric_semantics2.ets.autofix.json +++ b/ets2panda/linter/test/main/numeric_semantics2.ets.autofix.json @@ -419,6 +419,68 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 44, + "column": 17, + "endLine": 44, + "endColumn": 19, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 17, + "endLine": 45, + "endColumn": 23, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 13, + "endLine": 62, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1792, + "end": 1793, + "replacementText": "1.0", + "line": 62, + "column": 13, + "endLine": 62, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 13, + "endLine": 63, + "endColumn": 14, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1808, + "end": 1809, + "replacementText": "2.0", + "line": 63, + "column": 13, + "endLine": 63, + "endColumn": 14 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 68, "column": 28, diff --git a/ets2panda/linter/test/main/numeric_semantics2.ets.migrate.ets b/ets2panda/linter/test/main/numeric_semantics2.ets.migrate.ets index db5e2adfbe..3b6d90963d 100644 --- a/ets2panda/linter/test/main/numeric_semantics2.ets.migrate.ets +++ b/ets2panda/linter/test/main/numeric_semantics2.ets.migrate.ets @@ -61,8 +61,8 @@ namespace NoNumericSemantics { let h: number = arr[12. as int] enum E { - A = 1, - B = 2 + A = 1.0, + B = 2.0 } } diff --git a/ets2panda/linter/test/main/numeric_semantics2.ets.migrate.json b/ets2panda/linter/test/main/numeric_semantics2.ets.migrate.json index 2b4699fa61..dcabd25e69 100644 --- a/ets2panda/linter/test/main/numeric_semantics2.ets.migrate.json +++ b/ets2panda/linter/test/main/numeric_semantics2.ets.migrate.json @@ -74,6 +74,26 @@ "rule": "Objects with property names that are not identifiers are not supported (arkts-identifiers-as-prop-names)", "severity": "ERROR" }, + { + "line": 46, + "column": 17, + "endLine": 46, + "endColumn": 19, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 17, + "endLine": 47, + "endColumn": 23, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 74, "column": 5, diff --git a/ets2panda/linter/test/main/object_literals_properties.ets b/ets2panda/linter/test/main/object_literals_properties.ets index d5265f7493..84c1d5db86 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets +++ b/ets2panda/linter/test/main/object_literals_properties.ets @@ -244,15 +244,42 @@ let b3: Derived3 = { // Fixable m() { console.log(2); } }; -interface A { +interface I4 { map: Map; } let map:Map = new Map(); -let a:A = {map}; +let i4: I4 = {map}; -class C { +class C6 { map1: Map = new Map(); } let map1:Map = new Map(); -let c:C = {map1}; \ No newline at end of file +let c6: C6 = {map1}; + +// Namespace typed object literals +namespace X { + export class C { + m() { + console.log("C - 1"); + } + } + + export interface I { + m(a: number, b: string): void; + } +} + +function test() { + let c: X.C = { + m() { + console.log("C - 2"); + } + } + + let i: X.I = { + m(): void { + console.log("I"); + } + } +} \ No newline at end of file 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 cc12e25c14..4f42a0f593 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.arkts2.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.arkts2.json @@ -124,6 +124,36 @@ "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, + { + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 3, + "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, @@ -164,6 +194,26 @@ "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": 48, + "column": 3, + "endLine": 48, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 50, "column": 3, @@ -334,6 +384,36 @@ "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, @@ -554,6 +634,36 @@ "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, @@ -584,6 +694,36 @@ "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, @@ -694,6 +834,36 @@ "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, @@ -1024,6 +1194,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 226, + "column": 16, + "endLine": 226, + "endColumn": 29, + "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": 229, "column": 20, @@ -1094,16 +1274,66 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 251, + "column": 15, + "endLine": 251, + "endColumn": 18, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 258, - "column": 11, + "column": 15, "endLine": 258, - "endColumn": 12, + "endColumn": 19, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 274, + "column": 16, + "endLine": 274, + "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": 275, + "column": 5, + "endLine": 277, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 280, + "column": 16, + "endLine": 280, + "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": 281, + "column": 5, + "endLine": 283, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 187, "column": 3, diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json b/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json index 8e5ca87403..04eed5c407 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json @@ -228,6 +228,69 @@ "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", "severity": "ERROR" }, + { + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 922, + "end": 923, + "replacementText": "x: x", + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 4 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 945, + "end": 946, + "replacementText": "y: y", + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 4 + } + ], + "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", + "autofix": [ + { + "start": 968, + "end": 969, + "replacementText": "z: z", + "line": 36, + "column": 3, + "endLine": 36, + "endColumn": 4 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 39, "column": 14, @@ -288,6 +351,48 @@ "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", + "autofix": [ + { + "start": 1112, + "end": 1113, + "replacementText": "x: x", + "line": 47, + "column": 3, + "endLine": 47, + "endColumn": 4 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 3, + "endLine": 48, + "endColumn": 4, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 1126, + "end": 1127, + "replacementText": "y: y", + "line": 48, + "column": 3, + "endLine": 48, + "endColumn": 4 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 50, "column": 3, @@ -601,6 +706,69 @@ "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", + "autofix": [ + { + "start": 1425, + "end": 1427, + "replacementText": "x2: x2", + "line": 69, + "column": 3, + "endLine": 69, + "endColumn": 5 + } + ], + "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", + "autofix": [ + { + "start": 1449, + "end": 1451, + "replacementText": "y2: y2", + "line": 70, + "column": 3, + "endLine": 70, + "endColumn": 5 + } + ], + "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", + "autofix": [ + { + "start": 1473, + "end": 1475, + "replacementText": "z2: z2", + "line": 71, + "column": 3, + "endLine": 71, + "endColumn": 5 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 72, "column": 3, @@ -1013,6 +1181,69 @@ "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", + "autofix": [ + { + "start": 1926, + "end": 1928, + "replacementText": "x2: x2", + "line": 110, + "column": 3, + "endLine": 110, + "endColumn": 5 + } + ], + "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", + "autofix": [ + { + "start": 1943, + "end": 1945, + "replacementText": "y2: y2", + "line": 111, + "column": 3, + "endLine": 111, + "endColumn": 5 + } + ], + "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", + "autofix": [ + { + "start": 1960, + "end": 1962, + "replacementText": "z2: z2", + "line": 112, + "column": 3, + "endLine": 112, + "endColumn": 5 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 113, "column": 3, @@ -1074,6 +1305,69 @@ "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", + "autofix": [ + { + "start": 2034, + "end": 2036, + "replacementText": "x2: x2", + "line": 117, + "column": 3, + "endLine": 117, + "endColumn": 5 + } + ], + "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", + "autofix": [ + { + "start": 2051, + "end": 2053, + "replacementText": "y2: y2", + "line": 118, + "column": 3, + "endLine": 118, + "endColumn": 5 + } + ], + "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", + "autofix": [ + { + "start": 2068, + "end": 2070, + "replacementText": "z2: z2", + "line": 119, + "column": 3, + "endLine": 119, + "endColumn": 5 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 120, "column": 3, @@ -1261,6 +1555,69 @@ "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", + "autofix": [ + { + "start": 2289, + "end": 2291, + "replacementText": "x2: x2", + "line": 134, + "column": 3, + "endLine": 134, + "endColumn": 5 + } + ], + "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", + "line": 135, + "column": 3, + "endLine": 135, + "endColumn": 5 + } + ], + "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", + "line": 136, + "column": 3, + "endLine": 136, + "endColumn": 5 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 137, "column": 3, @@ -1776,6 +2133,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 226, + "column": 16, + "endLine": 226, + "endColumn": 29, + "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": 229, "column": 20, @@ -1899,16 +2266,128 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 251, + "column": 15, + "endLine": 251, + "endColumn": 18, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 4619, + "end": 4622, + "replacementText": "map: map", + "line": 251, + "column": 15, + "endLine": 251, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 258, - "column": 11, + "column": 15, "endLine": 258, - "endColumn": 12, + "endColumn": 19, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 4766, + "end": 4770, + "replacementText": "map1: map1", + "line": 258, + "column": 15, + "endLine": 258, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 274, + "column": 16, + "endLine": 274, + "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": 275, + "column": 5, + "endLine": 277, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 4958, + "end": 4958, + "replacementText": "class GeneratedObjectLiteralClass_11 extends X.C {\n m() {\n console.log(\"C - 2\");\n }\n}\n\n", + "line": 275, + "column": 5, + "endLine": 277, + "endColumn": 6 + }, + { + "start": 4991, + "end": 5040, + "replacementText": "new GeneratedObjectLiteralClass_11()", + "line": 275, + "column": 5, + "endLine": 277, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, + { + "line": 280, + "column": 16, + "endLine": 280, + "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": 281, + "column": 5, + "endLine": 283, + "endColumn": 6, + "problem": "ObjectLiteralProperty", + "autofix": [ + { + "start": 4958, + "end": 4958, + "replacementText": "class GeneratedObjectLiteralClass_12 implements X.I {\n m(): void {\n console.log(\"I\");\n }\n}\n\n", + "line": 281, + "column": 5, + "endLine": 283, + "endColumn": 6 + }, + { + "start": 5058, + "end": 5109, + "replacementText": "new GeneratedObjectLiteralClass_12()", + "line": 281, + "column": 5, + "endLine": 283, + "endColumn": 6 + } + ], + "suggest": "", + "rule": "Object literal properties can only contain name-value pairs (arkts-obj-literal-props)", + "severity": "ERROR" + }, { "line": 187, "column": 3, diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.json b/ets2panda/linter/test/main/object_literals_properties.ets.json index 8548318c10..97cb35867c 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.json @@ -295,10 +295,20 @@ "severity": "ERROR" }, { - "line": 258, - "column": 11, - "endLine": 258, - "endColumn": 12, + "line": 274, + "column": 16, + "endLine": 274, + "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": 280, + "column": 16, + "endLine": 280, + "endColumn": 17, "problem": "ObjectLiteralNoContextType", "suggest": "", "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets index eb3a50b921..c2c2429650 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets +++ b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets @@ -36,10 +36,15 @@ let setMethod = new GeneratedObjectLiteralClass_3(); let x: number = 1.0, y = '2', z = true; -let shorthand = { - x, // Error, fixable - y, // Error, fixable - z // Error, fixable +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 = { @@ -92,9 +97,9 @@ let x2: number = 1.0, y2: number = 2.0, z2: number = 3.0; let mixedBad = { // Not fixable a: 1.0, b: 2.0, - x2, // Error, fixable - y2, // Error, fixable - z2, // Error, fixable + x2: x2, // Error, fixable + y2: y2, // Error, fixable + z2: z2, // Error, fixable m() {}, ...shorthand // Error, not fixable } @@ -142,7 +147,7 @@ class GeneratedObjectLiteralClass_8 extends C2 { x2: number; y2: number; z2: number; - constructor(init: GeneratedObjectLiteralInitInterface_8) { + constructor(init: GeneratedObjectLiteralInitInterface_1) { super(); this.x2 = init.x2; this.y2 = init.y2; @@ -151,7 +156,7 @@ class GeneratedObjectLiteralClass_8 extends C2 { m() { console.log(1.0); } // Fixable } -interface GeneratedObjectLiteralInitInterface_8 { +interface GeneratedObjectLiteralInitInterface_1 { x2: number; y2: number; z2: number; @@ -164,9 +169,9 @@ let c2: C2 = new GeneratedObjectLiteralClass_8({ }); let c22: C2 = { - x2, // Fixable - y2, // Fixable - z2, // Fixable + x2: x2, // Fixable + y2: y2, // Fixable + z2: z2, // Fixable m() { console.log(1.0); }, // Not fixable, object has spread property ...shorthand // Not fixable }; @@ -181,9 +186,9 @@ class C3 { constructor(a: number) {} } let c3: C3 = { - x2, // Fixable - y2, // Fixable - z2, // Fixable + x2: x2, // Fixable + y2: y2, // Fixable + z2: z2, // Fixable m() { console.log(1.0); } // Not fixable, class type has constructor with parameters }; @@ -301,15 +306,46 @@ class GeneratedObjectLiteralClass_10 extends Derived3 { let b3: Derived3 = new GeneratedObjectLiteralClass_10(); -interface A { +interface I4 { map: Map; } let map:Map = new Map(); -let a:A = {map}; +let i4: I4 = {map: map}; -class C { +class C6 { map1: Map = new Map(); } let map1:Map = new Map(); -let c:C = {map1}; \ No newline at end of file +let c6: C6 = {map1: map1}; + +// Namespace typed object literals +namespace X { + export class C { + m() { + console.log("C - 1"); + } + } + + export interface I { + m(a: number, b: string): void; + } +} + +class GeneratedObjectLiteralClass_11 extends X.C { + m() { + console.log("C - 2"); + } +} + +class GeneratedObjectLiteralClass_12 implements X.I { + m(): void { + console.log("I"); + } +} + +function test() { + let c: X.C = new GeneratedObjectLiteralClass_11() + + let i: X.I = new GeneratedObjectLiteralClass_12() +} \ 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 index 9143d0676d..b652f8984b 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json @@ -15,19 +15,9 @@ ], "result": [ { - "line": 39, - "column": 17, - "endLine": 39, - "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": 45, + "line": 50, "column": 14, - "endLine": 45, + "endLine": 50, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -35,9 +25,9 @@ "severity": "ERROR" }, { - "line": 46, + "line": 51, "column": 3, - "endLine": 46, + "endLine": 51, "endColumn": 15, "problem": "ObjectLiteralProperty", "suggest": "", @@ -45,9 +35,9 @@ "severity": "ERROR" }, { - "line": 46, + "line": 51, "column": 3, - "endLine": 46, + "endLine": 51, "endColumn": 15, "problem": "SpreadOperator", "suggest": "", @@ -55,9 +45,9 @@ "severity": "ERROR" }, { - "line": 92, + "line": 97, "column": 16, - "endLine": 92, + "endLine": 97, "endColumn": 17, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -65,9 +55,9 @@ "severity": "ERROR" }, { - "line": 98, + "line": 103, "column": 3, - "endLine": 98, + "endLine": 103, "endColumn": 9, "problem": "ObjectLiteralProperty", "suggest": "", @@ -75,9 +65,9 @@ "severity": "ERROR" }, { - "line": 99, + "line": 104, "column": 3, - "endLine": 99, + "endLine": 104, "endColumn": 15, "problem": "ObjectLiteralProperty", "suggest": "", @@ -85,9 +75,9 @@ "severity": "ERROR" }, { - "line": 99, + "line": 104, "column": 3, - "endLine": 99, + "endLine": 104, "endColumn": 15, "problem": "SpreadOperator", "suggest": "", @@ -95,9 +85,9 @@ "severity": "ERROR" }, { - "line": 166, + "line": 171, "column": 15, - "endLine": 166, + "endLine": 171, "endColumn": 16, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -105,9 +95,9 @@ "severity": "ERROR" }, { - "line": 170, + "line": 175, "column": 3, - "endLine": 170, + "endLine": 175, "endColumn": 28, "problem": "ObjectLiteralProperty", "suggest": "", @@ -115,9 +105,9 @@ "severity": "ERROR" }, { - "line": 171, + "line": 176, "column": 3, - "endLine": 171, + "endLine": 176, "endColumn": 15, "problem": "ObjectLiteralProperty", "suggest": "", @@ -125,9 +115,9 @@ "severity": "ERROR" }, { - "line": 171, + "line": 176, "column": 3, - "endLine": 171, + "endLine": 176, "endColumn": 15, "problem": "SpreadOperator", "suggest": "", @@ -135,9 +125,9 @@ "severity": "ERROR" }, { - "line": 183, + "line": 188, "column": 14, - "endLine": 183, + "endLine": 188, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -145,9 +135,9 @@ "severity": "ERROR" }, { - "line": 187, + "line": 192, "column": 3, - "endLine": 187, + "endLine": 192, "endColumn": 28, "problem": "ObjectLiteralProperty", "suggest": "", @@ -155,9 +145,9 @@ "severity": "ERROR" }, { - "line": 192, + "line": 197, "column": 25, - "endLine": 192, + "endLine": 197, "endColumn": 26, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -165,9 +155,9 @@ "severity": "ERROR" }, { - "line": 193, + "line": 198, "column": 5, - "endLine": 195, + "endLine": 200, "endColumn": 6, "problem": "ObjectLiteralProperty", "suggest": "", @@ -175,9 +165,9 @@ "severity": "ERROR" }, { - "line": 198, + "line": 203, "column": 29, - "endLine": 198, + "endLine": 203, "endColumn": 30, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -185,9 +175,9 @@ "severity": "ERROR" }, { - "line": 199, + "line": 204, "column": 5, - "endLine": 201, + "endLine": 206, "endColumn": 6, "problem": "ObjectLiteralProperty", "suggest": "", @@ -195,9 +185,9 @@ "severity": "ERROR" }, { - "line": 209, + "line": 214, "column": 26, - "endLine": 209, + "endLine": 214, "endColumn": 27, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -205,9 +195,9 @@ "severity": "ERROR" }, { - "line": 210, + "line": 215, "column": 5, - "endLine": 212, + "endLine": 217, "endColumn": 6, "problem": "ObjectLiteralProperty", "suggest": "", @@ -215,9 +205,9 @@ "severity": "ERROR" }, { - "line": 214, + "line": 219, "column": 27, - "endLine": 214, + "endLine": 219, "endColumn": 28, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -225,9 +215,9 @@ "severity": "ERROR" }, { - "line": 215, + "line": 220, "column": 5, - "endLine": 217, + "endLine": 222, "endColumn": 6, "problem": "ObjectLiteralProperty", "suggest": "", @@ -235,9 +225,9 @@ "severity": "ERROR" }, { - "line": 221, + "line": 226, "column": 27, - "endLine": 221, + "endLine": 226, "endColumn": 28, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -245,9 +235,9 @@ "severity": "ERROR" }, { - "line": 222, + "line": 227, "column": 5, - "endLine": 224, + "endLine": 229, "endColumn": 6, "problem": "ObjectLiteralProperty", "suggest": "", @@ -255,9 +245,9 @@ "severity": "ERROR" }, { - "line": 233, + "line": 238, "column": 14, - "endLine": 233, + "endLine": 238, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -265,9 +255,9 @@ "severity": "ERROR" }, { - "line": 244, + "line": 249, "column": 3, - "endLine": 244, + "endLine": 249, "endColumn": 9, "problem": "ObjectLiteralProperty", "suggest": "", @@ -275,9 +265,9 @@ "severity": "ERROR" }, { - "line": 251, + "line": 256, "column": 14, - "endLine": 251, + "endLine": 256, "endColumn": 15, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -285,9 +275,9 @@ "severity": "ERROR" }, { - "line": 262, + "line": 267, "column": 3, - "endLine": 262, + "endLine": 267, "endColumn": 9, "problem": "ObjectLiteralProperty", "suggest": "", @@ -295,9 +285,19 @@ "severity": "ERROR" }, { - "line": 284, + "line": 286, + "column": 16, + "endLine": 286, + "endColumn": 29, + "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": 289, "column": 20, - "endLine": 284, + "endLine": 289, "endColumn": 21, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -305,9 +305,9 @@ "severity": "ERROR" }, { - "line": 285, + "line": 290, "column": 3, - "endLine": 285, + "endLine": 290, "endColumn": 28, "problem": "ObjectLiteralProperty", "suggest": "", @@ -315,19 +315,19 @@ "severity": "ERROR" }, { - "line": 315, - "column": 11, - "endLine": 315, - "endColumn": 12, - "problem": "ObjectLiteralNoContextType", + "line": 342, + "column": 5, + "endLine": 342, + "endColumn": 6, + "problem": "MethodInheritRule", "suggest": "", - "rule": "Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)", + "rule": "Overridden method parameters and return types must respect type inheritance principles (arkts-method-inherit-rule)", "severity": "ERROR" }, { - "line": 240, + "line": 245, "column": 3, - "endLine": 240, + "endLine": 245, "endColumn": 4, "problem": "StrictDiagnostic", "suggest": "Property 'b' has no initializer and is not definitely assigned in the constructor.", diff --git a/ets2panda/linter/test/main/parameter_properties.ets.arkts2.json b/ets2panda/linter/test/main/parameter_properties.ets.arkts2.json index 70d8cbcfa4..a4cd69b217 100644 --- a/ets2panda/linter/test/main/parameter_properties.ets.arkts2.json +++ b/ets2panda/linter/test/main/parameter_properties.ets.arkts2.json @@ -84,6 +84,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 34, + "column": 33, + "endLine": 34, + "endColumn": 34, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, { "line": 34, "column": 26, diff --git a/ets2panda/linter/test/main/parameter_properties.ets.autofix.json b/ets2panda/linter/test/main/parameter_properties.ets.autofix.json index cd0ccd75ee..6e139d8b9e 100644 --- a/ets2panda/linter/test/main/parameter_properties.ets.autofix.json +++ b/ets2panda/linter/test/main/parameter_properties.ets.autofix.json @@ -269,6 +269,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 34, + "column": 33, + "endLine": 34, + "endColumn": 34, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, { "line": 34, "column": 26, diff --git a/ets2panda/linter/test/main/parameter_properties.ets.migrate.json b/ets2panda/linter/test/main/parameter_properties.ets.migrate.json index 03cac9f4e4..f5bbbab541 100644 --- a/ets2panda/linter/test/main/parameter_properties.ets.migrate.json +++ b/ets2panda/linter/test/main/parameter_properties.ets.migrate.json @@ -14,6 +14,16 @@ "limitations under the License." ], "result": [ + { + "line": 43, + "column": 24, + "endLine": 43, + "endColumn": 25, + "problem": "DefaultArgsBehindRequiredArgs", + "suggest": "", + "rule": "Default parameters must be placed after mandatory parameters (arkts-default-args-behind-required-args)", + "severity": "ERROR" + }, { "line": 54, "column": 15, diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets similarity index 100% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.args.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.args.json new file mode 100644 index 0000000000..ee0734c0fc --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_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/main/prop_decorator_and_interfaces_1.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.arkts2.json similarity index 68% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.arkts2.json index 2bf08fd4cc..a652bb026f 100644 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.arkts2.json @@ -61,7 +61,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -71,17 +71,7 @@ "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)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +81,7 @@ "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"StorageLink\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +91,7 @@ "endColumn": 20, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"LocalStorageLink\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,27 +101,7 @@ "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)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.autofix.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.autofix.json new file mode 100644 index 0000000000..7749390fd7 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.autofix.json @@ -0,0 +1,207 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 654, + "end": 655, + "replacementText": "0.0", + "line": 18, + "column": 17, + "endLine": 18, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 33, + "problem": "PropDecoratorNotSupported", + "autofix": [ + { + "start": 704, + "end": 709, + "replacementText": "@PropRef", + "line": 24, + "column": 3, + "endLine": 24, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "\"@Prop\" decorator is not supported (arkui-no-prop-decorator)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 49, + "problem": "StoragePropDecoratorNotSupported", + "autofix": [ + { + "start": 895, + "end": 916, + "replacementText": "@StoragePropRef", + "line": 34, + "column": 3, + "endLine": 34, + "endColumn": 49 + } + ], + "suggest": "", + "rule": "\"@StorageProp\" decorator is not supported (arkui-no-storageprop-decorator)", + "severity": "ERROR" + }, + { + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 54, + "problem": "LocalStoragePropDecoratorNotSupported", + "autofix": [ + { + "start": 944, + "end": 970, + "replacementText": "@LocalStoragePropRef", + "line": 35, + "column": 3, + "endLine": 35, + "endColumn": 54 + } + ], + "suggest": "", + "rule": "\"@LocalStorageProp\" decorator is not supported (arkui-no-localstorageprop-decorator)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 2, + "endLine": 21, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 2, + "endLine": 22, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 4, + "endLine": 25, + "endColumn": 15, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"StorageLink\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 4, + "endLine": 26, + "endColumn": 20, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"LocalStorageLink\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ 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_decorators_and_interfaces_1.ets.json similarity index 94% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.json index 4acc088d1d..ca88f857e9 100644 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.args.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.json @@ -13,7 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "mode": { - "arkts2": "" - } + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.ets b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.ets new file mode 100644 index 0000000000..15f5527cbf --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.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. + */ + +import { PropRef, StoragePropRef, LocalStoragePropRef } from '@kit.ArkUI'; + +import { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI'; + +class User { + name: string = "" + age: number = 0.0 +} + +@Entry +@Component +struct FatherComponent { + @PropRef user1: User = new User() + @StorageLink("user2") user2: User = new User() + @LocalStorageLink("user3") user3: User = new User() + + build() { + } +} + +@Component +struct ChildComponent { + @StoragePropRef user2: User = new User() + @LocalStoragePropRef user3: User = new User() + + build() { + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/debugger_statememt.ets.autofix.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.json similarity index 52% rename from ets2panda/linter/test/main/debugger_statememt.ets.autofix.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.json index 6c9d73e3d1..671d92eb76 100644 --- a/ets2panda/linter/test/main/debugger_statememt.ets.autofix.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.json @@ -15,37 +15,33 @@ ], "result": [ { - "line": 16, - "column": 1, - "endLine": 16, - "endColumn": 10, - "problem": "DebuggerStatement", - "autofix": [ - { - "start": 605, - "end": 614, - "replacementText": "specialAutofixLib.debugger();" - } - ], + "line": 28, + "column": 3, + "endLine": 28, + "endColumn": 11, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 3, + "endLine": 38, + "endColumn": 18, + "problem": "DecoratorsNotSupported", "suggest": "", - "rule": "\"debugger\" is not supported (arkts-no-debugger-stmt)", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", "severity": "ERROR" }, { - "line": 19, + "line": 39, "column": 3, - "endLine": 19, - "endColumn": 12, - "problem": "DebuggerStatement", - "autofix": [ - { - "start": 633, - "end": 642, - "replacementText": "specialAutofixLib.debugger();" - } - ], + "endLine": 39, + "endColumn": 23, + "problem": "DecoratorsNotSupported", "suggest": "", - "rule": "\"debugger\" is not supported (arkts-no-debugger-stmt)", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets b/ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets similarity index 100% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets.args.json similarity index 100% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_1.ets.args.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets.args.json diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets.arkts2.json similarity index 84% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets.arkts2.json index 791b77c85e..4ab5760d4b 100644 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets.arkts2.json @@ -281,7 +281,7 @@ "endColumn": 26, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"LocalStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -291,7 +291,7 @@ "endColumn": 45, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"LocalStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -301,7 +301,7 @@ "endColumn": 38, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SubscribedAbstractProperty\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -311,7 +311,7 @@ "endColumn": 38, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SubscribedAbstractProperty\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -321,7 +321,7 @@ "endColumn": 38, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SubscribedAbstractProperty\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -331,7 +331,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -341,7 +341,7 @@ "endColumn": 23, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -351,7 +351,7 @@ "endColumn": 23, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -361,7 +361,7 @@ "endColumn": 23, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -371,7 +371,7 @@ "endColumn": 39, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SubscribedAbstractProperty\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -381,7 +381,7 @@ "endColumn": 60, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -391,7 +391,7 @@ "endColumn": 39, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SubscribedAbstractProperty\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -401,7 +401,7 @@ "endColumn": 62, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -411,7 +411,7 @@ "endColumn": 39, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SubscribedAbstractProperty\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -421,7 +421,7 @@ "endColumn": 71, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"AppStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -431,7 +431,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -441,7 +441,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -451,7 +451,7 @@ "endColumn": 35, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"LocalStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -461,7 +461,7 @@ "endColumn": 46, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"SubscribedAbstractProperty\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets.json similarity index 100% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_2.ets.json diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets b/ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets similarity index 100% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets.args.json similarity index 100% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_2.ets.args.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets.args.json diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets.arkts2.json similarity index 96% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets.arkts2.json index 07fee6d056..17b93fa546 100644 --- a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.arkts2.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets.arkts2.json @@ -351,7 +351,7 @@ "endColumn": 26, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"LocalStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -361,7 +361,7 @@ "endColumn": 45, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"LocalStorage\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -371,7 +371,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -381,7 +381,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets.json similarity index 100% rename from ets2panda/linter/test/main/prop_decorator_and_interfaces_3.ets.json rename to ets2panda/linter/test/main/prop_decorators_and_interfaces_3.ets.json diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets new file mode 100644 index 0000000000..4f8c44b226 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 ChildComponentOptions { + count: number; +} + +@Component +struct SuperComponent1 { + @State countOptions: ChildComponentOptions = { count: 0 } + + build() { + Column() { + ChildComponent1({ options1: this.countOptions }) + Text(`${this.countOptions.count}`) + } + } +} + +@Component +struct SuperComponent2 { + @State countOptions: ChildComponentOptions = { count: 0 } + + build() { + Column() { + ChildComponent2({ options2: this.countOptions }) + Text(`${this.countOptions.count}`) + } + } +} + +@Component +struct SuperComponent3 { + @State countOptions: ChildComponentOptions = { count: 0 } + + build() { + Column() { + ChildComponent3({ options3: this.countOptions }) + Text(`${this.countOptions.count}`) + } + } +} + +@Component +struct ChildComponent1 { + @Prop options1: ChildComponentOptions; + + build() { + Row() { + Text(`${this.options1.count}`) + Blank() + Button('+').onClick(() => { + this.options1.count++; + }) + Button('-').onClick(() => { + this.options1.count--; + }) + } + } +} + +@Component +struct ChildComponent2 { + @Prop options2: ChildComponentOptions; + + build() { + Row() { + Text(`${this.options2.count}`) + Blank() + Button('change1').onClick(() => { + this.options2.count = 1; + }) + Button('change2').onClick(() => { + this.options2.count = 1; + }) + } + } +} + +@Component +struct ChildComponent3 { + @Prop options3: ChildComponentOptions; + + build() { + Row() { + Text(`${this.options3.count}`) + Blank() + Button('+').onClick(() => { + ++this.options3.count; + }) + Button('-').onClick(() => { + --this.options3.count; + }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.args.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.args.json new file mode 100644 index 0000000000..ee0734c0fc --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.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/prop_decorators_and_interfaces_4.ets.arkts2.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.arkts2.json new file mode 100644 index 0000000000..5864532002 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.arkts2.json @@ -0,0 +1,428 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 57, + "endLine": 22, + "endColumn": 58, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 25, + "endLine": 26, + "endColumn": 52, + "problem": "PropNeedCallMethodForDeepCopy", + "suggest": "", + "rule": "Parameters decorated with \"@Prop\" need to call the specific method when receiving data to ensure deep copy of the data (arkui-prop-need-call-method-for-deep-copy)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 57, + "endLine": 34, + "endColumn": 58, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 25, + "endLine": 38, + "endColumn": 52, + "problem": "PropNeedCallMethodForDeepCopy", + "suggest": "", + "rule": "Parameters decorated with \"@Prop\" need to call the specific method when receiving data to ensure deep copy of the data (arkui-prop-need-call-method-for-deep-copy)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 57, + "endLine": 46, + "endColumn": 58, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 25, + "endLine": 50, + "endColumn": 52, + "problem": "PropNeedCallMethodForDeepCopy", + "suggest": "", + "rule": "Parameters decorated with \"@Prop\" need to call the specific method when receiving data to ensure deep copy of the data (arkui-prop-need-call-method-for-deep-copy)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 3, + "endLine": 58, + "endColumn": 41, + "problem": "PropDecoratorNotSupported", + "suggest": "", + "rule": "\"@Prop\" decorator is not supported (arkui-no-prop-decorator)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 3, + "endLine": 76, + "endColumn": 41, + "problem": "PropDecoratorNotSupported", + "suggest": "", + "rule": "\"@Prop\" decorator is not supported (arkui-no-prop-decorator)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 31, + "endLine": 83, + "endColumn": 32, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 31, + "endLine": 86, + "endColumn": 32, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 3, + "endLine": 94, + "endColumn": 41, + "problem": "PropDecoratorNotSupported", + "suggest": "", + "rule": "\"@Prop\" decorator is not supported (arkui-no-prop-decorator)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 4, + "endLine": 22, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 7, + "endLine": 27, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 4, + "endLine": 34, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 7, + "endLine": 39, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 2, + "endLine": 44, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 4, + "endLine": 46, + "endColumn": 9, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 5, + "endLine": 49, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 7, + "endLine": 51, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 2, + "endLine": 56, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 7, + "endLine": 62, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 7, + "endLine": 63, + "endColumn": 12, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 7, + "endLine": 64, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 7, + "endLine": 67, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 2, + "endLine": 74, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 5, + "endLine": 79, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 7, + "endLine": 80, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 7, + "endLine": 81, + "endColumn": 12, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 7, + "endLine": 82, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 7, + "endLine": 85, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 2, + "endLine": 92, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 5, + "endLine": 97, + "endColumn": 8, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 7, + "endLine": 98, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 7, + "endLine": 99, + "endColumn": 12, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 100, + "column": 7, + "endLine": 100, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.autofix.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.autofix.json new file mode 100644 index 0000000000..2de9a369ef --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.autofix.json @@ -0,0 +1,846 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 57, + "endLine": 22, + "endColumn": 58, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 751, + "end": 752, + "replacementText": "0.0", + "line": 22, + "column": 57, + "endLine": 22, + "endColumn": 58 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 25, + "endLine": 26, + "endColumn": 52, + "problem": "PropNeedCallMethodForDeepCopy", + "suggest": "", + "rule": "Parameters decorated with \"@Prop\" need to call the specific method when receiving data to ensure deep copy of the data (arkui-prop-need-call-method-for-deep-copy)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 57, + "endLine": 34, + "endColumn": 58, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 984, + "end": 985, + "replacementText": "0.0", + "line": 34, + "column": 57, + "endLine": 34, + "endColumn": 58 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 25, + "endLine": 38, + "endColumn": 52, + "problem": "PropNeedCallMethodForDeepCopy", + "suggest": "", + "rule": "Parameters decorated with \"@Prop\" need to call the specific method when receiving data to ensure deep copy of the data (arkui-prop-need-call-method-for-deep-copy)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 57, + "endLine": 46, + "endColumn": 58, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1217, + "end": 1218, + "replacementText": "0.0", + "line": 46, + "column": 57, + "endLine": 46, + "endColumn": 58 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 25, + "endLine": 50, + "endColumn": 52, + "problem": "PropNeedCallMethodForDeepCopy", + "suggest": "", + "rule": "Parameters decorated with \"@Prop\" need to call the specific method when receiving data to ensure deep copy of the data (arkui-prop-need-call-method-for-deep-copy)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 3, + "endLine": 58, + "endColumn": 41, + "problem": "PropDecoratorNotSupported", + "autofix": [ + { + "start": 1396, + "end": 1401, + "replacementText": "@PropRef", + "line": 58, + "column": 3, + "endLine": 58, + "endColumn": 41 + } + ], + "suggest": "", + "rule": "\"@Prop\" decorator is not supported (arkui-no-prop-decorator)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 3, + "endLine": 76, + "endColumn": 41, + "problem": "PropDecoratorNotSupported", + "autofix": [ + { + "start": 1710, + "end": 1715, + "replacementText": "@PropRef", + "line": 76, + "column": 3, + "endLine": 76, + "endColumn": 41 + } + ], + "suggest": "", + "rule": "\"@Prop\" decorator is not supported (arkui-no-prop-decorator)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 31, + "endLine": 83, + "endColumn": 32, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1895, + "end": 1896, + "replacementText": "1.0", + "line": 83, + "column": 31, + "endLine": 83, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 86, + "column": 31, + "endLine": 86, + "endColumn": 32, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1977, + "end": 1978, + "replacementText": "1.0", + "line": 86, + "column": 31, + "endLine": 86, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 3, + "endLine": 94, + "endColumn": 41, + "problem": "PropDecoratorNotSupported", + "autofix": [ + { + "start": 2040, + "end": 2045, + "replacementText": "@PropRef", + "line": 94, + "column": 3, + "endLine": 94, + "endColumn": 41 + } + ], + "suggest": "", + "rule": "\"@Prop\" decorator is not supported (arkui-no-prop-decorator)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 2, + "endLine": 20, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 4, + "endLine": 22, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 5, + "endLine": 25, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 7, + "endLine": 27, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 2, + "endLine": 32, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 4, + "endLine": 34, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 7, + "endLine": 39, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 44, + "column": 2, + "endLine": 44, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 4, + "endLine": 46, + "endColumn": 9, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 5, + "endLine": 49, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 7, + "endLine": 51, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 2, + "endLine": 56, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 7, + "endLine": 62, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 7, + "endLine": 63, + "endColumn": 12, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 7, + "endLine": 64, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 7, + "endLine": 67, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 2, + "endLine": 74, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 5, + "endLine": 79, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 7, + "endLine": 80, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 7, + "endLine": 81, + "endColumn": 12, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 7, + "endLine": 82, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 7, + "endLine": 85, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 92, + "column": 2, + "endLine": 92, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 5, + "endLine": 97, + "endColumn": 8, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Row\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 7, + "endLine": 98, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 7, + "endLine": 99, + "endColumn": 12, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Blank\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 100, + "column": 7, + "endLine": 100, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "line": 103, + "column": 7, + "endLine": 103, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.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_decorators_and_interfaces_4.ets.migrate.ets b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.ets new file mode 100644 index 0000000000..7183356197 --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.ets @@ -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 { PropRef } from '@kit.ArkUI'; + +import { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI'; + +interface ChildComponentOptions { + count: number; +} + +@Component +struct SuperComponent1 { + @State countOptions: ChildComponentOptions = { count: 0.0 } + + build() { + Column() { + ChildComponent1({ options1: this.countOptions }) + Text(`${this.countOptions.count}`) + } + } +} + +@Component +struct SuperComponent2 { + @State countOptions: ChildComponentOptions = { count: 0.0 } + + build() { + Column() { + ChildComponent2({ options2: this.countOptions }) + Text(`${this.countOptions.count}`) + } + } +} + +@Component +struct SuperComponent3 { + @State countOptions: ChildComponentOptions = { count: 0.0 } + + build() { + Column() { + ChildComponent3({ options3: this.countOptions }) + Text(`${this.countOptions.count}`) + } + } +} + +@Component +struct ChildComponent1 { + @PropRef options1: ChildComponentOptions; + + build() { + Row() { + Text(`${this.options1.count}`) + Blank() + Button('+').onClick(() => { + this.options1.count++; + }) + Button('-').onClick(() => { + this.options1.count--; + }) + } + } +} + +@Component +struct ChildComponent2 { + @PropRef options2: ChildComponentOptions; + + build() { + Row() { + Text(`${this.options2.count}`) + Blank() + Button('change1').onClick(() => { + this.options2.count = 1.0; + }) + Button('change2').onClick(() => { + this.options2.count = 1.0; + }) + } + } +} + +@Component +struct ChildComponent3 { + @PropRef options3: ChildComponentOptions; + + build() { + Row() { + Text(`${this.options3.count}`) + Blank() + Button('+').onClick(() => { + ++this.options3.count; + }) + Button('-').onClick(() => { + --this.options3.count; + }) + } + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.json new file mode 100644 index 0000000000..e9031d32bc --- /dev/null +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.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": 62, + "column": 3, + "endLine": 62, + "endColumn": 11, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 3, + "endLine": 80, + "endColumn": 11, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 3, + "endLine": 98, + "endColumn": 11, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 12, + "endLine": 62, + "endColumn": 20, + "problem": "StrictDiagnostic", + "suggest": "Property 'options1' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'options1' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 80, + "column": 12, + "endLine": 80, + "endColumn": 20, + "problem": "StrictDiagnostic", + "suggest": "Property 'options2' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'options2' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 98, + "column": 12, + "endLine": 98, + "endColumn": 20, + "problem": "StrictDiagnostic", + "suggest": "Property 'options3' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'options3' 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/property_access_by_index.ets b/ets2panda/linter/test/main/property_access_by_index.ets index a19d015480..6424bdfec8 100644 --- a/ets2panda/linter/test/main/property_access_by_index.ets +++ b/ets2panda/linter/test/main/property_access_by_index.ets @@ -182,3 +182,15 @@ class MyClass extends collections.BitVector { } } } + +class AA { + i: number = 1.0; + func(b: number) {} +} +let a: object = new AA(); +let b: AA = new AA(); +b[i] = 1.0; +a["i"] = 2.0; +(b as object)["i"] = 2.0; +(b as object)["func"](1.0); +(b as object)["func1"](1.0); 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 7341e330fa..25a9f93078 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 @@ -14,8 +14,8 @@ "limitations under the License." ], "mode": { - "autofix": "", + "autofix": "--arkts-2", "arkts2": "", - "migrate": "" + "migrate": "--arkts-2" } } 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 8bdc1c6d5d..a5f04e6564 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 @@ -124,6 +124,36 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 37, + "column": 1, + "endLine": 37, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 1, + "endLine": 39, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 41, "column": 7, @@ -494,6 +524,196 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 1, + "endLine": 74, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 1, + "endLine": 75, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 1, + "endLine": 76, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 1, + "endLine": 77, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 1, + "endLine": 78, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 1, + "endLine": 79, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 1, + "endLine": 80, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 1, + "endLine": 82, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 1, + "endLine": 83, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 1, + "endLine": 84, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 1, + "endLine": 85, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 1, + "endLine": 97, + "endColumn": 18, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 1, + "endLine": 98, + "endColumn": 17, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 1, + "endLine": 99, + "endColumn": 17, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, { "line": 105, "column": 31, @@ -674,6 +894,16 @@ "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", "severity": "ERROR" }, + { + "line": 176, + "column": 1, + "endLine": 176, + "endColumn": 10, + "problem": "LimitedStdLibNoSendableDecorator", + "suggest": "", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-sendable-decorator)", + "severity": "ERROR" + }, { "line": 177, "column": 23, @@ -723,6 +953,56 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 192, + "column": 1, + "endLine": 192, + "endColumn": 5, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 193, + "column": 1, + "endLine": 193, + "endColumn": 7, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 194, + "column": 1, + "endLine": 194, + "endColumn": 19, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 1, + "endLine": 195, + "endColumn": 22, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 196, + "column": 1, + "endLine": 196, + "endColumn": 23, + "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_access_by_index.ets.autofix.json b/ets2panda/linter/test/main/property_access_by_index.ets.autofix.json index f1ca92fec9..5125535ce1 100644 --- a/ets2panda/linter/test/main/property_access_by_index.ets.autofix.json +++ b/ets2panda/linter/test/main/property_access_by_index.ets.autofix.json @@ -14,6 +14,27 @@ "limitations under the License." ], "result": [ + { + "line": 16, + "column": 10, + "endLine": 16, + "endColumn": 21, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 662, + "end": 713, + "replacementText": "", + "line": 16, + "column": 10, + "endLine": 16, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, { "line": 22, "column": 3, @@ -34,6 +55,256 @@ "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", "severity": "ERROR" }, + { + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 23, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1158, + "end": 1176, + "replacementText": "ar1: number[] = [1, 2, 3, 4]", + "line": 33, + "column": 5, + "endLine": 33, + "endColumn": 23 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 12, + "endLine": 33, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1165, + "end": 1166, + "replacementText": "1.0", + "line": 33, + "column": 12, + "endLine": 33, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 15, + "endLine": 33, + "endColumn": 16, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1168, + "end": 1169, + "replacementText": "2.0", + "line": 33, + "column": 15, + "endLine": 33, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 18, + "endLine": 33, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1171, + "end": 1172, + "replacementText": "3.0", + "line": 33, + "column": 18, + "endLine": 33, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 21, + "endLine": 33, + "endColumn": 22, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1174, + "end": 1175, + "replacementText": "4.0", + "line": 33, + "column": 21, + "endLine": 33, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 12, + "endLine": 34, + "endColumn": 13, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1189, + "end": 1190, + "replacementText": "1.0", + "line": 34, + "column": 12, + "endLine": 34, + "endColumn": 13 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 20, + "endLine": 34, + "endColumn": 21, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1197, + "end": 1198, + "replacementText": "3.0", + "line": 34, + "column": 20, + "endLine": 34, + "endColumn": 21 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 34, + "column": 23, + "endLine": 34, + "endColumn": 24, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1200, + "end": 1201, + "replacementText": "4.0", + "line": 34, + "column": 23, + "endLine": 34, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 1, + "endLine": 37, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 1, + "endLine": 39, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 7, + "endLine": 41, + "endColumn": 24, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1260, + "end": 1277, + "replacementText": "r0: number = [1, 2, 3][1]", + "line": 41, + "column": 7, + "endLine": 41, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 5, + "endLine": 42, + "endColumn": 25, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1283, + "end": 1303, + "replacementText": "r1: number = [1, 2, 3, 4][0]", + "line": 42, + "column": 5, + "endLine": 42, + "endColumn": 25 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "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, @@ -44,6 +315,405 @@ "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", "severity": "ERROR" }, + { + "line": 53, + "column": 5, + "endLine": 53, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1422, + "end": 1436, + "replacementText": "array1: number[] = [0, 1]", + "line": 53, + "column": 5, + "endLine": 53, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 15, + "endLine": 53, + "endColumn": 16, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1432, + "end": 1433, + "replacementText": "0.0", + "line": 53, + "column": 15, + "endLine": 53, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 17, + "endLine": 53, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1434, + "end": 1435, + "replacementText": "1.0", + "line": 53, + "column": 17, + "endLine": 53, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 5, + "endLine": 54, + "endColumn": 25, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1441, + "end": 1461, + "replacementText": "array2: number[] = [1, 2, 3, 4, 5]", + "line": 54, + "column": 5, + "endLine": 54, + "endColumn": 25 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 15, + "endLine": 54, + "endColumn": 16, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1451, + "end": 1452, + "replacementText": "1.0", + "line": 54, + "column": 15, + "endLine": 54, + "endColumn": 16 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 17, + "endLine": 54, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1453, + "end": 1454, + "replacementText": "2.0", + "line": 54, + "column": 17, + "endLine": 54, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 19, + "endLine": 54, + "endColumn": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1455, + "end": 1456, + "replacementText": "3.0", + "line": 54, + "column": 19, + "endLine": 54, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 21, + "endLine": 54, + "endColumn": 22, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1457, + "end": 1458, + "replacementText": "4.0", + "line": 54, + "column": 21, + "endLine": 54, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 54, + "column": 23, + "endLine": 54, + "endColumn": 24, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1459, + "end": 1460, + "replacementText": "5.0", + "line": 54, + "column": 23, + "endLine": 54, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 25, + "endLine": 55, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1486, + "end": 1487, + "replacementText": "1.0", + "line": 55, + "column": 25, + "endLine": 55, + "endColumn": 26 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 27, + "endLine": 55, + "endColumn": 28, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1488, + "end": 1489, + "replacementText": "2.0", + "line": 55, + "column": 27, + "endLine": 55, + "endColumn": 28 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 29, + "endLine": 55, + "endColumn": 30, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1490, + "end": 1491, + "replacementText": "3.0", + "line": 55, + "column": 29, + "endLine": 55, + "endColumn": 30 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 31, + "endLine": 55, + "endColumn": 32, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1492, + "end": 1493, + "replacementText": "4.0", + "line": 55, + "column": 31, + "endLine": 55, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 33, + "endLine": 55, + "endColumn": 34, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1494, + "end": 1495, + "replacementText": "5.0", + "line": 55, + "column": 33, + "endLine": 55, + "endColumn": 34 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 30, + "endLine": 56, + "endColumn": 31, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1526, + "end": 1527, + "replacementText": "1.0", + "line": 56, + "column": 30, + "endLine": 56, + "endColumn": 31 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 32, + "endLine": 56, + "endColumn": 33, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1528, + "end": 1529, + "replacementText": "2.0", + "line": 56, + "column": 32, + "endLine": 56, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 34, + "endLine": 56, + "endColumn": 35, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1530, + "end": 1531, + "replacementText": "3.0", + "line": 56, + "column": 34, + "endLine": 56, + "endColumn": 35 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 36, + "endLine": 56, + "endColumn": 37, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1532, + "end": 1533, + "replacementText": "4.0", + "line": 56, + "column": 36, + "endLine": 56, + "endColumn": 37 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 38, + "endLine": 56, + "endColumn": 39, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1534, + "end": 1535, + "replacementText": "5.0", + "line": 56, + "column": 38, + "endLine": 56, + "endColumn": 39 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 57, "column": 5, @@ -54,6 +724,541 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 57, + "column": 14, + "endLine": 57, + "endColumn": 27, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 24, + "endLine": 57, + "endColumn": 26, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1560, + "end": 1562, + "replacementText": "10.0", + "line": 57, + "column": 24, + "endLine": 57, + "endColumn": 26 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 58, + "column": 28, + "endLine": 58, + "endColumn": 30, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1591, + "end": 1593, + "replacementText": "10.0", + "line": 58, + "column": 28, + "endLine": 58, + "endColumn": 30 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 29, + "endLine": 59, + "endColumn": 31, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1623, + "end": 1625, + "replacementText": "10.0", + "line": 59, + "column": 29, + "endLine": 59, + "endColumn": 31 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 36, + "endLine": 60, + "endColumn": 38, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1662, + "end": 1664, + "replacementText": "10.0", + "line": 60, + "column": 36, + "endLine": 60, + "endColumn": 38 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 29, + "endLine": 61, + "endColumn": 31, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1694, + "end": 1696, + "replacementText": "10.0", + "line": 61, + "column": 29, + "endLine": 61, + "endColumn": 31 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 31, + "endLine": 62, + "endColumn": 33, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1728, + "end": 1730, + "replacementText": "10.0", + "line": 62, + "column": 31, + "endLine": 62, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 63, + "column": 30, + "endLine": 63, + "endColumn": 32, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1761, + "end": 1763, + "replacementText": "10.0", + "line": 63, + "column": 30, + "endLine": 63, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 64, + "column": 31, + "endLine": 64, + "endColumn": 33, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1795, + "end": 1797, + "replacementText": "10.0", + "line": 64, + "column": 31, + "endLine": 64, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 65, + "column": 32, + "endLine": 65, + "endColumn": 34, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1830, + "end": 1832, + "replacementText": "10.0", + "line": 65, + "column": 32, + "endLine": 65, + "endColumn": 34 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 66, + "column": 32, + "endLine": 66, + "endColumn": 34, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1865, + "end": 1867, + "replacementText": "10.0", + "line": 66, + "column": 32, + "endLine": 66, + "endColumn": 34 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 67, + "column": 33, + "endLine": 67, + "endColumn": 35, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1901, + "end": 1903, + "replacementText": "10.0", + "line": 67, + "column": 33, + "endLine": 67, + "endColumn": 35 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 34, + "endLine": 68, + "endColumn": 36, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 1938, + "end": 1940, + "replacementText": "10.0", + "line": 68, + "column": 34, + "endLine": 68, + "endColumn": 36 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 1, + "endLine": 74, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 1, + "endLine": 75, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 1, + "endLine": 76, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 1, + "endLine": 77, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 1, + "endLine": 78, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 1, + "endLine": 79, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 1, + "endLine": 80, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 1, + "endLine": 82, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 1, + "endLine": 83, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 1, + "endLine": 84, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 1, + "endLine": 85, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 1, + "endLine": 97, + "endColumn": 18, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 1, + "endLine": 98, + "endColumn": 17, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 1, + "endLine": 99, + "endColumn": 17, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 31, + "endLine": 105, + "endColumn": 32, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2388, + "end": 2389, + "replacementText": "1.0", + "line": 105, + "column": 31, + "endLine": 105, + "endColumn": 32 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 33, + "endLine": 105, + "endColumn": 34, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2390, + "end": 2391, + "replacementText": "2.0", + "line": 105, + "column": 33, + "endLine": 105, + "endColumn": 34 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 35, + "endLine": 105, + "endColumn": 36, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 2392, + "end": 2393, + "replacementText": "3.0", + "line": 105, + "column": 35, + "endLine": 105, + "endColumn": 36 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 24, + "endLine": 107, + "endColumn": 39, + "problem": "ArrayIndexExprType", + "suggest": "", + "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, @@ -64,6 +1269,46 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 108, + "column": 17, + "endLine": 108, + "endColumn": 40, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 15, + "endLine": 112, + "endColumn": 38, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 20, + "endLine": 117, + "endColumn": 35, + "problem": "ArrayIndexExprType", + "suggest": "", + "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, @@ -74,6 +1319,36 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 118, + "column": 15, + "endLine": 118, + "endColumn": 36, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 13, + "endLine": 121, + "endColumn": 34, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 12, + "endLine": 139, + "endColumn": 31, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "Primitive types are normalized with their boxed type (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, { "line": 159, "column": 3, @@ -83,6 +1358,234 @@ "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" + }, + { + "line": 176, + "column": 1, + "endLine": 176, + "endColumn": 10, + "problem": "LimitedStdLibNoSendableDecorator", + "autofix": [ + { + "start": 3701, + "end": 3710, + "replacementText": "", + "line": 176, + "column": 1, + "endLine": 176, + "endColumn": 10 + } + ], + "suggest": "", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-sendable-decorator)", + "severity": "ERROR" + }, + { + "line": 177, + "column": 23, + "endLine": 177, + "endColumn": 34, + "problem": "NoNeedStdLibSendableContainer", + "autofix": [ + { + "start": 3733, + "end": 3754, + "replacementText": "BitVector", + "line": 177, + "column": 23, + "endLine": 177, + "endColumn": 34 + } + ], + "suggest": "", + "rule": "Sendable containers are not supported (arkts-no-need-stdlib-sendable-containers)", + "severity": "ERROR" + }, + { + "line": 179, + "column": 11, + "endLine": 179, + "endColumn": 12, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 3785, + "end": 3786, + "replacementText": "0.0", + "line": 179, + "column": 11, + "endLine": 179, + "endColumn": 12 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 180, + "column": 14, + "endLine": 180, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 3802, + "end": 3807, + "replacementText": "i: number = 0", + "line": 180, + "column": 14, + "endLine": 180, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 180, + "column": 18, + "endLine": 180, + "endColumn": 19, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 3806, + "end": 3807, + "replacementText": "0.0", + "line": 180, + "column": 18, + "endLine": 180, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 181, + "column": 17, + "endLine": 181, + "endColumn": 18, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 3849, + "end": 3850, + "replacementText": "1.0", + "line": 181, + "column": 17, + "endLine": 181, + "endColumn": 18 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 192, + "column": 1, + "endLine": 192, + "endColumn": 5, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 193, + "column": 1, + "endLine": 193, + "endColumn": 7, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 194, + "column": 1, + "endLine": 194, + "endColumn": 19, + "problem": "PropertyAccessByIndex", + "autofix": [ + { + "replacementText": "b.i", + "start": 3992, + "end": 4010, + "line": 194, + "column": 1, + "endLine": 194, + "endColumn": 19 + } + ], + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 1, + "endLine": 195, + "endColumn": 22, + "problem": "PropertyAccessByIndex", + "autofix": [ + { + "replacementText": "b.func", + "start": 4018, + "end": 4039, + "line": 195, + "column": 1, + "endLine": 195, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 196, + "column": 1, + "endLine": 196, + "endColumn": 23, + "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_access_by_index.ets.json b/ets2panda/linter/test/main/property_access_by_index.ets.json index f1ca92fec9..18153eceba 100644 --- a/ets2panda/linter/test/main/property_access_by_index.ets.json +++ b/ets2panda/linter/test/main/property_access_by_index.ets.json @@ -83,6 +83,16 @@ "suggest": "", "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", "severity": "ERROR" + }, + { + "line": 192, + "column": 1, + "endLine": 192, + "endColumn": 5, + "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_access_by_index.ets.migrate.ets b/ets2panda/linter/test/main/property_access_by_index.ets.migrate.ets index a19d015480..6d69629247 100644 --- a/ets2panda/linter/test/main/property_access_by_index.ets.migrate.ets +++ b/ets2panda/linter/test/main/property_access_by_index.ets.migrate.ets @@ -13,7 +13,7 @@ * limitations under the License. */ import {OhosInterface} from './oh_modules/ohos_lib'; -import { collections } from './@arkts.collections'; + // #14071 class A { v: string = ''; @@ -30,16 +30,16 @@ function test() { return GetProperty(a, 'v') + GetProperty(a, 'u'); } -let ar1 = [1, 2, 3, 4]; -let ar2 = [1, '2', 3, 4]; +let ar1: number[] = [1.0, 2.0, 3.0, 4.0]; +let ar2 = [1.0, '2', 3.0, 4.0]; let ar3: number[] = []; ar1[2]; ar2[2]; ar3[2]; -const r0 = [1, 2, 3][1]; -let r1 = [1, 2, 3, 4][0] +const r0: number = [1, 2, 3][1]; +let r1: number = [1, 2, 3, 4][0] let r2 = [1, '2', 3, 4][0] function fobject1(o: object) { @@ -50,22 +50,22 @@ 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) +let array1: number[] = [0.0, 1.0] +let array2: number[] = [1.0, 2.0, 3.0, 4.0, 5.0] +let array3: number[] = [1.0,2.0,3.0,4.0,5.0] +let array4: Array = [1.0,2.0,3.0,4.0,5.0] +let array5 = new Array(10.0) +let array6 = new Int8Array(10.0) +let array7 = new Uint8Array(10.0) +let array8 = new Uint8ClampedArray(10.0) +let array9 = new Int16Array(10.0) +let array10 = new Uint16Array(10.0) +let array11 = new Int32Array(10.0) +let array12 = new Uint32Array(10.0) +let array13 = new Float32Array(10.0) +let array14 = new Float64Array(10.0) +let array15 = new BigInt64Array(10.0) +let array16 = new BigUint64Array(10.0) array1[0]; array2[0]; @@ -102,7 +102,7 @@ CCCCCCCCC[CCCCCCCCC.KATE] CCCCCCCCC[CCCCCCCCC.BOB] CCCCCCCCC[CCCCCCCCC.ROB] -let arr32 = new Float32Array([1,2,3]) +let arr32 = new Float32Array([1.0,2.0,3.0]) let iter_arr32 = arr32[Symbol.iterator]() let tmp_arr32 = iter_arr32.next().value; @@ -173,12 +173,24 @@ mmap1[1]; mmap2['222']; mmap3["kkr"]; -@Sendable -class MyClass extends collections.BitVector { + +class MyClass extends BitVector { constructor() { - super(0); - for (let i = 0; i < this.length; i++) { - this[i] = 1; + super(0.0); + for (let i: number = 0.0; i < this.length; i++) { + this[i] = 1.0; } } } + +class AA { + i: number = 1.0; + func(b: number) {} +} +let a: object = new AA(); +let b: AA = new AA(); +b[i] = 1.0; +a["i"] = 2.0; +b.i = 2.0; +b.func(1.0); +(b as object)["func1"](1.0); diff --git a/ets2panda/linter/test/main/property_access_by_index.ets.migrate.json b/ets2panda/linter/test/main/property_access_by_index.ets.migrate.json index e700885404..3f19efdae1 100644 --- a/ets2panda/linter/test/main/property_access_by_index.ets.migrate.json +++ b/ets2panda/linter/test/main/property_access_by_index.ets.migrate.json @@ -34,6 +34,46 @@ "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", "severity": "ERROR" }, + { + "line": 37, + "column": 1, + "endLine": 37, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 1, + "endLine": 38, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 1, + "endLine": 39, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "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, @@ -48,12 +88,232 @@ "line": 57, "column": 5, "endLine": 57, - "endColumn": 27, + "endColumn": 29, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 57, + "column": 14, + "endLine": 57, + "endColumn": 29, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 1, + "endLine": 70, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 72, + "column": 1, + "endLine": 72, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 73, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 74, + "column": 1, + "endLine": 74, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 1, + "endLine": 75, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 1, + "endLine": 76, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 77, + "column": 1, + "endLine": 77, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 1, + "endLine": 78, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 79, + "column": 1, + "endLine": 79, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 1, + "endLine": 80, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 81, + "column": 1, + "endLine": 81, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 1, + "endLine": 82, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 83, + "column": 1, + "endLine": 83, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 84, + "column": 1, + "endLine": 84, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 85, + "column": 1, + "endLine": 85, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 1, + "endLine": 97, + "endColumn": 18, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 1, + "endLine": 98, + "endColumn": 17, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 1, + "endLine": 99, + "endColumn": 17, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 24, + "endLine": 107, + "endColumn": 39, + "problem": "ArrayIndexExprType", + "suggest": "", + "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, @@ -64,6 +324,46 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 108, + "column": 17, + "endLine": 108, + "endColumn": 40, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 112, + "column": 15, + "endLine": 112, + "endColumn": 38, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 20, + "endLine": 117, + "endColumn": 35, + "problem": "ArrayIndexExprType", + "suggest": "", + "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, @@ -74,6 +374,36 @@ "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, + { + "line": 118, + "column": 15, + "endLine": 118, + "endColumn": 36, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 13, + "endLine": 121, + "endColumn": 34, + "problem": "AvoidUnionTypes", + "suggest": "", + "rule": "Avoid using union types (arkts-common-union-member-access)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 12, + "endLine": 139, + "endColumn": 31, + "problem": "CreatingPrimitiveTypes", + "suggest": "", + "rule": "Primitive types are normalized with their boxed type (arkts-primitive-type-normalization)", + "severity": "ERROR" + }, { "line": 159, "column": 3, @@ -83,6 +413,76 @@ "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" + }, + { + "line": 181, + "column": 7, + "endLine": 181, + "endColumn": 14, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 192, + "column": 1, + "endLine": 192, + "endColumn": 5, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 193, + "column": 1, + "endLine": 193, + "endColumn": 7, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 196, + "column": 1, + "endLine": 196, + "endColumn": 23, + "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/props_by_index.ets b/ets2panda/linter/test/main/props_by_index.ets new file mode 100644 index 0000000000..63c685415b --- /dev/null +++ b/ets2panda/linter/test/main/props_by_index.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. + */ + +enum TEST { + A, + B, + C +} +const arr = ['a', 'b', 'c']; + +const val = TEST[1]; //error +const value: number = TEST.A; +const arrVal = arr[1]; +let a = 1; +let b = 2.3; +let c = "str"; +let d3 = TEST[TEST.A]; +let d4 = TEST[a]; //error +let d5 = TEST[b]; //error +let d2 = TEST['A']; //error +enum E { A, B, C } +console.log(E[E.A]); +function foo(e: E) { + console.log(E[e]); +} +foo(E.B); +console.log(E[2 as E]); +enum Color { Red, Green = 10, Blue } +enum E1 { One = 1, one = 1, oNe = 1 } +console.log(E1[1 as E1]) +let c1: Color = Color.Green; +console.log(c1.toString()) +console.log(Color[c1]); +enum G { + A = 1, + B = 2 +} +console.log(G[G.A]); \ 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/props_by_index.ets.args.json similarity index 100% rename from ets2panda/linter/test/main/prop_name_from_value.ets.args.json rename to ets2panda/linter/test/main/props_by_index.ets.args.json diff --git a/ets2panda/linter/test/main/global_this.ets.autofix.json b/ets2panda/linter/test/main/props_by_index.ets.arkts2.json old mode 100755 new mode 100644 similarity index 36% rename from ets2panda/linter/test/main/global_this.ets.autofix.json rename to ets2panda/linter/test/main/props_by_index.ets.arkts2.json index 95eda816e5..31386736eb --- a/ets2panda/linter/test/main/global_this.ets.autofix.json +++ b/ets2panda/linter/test/main/props_by_index.ets.arkts2.json @@ -1,6 +1,6 @@ { "copyright": [ - "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", @@ -15,188 +15,151 @@ ], "result": [ { - "line": 16, - "column": 7, - "endLine": 16, - "endColumn": 18, + "line": 23, + "column": 13, + "endLine": 23, + "endColumn": 20, + "problem": "UnsupportPropNameFromValue", + "suggest": "", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 16, + "endLine": 25, + "endColumn": 22, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 5, + "endLine": 26, + "endColumn": 10, "problem": "NumericSemantics", - "autofix": [ - { - "start": 616, - "end": 627, - "replacementText": "pi: number = 3.1416", - "line": 16, - "column": 7, - "endLine": 16, - "endColumn": 18 - } - ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 19, - "column": 7, - "endLine": 19, - "endColumn": 17, - "problem": "GlobalThisError", + "line": 26, + "column": 9, + "endLine": 26, + "endColumn": 10, + "problem": "NumericSemantics", "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 21, - "column": 10, - "endLine": 21, - "endColumn": 23, - "problem": "GlobalThisError", - "autofix": [ - { - "start": 700, - "end": 713, - "replacementText": "specialAutofixLib.globalThis.get(\"pi\")", - "line": 21, - "column": 10, - "endLine": 21, - "endColumn": 23 - } - ], + "line": 27, + "column": 5, + "endLine": 27, + "endColumn": 12, + "problem": "NumericSemantics", "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 24, - "column": 17, - "endLine": 24, - "endColumn": 20, - "problem": "AnyType", + "line": 30, + "column": 10, + "endLine": 30, + "endColumn": 17, + "problem": "UnsupportPropNameFromValue", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", "severity": "ERROR" }, { - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 21, - "problem": "GlobalThisError", - "autofix": [ - { - "start": 779, - "end": 799, - "replacementText": "specialAutofixLib.globalThis.set(\"abc\", 200)", - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 21 - } - ], + "line": 31, + "column": 10, + "endLine": 31, + "endColumn": 17, + "problem": "UnsupportPropNameFromValue", "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", "severity": "ERROR" }, { - "line": 28, - "column": 18, - "endLine": 28, - "endColumn": 21, + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 19, "problem": "NumericSemantics", - "autofix": [ - { - "start": 796, - "end": 799, - "replacementText": "200.0", - "line": 28, - "column": 18, - "endLine": 28, - "endColumn": 21 - } - ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 30, - "column": 7, - "endLine": 30, - "endColumn": 34, - "problem": "AnyType", + "line": 32, + "column": 10, + "endLine": 32, + "endColumn": 19, + "problem": "UnsupportPropNameFromValue", "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "rule": "Enum cannot get member name by member value (arkts-enum-no-props-by-index)", "severity": "ERROR" }, { - "line": 30, - "column": 15, - "endLine": 30, + "line": 40, + "column": 27, + "endLine": 40, "endColumn": 29, - "problem": "GlobalThisError", - "autofix": [ - { - "start": 816, - "end": 830, - "replacementText": "specialAutofixLib.globalThis.get(\"obj\")", - "line": 30, - "column": 15, - "endLine": 30, - "endColumn": 29 - } - ], + "problem": "NumericSemantics", "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 32, - "column": 1, - "endLine": 32, - "endColumn": 7, - "problem": "DeleteOperator", + "line": 41, + "column": 17, + "endLine": 41, + "endColumn": 18, + "problem": "NumericSemantics", "suggest": "", - "rule": "\"delete\" operator is not supported (arkts-no-delete)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 32, - "column": 8, - "endLine": 32, + "line": 41, + "column": 26, + "endLine": 41, "endColumn": 27, - "problem": "GlobalThisError", - "autofix": [ - { - "start": 845, - "end": 864, - "replacementText": "specialAutofixLib.globalThis.get(\"property\")", - "line": 32, - "column": 8, - "endLine": 32, - "endColumn": 27 - } - ], + "problem": "NumericSemantics", "suggest": "", - "rule": "\"globalThis\" is not supported (arkts-no-globalthis)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 35, + "endLine": 41, + "endColumn": 36, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 34, - "column": 18, - "endLine": 34, - "endColumn": 21, + "line": 47, + "column": 7, + "endLine": 47, + "endColumn": 8, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 7, + "endLine": 48, + "endColumn": 8, "problem": "NumericSemantics", - "autofix": [ - { - "start": 884, - "end": 887, - "replacementText": "100.0", - "line": 34, - "column": 18, - "endLine": 34, - "endColumn": 21 - } - ], "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" diff --git a/ets2panda/linter/test/main/props_by_index.ets.json b/ets2panda/linter/test/main/props_by_index.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/props_by_index.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/provide_annotation_1.ets.arkts2.json b/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json index a11e915085..e8bb63999f 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/provide_annotation_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", @@ -41,7 +41,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (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 499fa5b296..16e13e0bf2 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.autofix.json @@ -24,7 +24,11 @@ { "start": 727, "end": 744, - "replacementText": "@Provide({ alias: \"value\" })" + "replacementText": "@Provide({ alias: \"value\" })", + "line": 28, + "column": 3, + "endLine": 29, + "endColumn": 17 } ], "suggest": "", @@ -41,7 +45,11 @@ { "start": 830, "end": 864, - "replacementText": "@Provide({ alias: \"value\", allowOverride: true })" + "replacementText": "@Provide({ alias: \"value\", allowOverride: true })", + "line": 38, + "column": 3, + "endLine": 39, + "endColumn": 17 } ], "suggest": "", @@ -58,11 +66,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -75,11 +87,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -92,11 +108,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -109,11 +129,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -126,11 +150,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -143,11 +171,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -160,11 +192,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -177,11 +213,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -194,11 +234,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { 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 5683673096..2b7ce66f0b 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.arkts2.json @@ -21,7 +21,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -31,7 +31,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -41,7 +41,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -51,7 +51,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -61,7 +61,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (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 f828839e12..8a98dfc2d8 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json @@ -24,11 +24,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -41,11 +45,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -58,11 +66,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -75,11 +87,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -92,11 +108,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -109,11 +129,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -126,11 +150,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -143,11 +171,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Provide\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -160,11 +192,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';" + "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 11 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets b/ets2panda/linter/test/main/runtime_array_bound.ets index 435c6ac0e6..5540265166 100644 --- a/ets2panda/linter/test/main/runtime_array_bound.ets +++ b/ets2panda/linter/test/main/runtime_array_bound.ets @@ -86,5 +86,82 @@ newIndex = 22; arr10[newIndex]; +let arr = [0, 1, 2, 3, 4, 5] +for(let i = 0; i < arr.length; i++) { +arr[i] = arr[i] + 1; +} +for(let i = 0; i < arr.length; i++) { +i = 10; +arr[i] = arr[i] + 1; +} + +let arr = [0, 1, 2, 3, 4, 5] +let idx = 2; +if(idx > 0 && idx < arr.length) { +arr[idx] = arr[idx] + 1; +} +if(idx > 0 && idx < arr.length) { +idx = 10; +arr[idx] = arr[idx] + 1; +} + +let arr = [0, 1, 2, 3, 4, 5] +let idx = 0; +while(idx > 0 && idx < arr.length) { +arr[idx] = arr[idx] + 1; +idx++; +idx = 10; +} +while(idx > 0 && idx < arr.length) { +idx = 10; +arr[idx] = arr[idx] + 1; +} + +let arr = [0, 1, 2, 3, 4, 5] +let idx = 0; +arr[idx]; +arr[10]; +if (arr.length > 10) { +arr[10] = 10; +} + +function foo():int{ +return 1; +} +arr[44/3]; +arr[foo()]; +arr[()=>{return 1}]; +if(arr.length > foo()) { +arr[foo()]; +} +if(arr.length > 44/3) { +arr[4*4/3]; +} + +let arr1:number[] = [1, 1.5,45,2] + +function foo(i:number):number{ + return i; +} + +arr1[3*5] = 23; +arr1[parseInt("16")] = 23; +arr1[foo(16)] = 23 + +let arr1:number[] = [1, 1.5,45,2] + +arr1[Number.MAX_VALUE] = 23; +arr1[Number.MAX_SAFE_INTEGER] = 23; + +let arr1:number[] = [1, 1.5,45,2] +function foo(i:number):number{ + return i; +} +arr1[(24)] = 23; +arr1[+24] = 23; +enum TE{ + AA = 12 +} +arr1[TE.AA] = 12; diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json b/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json index ee17b482f0..fb3f014d24 100644 --- a/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json @@ -144,16 +144,6 @@ "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, @@ -184,6 +174,16 @@ "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": 32, "column": 22, @@ -224,16 +224,6 @@ "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, @@ -254,6 +244,16 @@ "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": 37, "column": 22, @@ -304,16 +304,6 @@ "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, @@ -374,16 +364,6 @@ "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, @@ -414,6 +394,16 @@ "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": 49, "column": 22, @@ -464,6 +454,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 51, + "column": 5, + "endLine": 51, + "endColumn": 13, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 54, "column": 22, @@ -514,6 +514,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 59, + "column": 1, + "endLine": 59, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 61, "column": 22, @@ -584,16 +594,6 @@ "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": 69, "column": 22, @@ -634,16 +634,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "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": 70, "column": 19, @@ -704,16 +694,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 76, - "column": 5, - "endLine": 76, - "endColumn": 10, - "problem": "RuntimeArrayCheck", - "suggest": "", - "rule": "Array bound not checked. (arkts-runtime-array-check)", - "severity": "ERROR" - }, { "line": 75, "column": 13, @@ -803,6 +783,1076 @@ "suggest": "", "rule": "Array bound not checked. (arkts-runtime-array-check)", "severity": "ERROR" + }, + { + "line": 89, + "column": 5, + "endLine": 89, + "endColumn": 29, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 12, + "endLine": 89, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 15, + "endLine": 89, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 18, + "endLine": 89, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 21, + "endLine": 89, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 24, + "endLine": 89, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 27, + "endLine": 89, + "endColumn": 28, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 9, + "endLine": 90, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 90, + "column": 13, + "endLine": 90, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 19, + "endLine": 91, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 93, + "column": 9, + "endLine": 93, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 93, + "column": 13, + "endLine": 93, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 5, + "endLine": 94, + "endColumn": 7, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 1, + "endLine": 95, + "endColumn": 7, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 10, + "endLine": 95, + "endColumn": 16, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 95, + "column": 19, + "endLine": 95, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 5, + "endLine": 98, + "endColumn": 29, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 12, + "endLine": 98, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 15, + "endLine": 98, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 18, + "endLine": 98, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 21, + "endLine": 98, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 24, + "endLine": 98, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 27, + "endLine": 98, + "endColumn": 28, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 5, + "endLine": 99, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 11, + "endLine": 99, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 100, + "column": 10, + "endLine": 100, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 101, + "column": 23, + "endLine": 101, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 103, + "column": 10, + "endLine": 103, + "endColumn": 11, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 104, + "column": 7, + "endLine": 104, + "endColumn": 9, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 1, + "endLine": 105, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 12, + "endLine": 105, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 23, + "endLine": 105, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 5, + "endLine": 108, + "endColumn": 29, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 12, + "endLine": 108, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 15, + "endLine": 108, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 18, + "endLine": 108, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 21, + "endLine": 108, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 24, + "endLine": 108, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 108, + "column": 27, + "endLine": 108, + "endColumn": 28, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 5, + "endLine": 109, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 109, + "column": 11, + "endLine": 109, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 110, + "column": 13, + "endLine": 110, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 111, + "column": 23, + "endLine": 111, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 113, + "column": 7, + "endLine": 113, + "endColumn": 9, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 115, + "column": 13, + "endLine": 115, + "endColumn": 14, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 7, + "endLine": 116, + "endColumn": 9, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 1, + "endLine": 117, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 12, + "endLine": 117, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 117, + "column": 23, + "endLine": 117, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 5, + "endLine": 120, + "endColumn": 29, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 12, + "endLine": 120, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 15, + "endLine": 120, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 18, + "endLine": 120, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 21, + "endLine": 120, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 24, + "endLine": 120, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 120, + "column": 27, + "endLine": 120, + "endColumn": 28, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 5, + "endLine": 121, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 121, + "column": 11, + "endLine": 121, + "endColumn": 12, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 122, + "column": 1, + "endLine": 122, + "endColumn": 9, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 123, + "column": 1, + "endLine": 123, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 124, + "column": 18, + "endLine": 124, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 1, + "endLine": 125, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 11, + "endLine": 125, + "endColumn": 13, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 1, + "endLine": 130, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 129, + "column": 8, + "endLine": 129, + "endColumn": 9, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 1, + "endLine": 132, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 132, + "column": 5, + "endLine": 132, + "endColumn": 9, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 133, + "column": 1, + "endLine": 133, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 1, + "endLine": 134, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 134, + "column": 5, + "endLine": 134, + "endColumn": 19, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 1, + "endLine": 136, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 17, + "endLine": 138, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 20, + "endLine": 138, + "endColumn": 21, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 1, + "endLine": 139, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 139, + "column": 5, + "endLine": 139, + "endColumn": 10, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 22, + "endLine": 142, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 29, + "endLine": 142, + "endColumn": 31, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 142, + "column": 32, + "endLine": 142, + "endColumn": 33, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 144, + "column": 1, + "endLine": 146, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 1, + "endLine": 148, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 13, + "endLine": 148, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 1, + "endLine": 149, + "endColumn": 21, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 6, + "endLine": 149, + "endColumn": 20, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 149, + "column": 24, + "endLine": 149, + "endColumn": 26, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 1, + "endLine": 150, + "endColumn": 14, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 6, + "endLine": 150, + "endColumn": 13, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 150, + "column": 17, + "endLine": 150, + "endColumn": 19, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 22, + "endLine": 152, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 29, + "endLine": 152, + "endColumn": 31, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 152, + "column": 32, + "endLine": 152, + "endColumn": 33, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 1, + "endLine": 154, + "endColumn": 23, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 6, + "endLine": 154, + "endColumn": 22, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 154, + "column": 26, + "endLine": 154, + "endColumn": 28, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 1, + "endLine": 155, + "endColumn": 30, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 6, + "endLine": 155, + "endColumn": 29, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 155, + "column": 33, + "endLine": 155, + "endColumn": 35, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 157, + "column": 22, + "endLine": 157, + "endColumn": 23, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 157, + "column": 29, + "endLine": 157, + "endColumn": 31, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 157, + "column": 32, + "endLine": 157, + "endColumn": 33, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 1, + "endLine": 160, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 161, + "column": 1, + "endLine": 161, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 161, + "column": 14, + "endLine": 161, + "endColumn": 16, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 162, + "column": 1, + "endLine": 162, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 162, + "column": 13, + "endLine": 162, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 164, + "column": 8, + "endLine": 164, + "endColumn": 10, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 166, + "column": 1, + "endLine": 166, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 166, + "column": 15, + "endLine": 166, + "endColumn": 17, + "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/main/runtime_array_bound.ets.migrate.ets b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets index 3ac6cbf343..2d4beff418 100644 --- a/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets @@ -86,5 +86,82 @@ newIndex = 22.0; arr10[newIndex as int]; +let arr: number[] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +for(let i: number = 0.0; i < arr.length; i++) { +arr[i as int] = arr[i as int] + 1.0; +} +for(let i: number = 0.0; i < arr.length; i++) { +i = 10.0; +arr[i as int] = arr[i as int] + 1.0; +} + +let arr: number[] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +let idx: number = 2.0; +if(idx > 0.0 && idx < arr.length) { +arr[idx as int] = arr[idx as int] + 1.0; +} +if(idx > 0.0 && idx < arr.length) { +idx = 10.0; +arr[idx as int] = arr[idx as int] + 1.0; +} + +let arr: number[] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +let idx: number = 0.0; +while(idx > 0.0 && idx < arr.length) { +arr[idx as int] = arr[idx as int] + 1.0; +idx++; +idx = 10.0; +} +while(idx > 0.0 && idx < arr.length) { +idx = 10.0; +arr[idx as int] = arr[idx as int] + 1.0; +} + +let arr: number[] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +let idx: number = 0.0; +arr[idx as int]; +arr[10]; +if (arr.length > 10.0) { +arr[10] = 10.0; +} + +function foo():int{ +return 1.0; +} +arr[(44/3) as int]; +arr[foo()]; +arr[()=>{return 1}]; +if(arr.length > foo()) { +arr[foo()]; +} +if(arr.length > 44.0/3.0) { +arr[(4*4/3) as int]; +} + +let arr1:number[] = [1.0, 1.5,45.0,2.0] + +function foo(i:number):number{ + return i; +} + +arr1[3*5] = 23.0; +arr1[parseInt("16") as int] = 23.0; +arr1[foo(16) as int] = 23.0 + +let arr1:number[] = [1.0, 1.5,45.0,2.0] + +arr1[Number.MAX_VALUE as int] = 23.0; +arr1[Number.MAX_SAFE_INTEGER as int] = 23.0; + +let arr1:number[] = [1.0, 1.5,45.0,2.0] +function foo(i:number):number{ + return i; +} +arr1[(24)] = 23.0; +arr1[+24] = 23.0; +enum TE{ + AA = 12.0 +} +arr1[TE.AA] = 12.0; diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.json b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.json index 2801165e5d..a5dcce18b3 100644 --- a/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.json +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.json @@ -35,44 +35,154 @@ "severity": "ERROR" }, { - "line": 40, + "line": 51, "column": 5, - "endLine": 40, - "endColumn": 12, + "endLine": 51, + "endColumn": 13, "problem": "RuntimeArrayCheck", "suggest": "", "rule": "Array bound not checked. (arkts-runtime-array-check)", "severity": "ERROR" }, { - "line": 67, + "line": 59, "column": 1, - "endLine": 67, - "endColumn": 12, + "endLine": 59, + "endColumn": 9, "problem": "RuntimeArrayCheck", "suggest": "", "rule": "Array bound not checked. (arkts-runtime-array-check)", "severity": "ERROR" }, { - "line": 71, - "column": 5, - "endLine": 71, - "endColumn": 16, + "line": 123, + "column": 1, + "endLine": 123, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 125, + "column": 1, + "endLine": 125, + "endColumn": 8, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 128, + "column": 1, + "endLine": 130, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 133, + "column": 1, + "endLine": 133, + "endColumn": 11, "problem": "RuntimeArrayCheck", "suggest": "", "rule": "Array bound not checked. (arkts-runtime-array-check)", "severity": "ERROR" }, { - "line": 76, + "line": 134, + "column": 1, + "endLine": 134, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 134, "column": 5, - "endLine": 76, + "endLine": 134, + "endColumn": 19, + "problem": "ArrayIndexExprType", + "suggest": "", + "rule": "The index expression must be of a numeric type (arkts-array-index-expr-type)", + "severity": "ERROR" + }, + { + "line": 136, + "column": 1, + "endLine": 136, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 144, + "column": 1, + "endLine": 146, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 148, + "column": 1, + "endLine": 148, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 1, + "endLine": 160, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 161, + "column": 1, + "endLine": 161, + "endColumn": 11, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 162, + "column": 1, + "endLine": 162, "endColumn": 10, "problem": "RuntimeArrayCheck", "suggest": "", "rule": "Array bound not checked. (arkts-runtime-array-check)", "severity": "ERROR" + }, + { + "line": 166, + "column": 1, + "endLine": 166, + "endColumn": 12, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" } ] } diff --git a/ets2panda/linter/test/main/stdlib_array.ets.arkts2.json b/ets2panda/linter/test/main/stdlib_array.ets.arkts2.json index 071dffbe54..f7b6b0c4e8 100644 --- a/ets2panda/linter/test/main/stdlib_array.ets.arkts2.json +++ b/ets2panda/linter/test/main/stdlib_array.ets.arkts2.json @@ -224,6 +224,26 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 49, + "column": 12, + "endLine": 49, + "endColumn": 16, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 19, + "endLine": 49, + "endColumn": 23, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 53, "column": 10, diff --git a/ets2panda/linter/test/main/structural_identity.ets b/ets2panda/linter/test/main/structural_identity.ets index eae4133097..406a7fee8e 100644 --- a/ets2panda/linter/test/main/structural_identity.ets +++ b/ets2panda/linter/test/main/structural_identity.ets @@ -692,4 +692,15 @@ interface goodPerson extends IPerson { sayHello:()=> { return new MyObj2() } - } \ No newline at end of file + } + + async function foo1(): Promise{ + + return new Promise(()=>{ + + }); +} + +function foo2(rule:Record){ + let b:Array = rule['123'] as Array +} \ 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 1a9ca3c7cf..89cd070221 100644 --- a/ets2panda/linter/test/main/structural_identity.ets.arkts2.json +++ b/ets2panda/linter/test/main/structural_identity.ets.arkts2.json @@ -64,6 +64,16 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, + { + "line": 54, + "column": 3, + "endLine": 54, + "endColumn": 10, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 57, "column": 13, @@ -984,6 +994,26 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, + { + "line": 480, + "column": 1, + "endLine": 480, + "endColumn": 10, + "problem": "LimitedStdLibNoSendableDecorator", + "suggest": "", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-sendable-decorator)", + "severity": "ERROR" + }, + { + "line": 485, + "column": 1, + "endLine": 485, + "endColumn": 10, + "problem": "LimitedStdLibNoSendableDecorator", + "suggest": "", + "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-sendable-decorator)", + "severity": "ERROR" + }, { "line": 502, "column": 7, @@ -1583,6 +1613,16 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 699, + "column": 14, + "endLine": 699, + "endColumn": 21, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/structural_identity_extended_inheritance.ets.arkts2.json b/ets2panda/linter/test/main/structural_identity_extended_inheritance.ets.arkts2.json index d99589819b..72f2d82336 100644 --- a/ets2panda/linter/test/main/structural_identity_extended_inheritance.ets.arkts2.json +++ b/ets2panda/linter/test/main/structural_identity_extended_inheritance.ets.arkts2.json @@ -164,6 +164,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 56, + "column": 1, + "endLine": 56, + "endColumn": 18, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 73, "column": 1, 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 3b45c45182..b63b7b7e89 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 @@ -61,7 +61,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -71,7 +71,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -81,7 +81,7 @@ "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 31, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (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 a6ab4947d5..caa81eea0f 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 @@ -116,7 +116,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -137,7 +137,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -158,7 +158,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -179,7 +179,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -200,7 +200,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 8ecdfbedea..c5ef980975 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 @@ -91,7 +91,7 @@ "endColumn": 23, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 17, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 31, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 18, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -161,7 +161,7 @@ "endColumn": 13, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -171,7 +171,7 @@ "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (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 6327fe8134..bbd292d197 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 @@ -197,7 +197,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -218,7 +218,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -239,7 +239,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -260,7 +260,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -281,7 +281,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -302,7 +302,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -323,7 +323,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -344,7 +344,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -365,7 +365,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json index b0c53b4c8e..8879e846e8 100644 --- a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json @@ -81,7 +81,7 @@ "endColumn": 27, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -91,7 +91,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -101,7 +101,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +111,7 @@ "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +121,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +131,7 @@ "endColumn": 27, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +141,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -151,7 +151,7 @@ "endColumn": 31, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -161,7 +161,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -171,7 +171,7 @@ "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -181,7 +181,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -191,7 +191,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -201,7 +201,7 @@ "endColumn": 31, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -211,7 +211,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -231,7 +231,7 @@ "endColumn": 33, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -241,7 +241,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -251,7 +251,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -261,7 +261,7 @@ "endColumn": 33, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (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 index a84810a9e7..bca7d3fc19 100644 --- a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.autofix.json @@ -24,7 +24,11 @@ { "start": 605, "end": 673, - "replacementText": "function NormalStyles(instance: CommonMethod): void {\n instance.backgroundColor(Color.Blue);\n}" + "replacementText": "function NormalStyles(instance: CommonMethod): void {\n instance.backgroundColor(Color.Blue);\n}", + "line": 16, + "column": 1, + "endLine": 19, + "endColumn": 2 } ], "suggest": "", @@ -41,7 +45,11 @@ { "start": 765, "end": 830, - "replacementText": "PressedStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Green);\n };" + "replacementText": "PressedStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Green);\n };", + "line": 28, + "column": 3, + "endLine": 31, + "endColumn": 4 } ], "suggest": "", @@ -58,7 +66,11 @@ { "start": 912, "end": 1044, - "replacementText": "{\n pressed: this.PressedStyles,\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }" + "replacementText": "{\n pressed: this.PressedStyles,\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }", + "line": 37, + "column": 18, + "endLine": 43, + "endColumn": 6 } ], "suggest": "", @@ -75,7 +87,11 @@ { "start": 1214, "end": 1312, - "replacementText": "{\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }" + "replacementText": "{\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }", + "line": 57, + "column": 18, + "endLine": 62, + "endColumn": 6 } ], "suggest": "", @@ -92,7 +108,11 @@ { "start": 1407, "end": 1514, - "replacementText": "{\n normal: NormalStyles,\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n }\n }" + "replacementText": "{\n normal: NormalStyles,\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n }\n }", + "line": 71, + "column": 20, + "endLine": 76, + "endColumn": 8 } ], "suggest": "", @@ -109,7 +129,11 @@ { "start": 1609, "end": 1716, - "replacementText": "{\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }" + "replacementText": "{\n selected: (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n },\n normal: NormalStyles\n }", + "line": 85, + "column": 20, + "endLine": 90, + "endColumn": 8 } ], "suggest": "", @@ -126,11 +150,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -143,11 +171,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -160,11 +192,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -177,11 +213,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -194,11 +234,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -211,11 +255,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -228,11 +276,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -245,11 +297,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -262,11 +318,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -279,11 +339,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -296,11 +360,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -313,11 +381,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -330,11 +402,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -347,11 +423,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -364,11 +444,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -381,11 +465,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -398,11 +486,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -415,11 +507,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -432,11 +528,15 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';" + "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "line": 87, + "column": 28, + "endLine": 87, + "endColumn": 33 } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 c4491ce76c..0a96e0ecdc 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 @@ -74,6 +74,16 @@ "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", "severity": "ERROR" }, + { + "line": 103, + "column": 24, + "endLine": 103, + "endColumn": 37, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, { "line": 105, "column": 3, @@ -101,7 +111,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -111,7 +121,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -121,7 +131,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -131,7 +141,7 @@ "endColumn": 27, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -141,7 +151,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -151,7 +161,7 @@ "endColumn": 28, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -161,7 +171,7 @@ "endColumn": 17, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -171,7 +181,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -181,7 +191,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -191,7 +201,7 @@ "endColumn": 27, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -201,7 +211,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -211,7 +221,7 @@ "endColumn": 16, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +231,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -231,7 +241,7 @@ "endColumn": 27, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -241,7 +251,7 @@ "endColumn": 27, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -251,7 +261,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -261,7 +271,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -271,7 +281,7 @@ "endColumn": 37, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"CustomBuilder\" should be imported before it is used (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 3575cf7b84..9973d73974 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 @@ -176,6 +176,16 @@ "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", "severity": "ERROR" }, + { + "line": 103, + "column": 24, + "endLine": 103, + "endColumn": 37, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, { "line": 105, "column": 3, @@ -225,7 +235,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -246,7 +256,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -267,7 +277,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -288,7 +298,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -309,7 +319,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -330,7 +340,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -351,7 +361,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -372,7 +382,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -393,7 +403,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -414,7 +424,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -435,7 +445,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -456,7 +466,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"BuilderParam\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -477,7 +487,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Require\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -498,7 +508,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -519,7 +529,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -540,7 +550,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Button\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -561,7 +571,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -582,7 +592,7 @@ } ], "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"CustomBuilder\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 index 0e17a7dad5..b0daffd23c 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.json @@ -14,6 +14,16 @@ "limitations under the License." ], "result": [ + { + "line": 101, + "column": 24, + "endLine": 101, + "endColumn": 37, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, { "line": 105, "column": 26, 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 7ead10ecf2..1e21ab6ed3 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 @@ -34,6 +34,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 101, + "column": 24, + "endLine": 101, + "endColumn": 37, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, { "line": 105, "column": 26, 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 524d890233..bfbd6bbec9 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 @@ -56,6 +56,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 101, + "column": 24, + "endLine": 101, + "endColumn": 37, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, { "line": 105, "column": 26, 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 index 0e17a7dad5..b0daffd23c 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.json @@ -14,6 +14,16 @@ "limitations under the License." ], "result": [ + { + "line": 101, + "column": 24, + "endLine": 101, + "endColumn": 37, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, { "line": 105, "column": 26, diff --git a/ets2panda/linter/test/main/swicth_expr.ets.arkts2.json b/ets2panda/linter/test/main/swicth_expr.ets.arkts2.json index 5ce55a54ac..207e0d7ebf 100755 --- a/ets2panda/linter/test/main/swicth_expr.ets.arkts2.json +++ b/ets2panda/linter/test/main/swicth_expr.ets.arkts2.json @@ -174,6 +174,26 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 67, + "column": 7, + "endLine": 67, + "endColumn": 8, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 68, + "column": 7, + "endLine": 68, + "endColumn": 8, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, { "line": 70, "column": 7, diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets index 05ec4e2f14..8a089d224c 100644 --- a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets @@ -13,10 +13,54 @@ * limitations under the License. */ 'use static' +import ArrayBuffer,{ taskpool,ArrayList } from '@kit.ArkTS' +import { taskpool as tp } from '@kit.ArkTS' +import * as arkts from '@kit.ArkTS'; +import { task as task7,Task } from './taskpool_deprecated_usages3'; let baseInstance1: BaseClass = new BaseClass(); -let array1 = new Array(); -array1.push(baseInstance1); +let array = new Array(); +array.push(baseInstance1); +let task = new taskpool.Task(testFunc, array, 10); +task.setCloneList(array); //error +task.setTransferList(array); //error + +function testFunc(){} +function test1():void {} + +const array1: number[] =[1] +const transfer: ArrayBuffer[] =[] let task1 = new taskpool.Task(testFunc, array1, 10); -task1.setCloneList(array1); -task1.setTransferList(array1); +task1.setCloneList(array1); //error +task1.setTransferList(transfer); //error + +let task2 = new tp.Task(test1) +task2.setCloneList([]) //error +task2.setCloneList(transfer) //error + +let test3 = new tp.Task(test1) +test3.setCloneList([]) //error +test3.setCloneList([transfer]) //error + +let task4 = new tp.Task(test1) +task4.setTransferList() //error +task4.setTransferList([]) //error +task4.setTransferList(transfer) //error + +let test5 = new tp.Task(test1) +test5.setTransferList() //error +test5.setTransferList([]) //error +test5.setTransferList(transfer) //error + +let task6 = new arkts.taskpool.Task(test1); +task6.setCloneList([]) //error +task6.setCloneList([transfer]) //error + +task7.setCloneList(array1) //error +task7.setTransferList(transfer) //error +new task7.setTransferList(transfer) //error +new task7.setCloneList(array1) //error +new Task(test1).setTransferList(transfer) +new Task(test1).setCloneList(array1) +const task8 = new Task(testFunc); +task8.setCloneList(array1) \ No newline at end of file diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.arkts2.json b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.arkts2.json index 463c82314f..5881b8079d 100644 --- a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.arkts2.json +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.arkts2.json @@ -14,10 +14,70 @@ "limitations under the License." ], "result": [ + { + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 60, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 22, + "endLine": 16, + "endColumn": 30, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, { "line": 17, - "column": 36, + "column": 1, "endLine": 17, + "endColumn": 44, + "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": 44, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 1, + "endLine": 18, + "endColumn": 37, + "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": 68, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 36, + "endLine": 21, "endColumn": 45, "problem": "DynamicCtorCall", "suggest": "", @@ -25,9 +85,69 @@ "severity": "ERROR" }, { - "line": 20, + "line": 24, + "column": 5, + "endLine": 24, + "endColumn": 50, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 16, + "endLine": 24, + "endColumn": 29, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 47, + "endLine": 24, + "endColumn": 49, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 6, + "endLine": 25, + "endColumn": 18, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 6, + "endLine": 26, + "endColumn": 21, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 26, + "endLine": 31, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 33, "column": 5, - "endLine": 20, + "endLine": 33, "endColumn": 52, "problem": "AnyType", "suggest": "", @@ -35,9 +155,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 33, "column": 17, - "endLine": 20, + "endLine": 33, "endColumn": 30, "problem": "DynamicCtorCall", "suggest": "", @@ -45,9 +165,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 33, "column": 49, - "endLine": 20, + "endLine": 33, "endColumn": 51, "problem": "NumericSemantics", "suggest": "", @@ -55,24 +175,304 @@ "severity": "ERROR" }, { - "line": 21, - "column": 1, - "endLine": 21, - "endColumn": 28, + "line": 34, + "column": 7, + "endLine": 34, + "endColumn": 19, "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, + "line": 35, + "column": 7, + "endLine": 35, + "endColumn": 22, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 17, + "endLine": 37, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 7, + "endLine": 38, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 7, + "endLine": 39, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 17, + "endLine": 41, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 7, + "endLine": 42, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 43, + "column": 7, + "endLine": 43, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 17, + "endLine": 45, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 7, + "endLine": 46, + "endColumn": 22, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 7, + "endLine": 47, + "endColumn": 22, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 7, + "endLine": 48, + "endColumn": 22, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 17, + "endLine": 50, + "endColumn": 24, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 51, + "column": 7, + "endLine": 51, + "endColumn": 22, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 7, + "endLine": 52, + "endColumn": 22, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 7, + "endLine": 53, + "endColumn": 22, "problem": "SetTransferListDeprecated", "suggest": "", "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", "severity": "ERROR" + }, + { + "line": 55, + "column": 5, + "endLine": 55, + "endColumn": 43, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 17, + "endLine": 55, + "endColumn": 36, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 56, + "column": 7, + "endLine": 56, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 57, + "column": 7, + "endLine": 57, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 59, + "column": 7, + "endLine": 59, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 60, + "column": 7, + "endLine": 60, + "endColumn": 22, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 5, + "endLine": 61, + "endColumn": 26, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 61, + "column": 11, + "endLine": 61, + "endColumn": 26, + "problem": "SetTransferListDeprecated", + "suggest": "", + "rule": "The taskpool setTransferList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setTransferList)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 5, + "endLine": 62, + "endColumn": 23, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 62, + "column": 11, + "endLine": 62, + "endColumn": 23, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.json b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.json index 1c17b59df7..619623e560 100644 --- a/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.json +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages.ets.json @@ -15,14 +15,114 @@ ], "result": [ { - "line": 20, + "line": 16, + "column": 1, + "endLine": 16, + "endColumn": 60, + "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": 44, + "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": 37, + "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": 68, + "problem": "ImportAfterStatement", + "suggest": "", + "rule": "\"import\" statements after other statements are not allowed (arkts-no-misplaced-imports)", + "severity": "ERROR" + }, + { + "line": 24, "column": 5, - "endLine": 20, + "endLine": 24, + "endColumn": 50, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 5, + "endLine": 33, "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" + }, + { + "line": 37, + "column": 5, + "endLine": 37, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 5, + "endLine": 41, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 45, + "column": 5, + "endLine": 45, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 5, + "endLine": 50, + "endColumn": 31, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 55, + "column": 5, + "endLine": 55, + "endColumn": 43, + "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/taskpool_deprecated_usages2.ets b/ets2panda/linter/test/main/taskpool_deprecated_usages2.ets new file mode 100755 index 0000000000..f79e1e32cc --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages2.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. + */ + +import taskpool from '@ohos.taskpool'; +import { otherTaskPool as taskpool1 } from './@ohos.taskpool'; +import { taskpool as taskpool2 } from './@ohos.taskpool'; +function test1(){} +const array1: number[] =[1] +const transfer: ArrayBuffer[] =[] +let task = new taskpool1.Task(test1); +task.setCloneList(array1) +task.setTransferList(transfer) +new taskpool1.Task(test1).setTransferList(transfer); +function test(){ + const task3 = new taskpool2.Task(test1); + typeof task3.setTransferList(transfer); + return new taskpool2.Task(test1).setTransferList(); +} +let task4 = new taskpool.Task(test1); +task4.setCloneList([]) //error +task4.setCloneList(transfer) //error \ No newline at end of file diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages2.ets.args.json b/ets2panda/linter/test/main/taskpool_deprecated_usages2.ets.args.json new file mode 100755 index 0000000000..3ef4496a81 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages2.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/taskpool_deprecated_usages2.ets.arkts2.json b/ets2panda/linter/test/main/taskpool_deprecated_usages2.ets.arkts2.json new file mode 100755 index 0000000000..e4183cf1b5 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages2.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": 1, + "endLine": 16, + "endColumn": 39, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 26, + "endLine": 20, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 10, + "endLine": 28, + "endColumn": 41, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 5, + "endLine": 31, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 17, + "endLine": 31, + "endColumn": 30, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 7, + "endLine": 32, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 7, + "endLine": 33, + "endColumn": 19, + "problem": "SetCloneListDeprecated", + "suggest": "", + "rule": "The taskpool setCloneList interface is deleted from ArkTS1.2 (arkts-limited-stdlib-no-setCloneList)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages2.ets.json b/ets2panda/linter/test/main/taskpool_deprecated_usages2.ets.json new file mode 100755 index 0000000000..14da023dd0 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages2.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": 31, + "column": 5, + "endLine": 31, + "endColumn": 37, + "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/taskpool_deprecated_usages3.ets b/ets2panda/linter/test/main/taskpool_deprecated_usages3.ets new file mode 100755 index 0000000000..99eafb8296 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages3.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. + */ +import taskpool from '@ohos.taskpool'; +function test1(){} +export const task = new taskpool.Task(test1); +export class Task { + constructor(func: Function, ...args: Object[]){} + setTransferList(transfer?: ArrayBuffer[]): void{} + setCloneList(cloneList: Object[] | ArrayBuffer[]): void{} +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/taskpool_deprecated_usages3.ets.args.json b/ets2panda/linter/test/main/taskpool_deprecated_usages3.ets.args.json new file mode 100755 index 0000000000..3ef4496a81 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages3.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/taskpool_deprecated_usages3.ets.arkts2.json b/ets2panda/linter/test/main/taskpool_deprecated_usages3.ets.arkts2.json new file mode 100755 index 0000000000..449be5d794 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages3.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": 15, + "column": 1, + "endLine": 15, + "endColumn": 39, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 15, + "endLine": 17, + "endColumn": 46, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 26, + "endLine": 17, + "endColumn": 39, + "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/taskpool_deprecated_usages3.ets.json b/ets2panda/linter/test/main/taskpool_deprecated_usages3.ets.json new file mode 100755 index 0000000000..4fdd338ef2 --- /dev/null +++ b/ets2panda/linter/test/main/taskpool_deprecated_usages3.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": 15, + "endLine": 17, + "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/ts-like-catch-type.ets b/ets2panda/linter/test/main/ts-like-catch-type.ets index 76d4be8122..02c6d721fb 100644 --- a/ets2panda/linter/test/main/ts-like-catch-type.ets +++ b/ets2panda/linter/test/main/ts-like-catch-type.ets @@ -13,18 +13,14 @@ * limitations under the License. */ -function test() { - try { - let a: number = 1; - } catch (e) { - console.log('catch') - } +try { + throw new Error(); +} catch(e) { + e.message; + e.prop; } -function test2() { - try { - let a: number = 1; - } catch (e: any) { - console.log('catch') - } +try { + throw new Error(); +} catch(e) { } \ 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 index 2956a7461c..41e86435ee 100644 --- a/ets2panda/linter/test/main/ts-like-catch-type.ets.arkts2.json +++ b/ets2panda/linter/test/main/ts-like-catch-type.ets.arkts2.json @@ -15,64 +15,14 @@ ], "result": [ { - "line": 18, - "column": 21, - "endLine": 18, - "endColumn": 22, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 19, - "column": 5, - "endLine": 21, - "endColumn": 4, + "line": 20, + "column": 3, + "endLine": 20, + "endColumn": 9, "problem": "TsLikeCatchType", "suggest": "", "rule": "TS catch type are not supported (arkts-no-ts-like-catch-type)", "severity": "ERROR" - }, - { - "line": 26, - "column": 21, - "endLine": 26, - "endColumn": 22, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "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 index bd65f7efbe..315ec6f0ae 100644 --- a/ets2panda/linter/test/main/ts-like-catch-type.ets.json +++ b/ets2panda/linter/test/main/ts-like-catch-type.ets.json @@ -13,26 +13,5 @@ "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" - } - ] + "result": [] } \ 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 013ef916fe..625ed5b833 100644 --- a/ets2panda/linter/test/main/ts_overload.ets.arkts2.json +++ b/ets2panda/linter/test/main/ts_overload.ets.arkts2.json @@ -13,7 +13,7 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ + "result": [ { "line": 16, "column": 1, @@ -44,6 +44,26 @@ "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", "severity": "ERROR" }, + { + "line": 20, + "column": 16, + "endLine": 20, + "endColumn": 20, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 16, + "endLine": 22, + "endColumn": 20, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, { "line": 25, "column": 21, @@ -281,7 +301,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/rules/rule144.ets.json b/ets2panda/linter/test/rules/rule144.ets.json index c52a53a30f..9bbf5b7e7c 100644 --- a/ets2panda/linter/test/rules/rule144.ets.json +++ b/ets2panda/linter/test/rules/rule144.ets.json @@ -274,6 +274,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 85, + "column": 1, + "endLine": 85, + "endColumn": 51, + "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": 86, "column": 1, @@ -284,6 +294,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 86, + "column": 1, + "endLine": 86, + "endColumn": 39, + "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": 86, "column": 32, @@ -304,6 +324,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 87, + "column": 1, + "endLine": 87, + "endColumn": 36, + "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": 87, "column": 32, @@ -324,6 +354,26 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 88, + "column": 1, + "endLine": 88, + "endColumn": 34, + "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": 89, + "column": 1, + "endLine": 89, + "endColumn": 32, + "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": 90, "column": 1, @@ -334,6 +384,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 90, + "column": 1, + "endLine": 90, + "endColumn": 53, + "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": 91, "column": 1, @@ -344,6 +404,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 91, + "column": 1, + "endLine": 91, + "endColumn": 27, + "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": 92, "column": 1, @@ -354,6 +424,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 92, + "column": 1, + "endLine": 92, + "endColumn": 25, + "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": 93, "column": 1, @@ -364,6 +444,16 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 93, + "column": 1, + "endLine": 93, + "endColumn": 30, + "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": 94, "column": 1, @@ -374,6 +464,86 @@ "rule": "Usage of standard library is restricted (arkts-limited-stdlib)", "severity": "ERROR" }, + { + "line": 94, + "column": 1, + "endLine": 94, + "endColumn": 30, + "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": 95, + "column": 1, + "endLine": 95, + "endColumn": 39, + "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": 96, + "column": 1, + "endLine": 96, + "endColumn": 46, + "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": 97, + "column": 1, + "endLine": 97, + "endColumn": 39, + "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": 98, + "column": 1, + "endLine": 98, + "endColumn": 39, + "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": 99, + "column": 1, + "endLine": 99, + "endColumn": 38, + "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": 100, + "column": 1, + "endLine": 100, + "endColumn": 31, + "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": 101, + "column": 1, + "endLine": 101, + "endColumn": 29, + "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": 104, "column": 32, diff --git a/ets2panda/linter/test/rules/rule37.ets.migrate.json b/ets2panda/linter/test/rules/rule37.ets.migrate.json index ca88f857e9..0a1c7ec097 100644 --- a/ets2panda/linter/test/rules/rule37.ets.migrate.json +++ b/ets2panda/linter/test/rules/rule37.ets.migrate.json @@ -13,5 +13,16 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 59, + "column": 21, + "endLine": 59, + "endColumn": 27, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + } + ] } \ No newline at end of file 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 index 327b8e844f..64896441f0 100644 --- 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 @@ -211,7 +211,7 @@ "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -221,7 +221,7 @@ "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -231,7 +231,7 @@ "endColumn": 62, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -241,7 +241,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"State\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -251,7 +251,7 @@ "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"List\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -261,7 +261,7 @@ "endColumn": 14, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ForEach\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -271,7 +271,7 @@ "endColumn": 17, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"ListItem\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -281,7 +281,7 @@ "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { 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 d6b0d31865..5b7d055ce4 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 @@ -44,6 +44,16 @@ "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", "severity": "ERROR" }, + { + "line": 22, + "column": 26, + "endLine": 22, + "endColumn": 46, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 22, "column": 26, @@ -54,6 +64,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 41, + "column": 28, + "endLine": 41, + "endColumn": 48, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 41, "column": 28, @@ -64,6 +84,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 45, + "column": 29, + "endLine": 45, + "endColumn": 49, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 45, "column": 29, 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 5b41bb7baa..646d8423c0 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 @@ -24,16 +24,6 @@ "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, @@ -94,6 +84,16 @@ "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", "severity": "ERROR" }, + { + "line": 28, + "column": 28, + "endLine": 28, + "endColumn": 48, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 28, "column": 28, @@ -104,6 +104,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 32, + "column": 26, + "endLine": 32, + "endColumn": 46, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 32, "column": 26, @@ -201,7 +211,7 @@ "endColumn": 59, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"DataChangeListener\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" }, { @@ -211,7 +221,7 @@ "endColumn": 61, "problem": "UIInterfaceImport", "suggest": "", - "rule": "ArkUI interface should be imported before using (arkui-modular-interface)", + "rule": "The ArkUI interface \"DataChangeListener\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets index e05617b2ff..d7922e5530 100644 --- a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import { rcp } from '@kit.RemoteCommunicationKit'; +import mainRcp,{ rcp } from '@kit.RemoteCommunicationKit'; class LI implements rcp.WriteFile{ write(buffer: ArrayBuffer): Promise { // Error throw new Error('Method not implemented.'); @@ -41,4 +41,16 @@ export class LocalDataSource implements IDataSourcePrefetching { cancel(index: number): void | Promise { throw new Error("LocalDataSource Method not implemented."); } +} + +class L3 implements mainRcp.WriteFile { + write(buffer: ArrayBuffer): Promise { // error + throw new Error('Method not implemented.'); + } +} + +class L4 implements rcp.WriteFile { + write(buffer: ArrayBuffer): Promise { // error + throw new Error('Method not implemented.'); + } } \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.arkts2.json index 5d0e2d9cb6..ab0cf4ecd5 100644 --- a/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/limit_void_type_sdk3.ets.arkts2.json @@ -24,16 +24,6 @@ "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, @@ -94,6 +84,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 37, + "column": 28, + "endLine": 37, + "endColumn": 48, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 37, "column": 28, @@ -104,6 +104,16 @@ "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" }, + { + "line": 41, + "column": 26, + "endLine": 41, + "endColumn": 46, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, { "line": 41, "column": 26, @@ -113,6 +123,46 @@ "suggest": "", "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", "severity": "ERROR" + }, + { + "line": 47, + "column": 3, + "endLine": 49, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 48, + "endLine": 47, + "endColumn": 52, + "problem": "LimitedVoidType", + "suggest": "", + "rule": "Type \"void\" has no instances.(arkts-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 3, + "endLine": 55, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 53, + "column": 48, + "endLine": 53, + "endColumn": 52, + "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/quoted_hyphen_props_deprecated_sdk2.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/quoted_hyphen_props_deprecated_sdk2.ets.arkts2.json index f2d125c578..84106d351a 100755 --- 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 @@ -14,6 +14,26 @@ "limitations under the License." ], "result": [ + { + "line": 42, + "column": 10, + "endLine": 42, + "endColumn": 20, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, + { + "line": 48, + "column": 20, + "endLine": 48, + "endColumn": 30, + "problem": "RuntimeArrayCheck", + "suggest": "", + "rule": "Array bound not checked. (arkts-runtime-array-check)", + "severity": "ERROR" + }, { "line": 65, "column": 5, diff --git a/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets index c50d5885da..d14c65ae1c 100755 --- a/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets +++ b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets @@ -13,8 +13,30 @@ * limitations under the License. */ -import {cloudDatabase} from '@hms.core.deviceCloudGateway.cloudDatabase'; +import cloudDatabase from '@hms.core.deviceCloudGateway.cloudDatabase'; class Test extends cloudDatabase.DatabaseObject{ - + query = new cloudDatabase.DatabaseQuery(Test); //Error + equalTo(){ + return this.query.equalTo('test',''); + } } -new cloudDatabase.DatabaseQuery(Test); // NOT OK \ No newline at end of file +const localQuery = new cloudDatabase.DatabaseQuery(Test); //Error +class LocalDatabaseQuery extends cloudDatabase.DatabaseQuery{ //Error + query = new cloudDatabase.DatabaseQuery(Test); //Error + set(query:cloudDatabase.DatabaseQuery){ //Error + query.equalTo('test',''); + } + getTypeQuery(): cloudDatabase.DatabaseQuery { //Error + typeof new cloudDatabase.DatabaseQuery(Test); //Error + return new cloudDatabase.DatabaseQuery(Test); //Error + } + getEqual(){ + this.query = new Test().equalTo(); //Error? + } + +} +function useDatabaseQuery1(query:cloudDatabase.DatabaseQuery){ //Error + console.log(' '+new cloudDatabase.DatabaseQuery(Test)); //Error +} +class DatabaseQuery{} +new DatabaseQuery(); \ No newline at end of file diff --git a/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.arkts2.json index 745ab994b2..0356091ac5 100755 --- a/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.arkts2.json @@ -15,20 +15,200 @@ ], "result": [ { - "line": 20, - "column": 5, - "endLine": 20, - "endColumn": 32, + "line": 18, + "column": 3, + "endLine": 18, + "endColumn": 49, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 15, + "endLine": 18, + "endColumn": 42, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 18, + "column": 29, + "endLine": 18, + "endColumn": 42, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 10, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 8, + "endLine": 23, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 25, + "endLine": 23, + "endColumn": 52, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 39, + "endLine": 23, + "endColumn": 52, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 48, + "endLine": 24, + "endColumn": 61, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 49, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 15, + "endLine": 25, + "endColumn": 42, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 29, + "endLine": 25, + "endColumn": 42, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 27, + "endLine": 26, + "endColumn": 40, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 33, + "endLine": 29, + "endColumn": 46, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 16, + "endLine": 30, + "endColumn": 43, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 30, + "endLine": 30, + "endColumn": 43, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 16, + "endLine": 31, + "endColumn": 43, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 30, + "endLine": 31, + "endColumn": 43, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 48, + "endLine": 38, + "endColumn": 61, + "problem": "ConstructorTypesDeprecated", + "suggest": "", + "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 23, + "endLine": 39, + "endColumn": 50, "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, + "line": 39, + "column": 37, + "endLine": 39, + "endColumn": 50, "problem": "ConstructorTypesDeprecated", "suggest": "", "rule": "Constructor types are not supported - use lambda functions instead. (sdk-constructor-funcs)", diff --git a/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.json b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.json index 9f305c86d7..7cf57b141b 100755 --- a/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.json +++ b/ets2panda/linter/test/sdkwhite/sdk_constructor_funcs.ets.json @@ -13,5 +13,46 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 18, + "column": 3, + "endLine": 18, + "endColumn": 49, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 3, + "endLine": 19, + "endColumn": 10, + "problem": "LimitedReturnTypeInference", + "suggest": "", + "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 8, + "endLine": 23, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 25, + "endColumn": 49, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + } + ] } 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 67a42975bf..7053b9055f 100755 --- a/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/sdk_type_query.ets.arkts2.json @@ -174,6 +174,16 @@ "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" }, + { + "line": 44, + "column": 17, + "endLine": 44, + "endColumn": 19, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, { "line": 48, "column": 14, diff --git a/ets2panda/package-lock.json b/ets2panda/package-lock.json new file mode 100644 index 0000000000..8348c83704 --- /dev/null +++ b/ets2panda/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "ets2panda", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} -- Gitee From 5427f97396ee9e922dcea45b99c901883c15d0ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A2=81=E5=AE=B6=E7=86=99?= Date: Sun, 15 Jun 2025 16:03:40 +0800 Subject: [PATCH 009/145] Fix three circular definition bugs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICF9B4 Signed-off-by: 梁家熙 --- ets2panda/checker/ETSAnalyzer.cpp | 5 +++ ets2panda/checker/ets/utilityTypeHandlers.cpp | 4 ++ .../lowering/ets/localClassLowering.cpp | 8 +++- ets2panda/ir/ets/etsKeyofType.cpp | 5 +++ ets2panda/ir/ets/etsTypeReferencePart.cpp | 27 +++++++++++++ .../ast/parser/ets/circular_class_extends.ets | 27 +++++++++++++ .../ets/circular_in_class_functions.ets | 33 ++++++++++++++++ .../ast/parser/ets/circular_type_in_alias.ets | 38 +++++++++++++++++++ ets2panda/util/diagnostic/semantic.yaml | 12 ++++++ 9 files changed, 158 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/parser/ets/circular_class_extends.ets create mode 100644 ets2panda/test/ast/parser/ets/circular_in_class_functions.ets create mode 100644 ets2panda/test/ast/parser/ets/circular_type_in_alias.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 0f45d11123..2c0fd6a3fc 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -1547,6 +1547,11 @@ checker::Type *ETSAnalyzer::Check(ir::CallExpression *expr) const CheckCallee(checker, expr); + checker::TypeStackElement tse(checker, expr, {{diagnostic::CYCLIC_CALLEE, {}}}, expr->Start()); + if (tse.HasTypeError()) { + return checker->GlobalTypeError(); + } + checker::Type *const returnType = GetCallExpressionReturnType(expr, calleeType); expr->SetTsType(returnType); if (returnType->IsTypeError()) { diff --git a/ets2panda/checker/ets/utilityTypeHandlers.cpp b/ets2panda/checker/ets/utilityTypeHandlers.cpp index b2d95bd91d..d9e630189d 100644 --- a/ets2panda/checker/ets/utilityTypeHandlers.cpp +++ b/ets2panda/checker/ets/utilityTypeHandlers.cpp @@ -845,6 +845,10 @@ Type *ETSChecker::CreatePartialTypeClassDef(ir::ClassDefinition *const partialCl ? GlobalETSObjectType() : classDef->Super()->TsType()); + if (partialSuper == partialType) { + LogError(diagnostic::CYCLIC_CLASS_SUPER_TYPE, {}, classDef->Start()); + return partialType; + } partialType->SetSuperType(partialSuper->AsETSObjectType()); } diff --git a/ets2panda/compiler/lowering/ets/localClassLowering.cpp b/ets2panda/compiler/lowering/ets/localClassLowering.cpp index a9b4095219..4de051d1ea 100644 --- a/ets2panda/compiler/lowering/ets/localClassLowering.cpp +++ b/ets2panda/compiler/lowering/ets/localClassLowering.cpp @@ -199,7 +199,13 @@ void LocalClassConstructionPhase::RemapReferencesFromCapturedVariablesToClassPro if (it->IsMethodDefinition() && !it->AsMethodDefinition()->IsConstructor()) { LOG(DEBUG, ES2PANDA) << " - Rebinding variable rerferences in: " << it->AsMethodDefinition()->Id()->Name().Mutf8().c_str(); - it->AsMethodDefinition()->Function()->Body()->IterateRecursively(remapCapturedVariables); + if (it->AsMethodDefinition()->Function()->Body() == nullptr && + it->AsMethodDefinition()->AsyncPairMethod() != nullptr) { + it->AsMethodDefinition()->AsyncPairMethod()->Function()->Body()->IterateRecursively( + remapCapturedVariables); + } else { + it->AsMethodDefinition()->Function()->Body()->IterateRecursively(remapCapturedVariables); + } } } // Since the constructor with zero parameter is not listed in the class_def body the constructors diff --git a/ets2panda/ir/ets/etsKeyofType.cpp b/ets2panda/ir/ets/etsKeyofType.cpp index d266214e5b..2ef1666092 100644 --- a/ets2panda/ir/ets/etsKeyofType.cpp +++ b/ets2panda/ir/ets/etsKeyofType.cpp @@ -75,6 +75,11 @@ checker::Type *ETSKeyofType::GetType(checker::ETSChecker *checker) return checker->GlobalTypeError(); } + checker::TypeStackElement tse(checker, this, {{diagnostic::CYCLIC_TYPE_OF, {}}}, Start()); + if (tse.HasTypeError()) { + return checker->GlobalTypeError(); + } + SetTsType(checker->CreateUnionFromKeyofType(typeReference->AsETSObjectType())); return TsType(); } diff --git a/ets2panda/ir/ets/etsTypeReferencePart.cpp b/ets2panda/ir/ets/etsTypeReferencePart.cpp index e0686ef076..3c7089b10f 100644 --- a/ets2panda/ir/ets/etsTypeReferencePart.cpp +++ b/ets2panda/ir/ets/etsTypeReferencePart.cpp @@ -93,6 +93,29 @@ checker::VerifiedType ETSTypeReferencePart::Check(checker::ETSChecker *checker) return {this, checker->GetAnalyzer()->Check(this)}; } +[[maybe_unused]] static bool CheckTypeAliaLoop(ETSTypeReferencePart *ref, varbinder::Variable *variable) +{ + auto typeAliasDecl = variable->Declaration()->Node()->AsTSTypeAliasDeclaration(); + auto typeDeclaration = typeAliasDecl->TypeParams(); + if (typeDeclaration == nullptr) { + return false; + } + + for (auto *param : typeDeclaration->Params()) { + auto constraint = param->Constraint(); + if (constraint == nullptr || !constraint->IsETSTypeReference()) { + continue; + } + + auto part = constraint->AsETSTypeReference()->Part(); + if (part == ref) { + return true; + } + } + + return false; +} + checker::Type *ETSTypeReferencePart::HandleInternalTypes(checker::ETSChecker *const checker) { ES2PANDA_ASSERT(name_->IsIdentifier() || name_->IsTSQualifiedName()); @@ -112,6 +135,10 @@ checker::Type *ETSTypeReferencePart::HandleInternalTypes(checker::ETSChecker *co } if (variable != nullptr && variable->Declaration()->IsTypeAliasDecl()) { + if (CheckTypeAliaLoop(this, variable)) { + checker->LogError(diagnostic::CYCLIC_ALIAS, {}, Start()); + return checker->GlobalTypeError(); + } return checker->HandleTypeAlias(name_, typeParams_, variable->Declaration()->AsTypeAliasDecl()->Node()->AsTSTypeAliasDeclaration()); } diff --git a/ets2panda/test/ast/parser/ets/circular_class_extends.ets b/ets2panda/test/ast/parser/ets/circular_class_extends.ets new file mode 100644 index 0000000000..4cac2e3719 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/circular_class_extends.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. + */ + +namespace m { + export class c { + } +} + +// Instead of assigning namespace to variable, export the namespace directly +export { m }; + +// If you want to re-export the class from the namespace: +export class c extends m.c {} + +/* @@? 25:28 Error TypeError: Class's super type is itself */ diff --git a/ets2panda/test/ast/parser/ets/circular_in_class_functions.ets b/ets2panda/test/ast/parser/ets/circular_in_class_functions.ets new file mode 100644 index 0000000000..d128f8bcce --- /dev/null +++ b/ets2panda/test/ast/parser/ets/circular_in_class_functions.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 Test { + foo() {} + + bar() { + this.baz(this, "*1*"); + + const t = new Test() + this.baz(t, "*2*"); + } + + baz(a: Test, k: keyof Test) {} +} + +/* @@? 20:9 Error TypeError: No matching call signature for baz(Test, "*1*") */ +/* @@? 20:24 Error TypeError: Type '"*1*"' is not compatible with type '"foo"|"bar"|"baz"' at index 2 */ +/* @@? 23:9 Error TypeError: No matching call signature for baz(Test, "*2*") */ +/* @@? 23:21 Error TypeError: Type '"*2*"' is not compatible with type '"foo"|"bar"|"baz"' at index 2 */ +/* @@? 26:31 Error TypeError: Circular type of reference */ diff --git a/ets2panda/test/ast/parser/ets/circular_type_in_alias.ets b/ets2panda/test/ast/parser/ets/circular_type_in_alias.ets new file mode 100644 index 0000000000..920263f091 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/circular_type_in_alias.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. + */ + +type Loop> = { + [P in keyof T]: U[P] extends boolean ? number : string; +}; + +/* @@? 16:24 Error TypeError: Circular type alias reference */ +/* @@? 16:38 Error SyntaxError: Invalid Type. */ +/* @@? 17:6 Error TypeError: Unresolved reference P */ +/* @@? 17:8 Error SyntaxError: Unexpected token, expected ',' or ']'. */ +/* @@? 17:8 Error SyntaxError: Unexpected token 'in'. */ +/* @@? 17:8 Error TypeError: Unresolved reference in */ +/* @@? 17:11 Error SyntaxError: Unexpected token 'keyof'. */ +/* @@? 17:11 Error TypeError: Unresolved reference keyof */ +/* @@? 17:17 Error SyntaxError: Unexpected token 'T'. */ +/* @@? 17:17 Error TypeError: Unresolved reference T */ +/* @@? 17:18 Error SyntaxError: Unexpected token ']'. */ +/* @@? 17:19 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:21 Error SyntaxError: Unexpected token 'U'. */ +/* @@? 17:21 Error TypeError: Unresolved reference U */ +/* @@? 17:21 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 17:26 Error SyntaxError: Unexpected token 'extends'. */ +/* @@? 17:34 Error SyntaxError: Unexpected token 'boolean'. */ +/* @@? 17:44 Error TypeError: Type name 'number' used in the wrong context */ +/* @@? 17:53 Error TypeError: Type name 'string' used in the wrong context */ diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index e61143986b..ba0191e4ad 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -1482,3 +1482,15 @@ semantic: - name: SUPER_NOT_ACCESSIBLE id: 372 message: "Class field '{}' defined by the parent class is not accessible in the child class via super." + +- name: CYCLIC_TYPE_OF + id: 379 + message: "Circular type of reference" + +- name: CYCLIC_CLASS_SUPER_TYPE + id: 380 + message: "Class's super type is itself" + +- name: CYCLIC_CALLEE + id: 381 + message: "Circular call function" -- Gitee From 0bdedc893bdc13778d8f85513bf5aafcc614bd69 Mon Sep 17 00:00:00 2001 From: lijincheng Date: Sun, 22 Jun 2025 18:36:38 +0800 Subject: [PATCH 010/145] Json support annotation 1. cherry pick to 0603 Issue:https://gitee.com/openharmony/arkcompiler_runtime_core/issues/ICGXDV Signed-off-by: lijincheng --- ets2panda/compiler/core/ETSemitter.cpp | 5 ++++- .../test/runtime/ets/AnnotationOfClassPropertyInherit.ets | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/ets2panda/compiler/core/ETSemitter.cpp b/ets2panda/compiler/core/ETSemitter.cpp index 98dd37c7b5..6eba5e1753 100644 --- a/ets2panda/compiler/core/ETSemitter.cpp +++ b/ets2panda/compiler/core/ETSemitter.cpp @@ -437,11 +437,14 @@ void ETSEmitter::GenClassField(const ir::ClassProperty *prop, pandasm::Record &c field.type = PandasmTypeWithRank(prop->TsType()); field.metadata->SetAccessFlags(TranslateModifierFlags(prop->Modifiers())); + if (!external) { + field.metadata->SetAnnotations(GenCustomAnnotations(prop->Annotations(), field.name)); + } + if (external || prop->IsDeclare()) { field.metadata->SetAttribute(Signatures::EXTERNAL); } else if (prop->TsType()->IsETSPrimitiveType() || prop->TsType()->IsETSStringType()) { EmitDefaultFieldValue(field, prop->Value()); - field.metadata->SetAnnotations(GenCustomAnnotations(prop->Annotations(), field.name)); } classRecord.fieldList.emplace_back(std::move(field)); diff --git a/ets2panda/test/runtime/ets/AnnotationOfClassPropertyInherit.ets b/ets2panda/test/runtime/ets/AnnotationOfClassPropertyInherit.ets index f7f39edabb..1a10d2134b 100644 --- a/ets2panda/test/runtime/ets/AnnotationOfClassPropertyInherit.ets +++ b/ets2panda/test/runtime/ets/AnnotationOfClassPropertyInherit.ets @@ -13,12 +13,12 @@ * limitations under the License. */ -@interface JSONRename { +@interface JSONRenameTest { name:string = "" } class A { - @JSONRename("ID") + @JSONRenameTest("ID") name2: string = "" pwd2: string = "" } -- Gitee From ec233a5af2cd30eb0cc9962b28cde95d634ed029 Mon Sep 17 00:00:00 2001 From: dongchao Date: Wed, 28 May 2025 01:37:43 +0800 Subject: [PATCH 011/145] Fix ui import scenes in declgen_ets2ts Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGXLY Signed-off-by: dongchao Change-Id: I5442aeb82513534c7506830a2b546be449fcfdbf --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 62 +++++++++++++------ ets2panda/declgen_ets2ts/declgenEts2Ts.h | 6 +- .../declgen-ets2ts-runtime-ignored.txt | 1 + 3 files changed, 47 insertions(+), 22 deletions(-) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 6dd04a3916..01d16758d4 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -293,7 +293,7 @@ void TSDeclGen::GenImportDeclarations() } template -void TSDeclGen::GenSeparated(const T &container, const CB &cb, const char *separator, bool isReExport) +void TSDeclGen::GenSeparated(const T &container, const CB &cb, const char *separator, bool isReExport, bool isDtsExport) { if (container.empty()) { return; @@ -304,7 +304,9 @@ void TSDeclGen::GenSeparated(const T &container, const CB &cb, const char *separ if (isReExport) { OutTs(separator); } - OutDts(separator); + if (isDtsExport) { + OutDts(separator); + } cb(container[i]); } } @@ -965,6 +967,7 @@ void TSDeclGen::GenAnnotations(const T *node) if (!state_.inGlobalClass && (state_.inClass || state_.inInterface)) { ProcessIndent(); } + importSet_.insert(anno->GetBaseName()->Name().Mutf8()); OutDts("@", anno->GetBaseName()->Name()); GenAnnotationProperties(anno); OutEndlDts(); @@ -1041,52 +1044,63 @@ void TSDeclGen::GenImportDeclaration(const ir::ETSImportDeclaration *importDecla } else if (specifierFirst->IsImportSpecifier()) { 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(); + OutTs("import * as ", local, " from \"", source, "\";"); + OutEndlTs(); if (importSet_.find(local.Mutf8()) == importSet_.end()) { return; } OutDts("import * as ", local, " from \"", source, "\";"); - OutTs("import * as ", local, " from \"", source, "\";"); + OutEndlDts(); } void TSDeclGen::GenDefaultImport(const ir::AstNode *specifier, const std::string &source, const std::string &typeStr) { const auto local = specifier->AsImportDefaultSpecifier()->Local()->Name(); + OutTs("import ", typeStr, local, " from \"", source, "\";"); + OutEndlTs(); if (importSet_.find(local.Mutf8()) == importSet_.end()) { return; } OutDts("import ", typeStr, local, " from \"", source, "\";"); - OutTs("import ", typeStr, local, " from \"", source, "\";"); + OutEndlDts(); } void TSDeclGen::GenNamedImports(const ir::ETSImportDeclaration *importDeclaration, const ArenaVector &specifiers, const std::string &source, const std::string &typeStr) { + if (specifiers.empty()) { + return; + } + OutTs("import ", typeStr, "{ "); + GenSeparated( + specifiers, + [this, &importDeclaration](ir::AstNode *specifier) { + GenSingleNamedImport(specifier, importDeclaration, true); + }, + ", ", true, false); + OutTs(" } from \"", source, "\";"); + OutEndlTs(); 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, "\";"); + OutEndlDts(); } -void TSDeclGen::GenSingleNamedImport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration) +void TSDeclGen::GenSingleNamedImport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration, + bool isGlueCode) { if (!specifier->IsImportSpecifier()) { LogError(diagnostic::IMPORT_SPECIFIERS_SUPPORT, {}, importDeclaration->Start()); @@ -1094,11 +1108,9 @@ void TSDeclGen::GenSingleNamedImport(ir::AstNode *specifier, const ir::ETSImport 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); + isGlueCode ? OutTs(imported, " as ", local) : OutDts(imported, " as ", local); } else { - OutDts(local); - OutTs(local); + isGlueCode ? OutTs(local) : OutDts(local); } } @@ -1106,6 +1118,9 @@ std::vector TSDeclGen::FilterValidImportSpecifiers(const ArenaVec { std::vector importSpecifiers; for (auto specifier : specifiers) { + if (specifier->AsImportSpecifier()->IsRemovable()) { + continue; + } const auto local = specifier->AsImportSpecifier()->Local()->Name().Mutf8(); if (importSet_.find(local) != importSet_.end()) { importSpecifiers.push_back(specifier); @@ -1344,6 +1359,9 @@ void TSDeclGen::ProcessTSArrayType(const ir::TSArrayType *tsArrayType) void TSDeclGen::ProcessETSFunctionType(const ir::ETSFunctionType *etsFunction) { + if (etsFunction->TypeParams() != nullptr) { + GenTypeParameters(etsFunction->TypeParams()); + } bool inUnionBody = !state_.inUnionBodyStack.empty() && state_.inUnionBodyStack.top(); OutDts(inUnionBody ? "((" : "("); GenSeparated(etsFunction->Params(), [this](ir::Expression *param) { @@ -1630,10 +1648,10 @@ void TSDeclGen::HandleClassDeclarationTypeInfo(const ir::ClassDefinition *classD void TSDeclGen::HandleClassInherit(const ir::Expression *expr) { - if (!expr->TsType()->IsTypeError()) { - GenType(expr->TsType()); - } else if (expr->IsETSTypeReference()) { + if (expr->IsETSTypeReference()) { ProcessETSTypeReferenceType(expr->AsETSTypeReference()); + } else if (!expr->TsType()->IsTypeError()) { + GenType(expr->TsType()); } } @@ -1933,6 +1951,10 @@ void TSDeclGen::ProcessClassPropertyType(const ir::ClassProperty *classProp) ProcessTypeAnnotationType(classProp->TypeAnnotation(), classProp->TsType()); return; } + if (value->IsArrowFunctionExpression() && value->AsArrowFunctionExpression()->Function() != nullptr && + value->AsArrowFunctionExpression()->Function()->TypeParams() != nullptr) { + GenTypeParameters(value->AsArrowFunctionExpression()->Function()->TypeParams()); + } GenType(classProp->TsType()); } diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index fda8c826a1..fc580114db 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -123,7 +123,8 @@ private: 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 GenSingleNamedImport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration, + bool isGlueCode = false); void GenReExportDeclaration(const ir::ETSReExportDeclaration *reExportDeclaration); void GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAlias); void GenEnumDeclaration(const ir::ClassProperty *enumMember); @@ -155,7 +156,8 @@ private: bool ShouldEmitDeclarationSymbol(const ir::Identifier *symbol); template - void GenSeparated(const T &container, const CB &cb, const char *separator = ", ", bool isReExport = false); + void GenSeparated(const T &container, const CB &cb, const char *separator = ", ", bool isReExport = false, + bool isDtsExport = true); void PrepareClassDeclaration(const ir::ClassDefinition *classDef); bool ShouldSkipMethodDeclaration(const ir::MethodDefinition *methodDef); 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 71f12afe4c..2bfb00fa8a 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 @@ -18,3 +18,4 @@ lambda_with_receiver/lambda_with_receiver_trailing_in_function_return_this_rotat static-invoke.ets top_level_03.ets multisource_inheritance.ets +as_string.ets -- Gitee From e85909fb116e410decf01a1f0f42be2695768eeb Mon Sep 17 00:00:00 2001 From: fcc Date: Tue, 10 Jun 2025 15:43:56 +0800 Subject: [PATCH 012/145] fix unicode whitespace in lexer Fix Unicode whitespace in lexer. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICE0R4 Signed-off-by: fcc --- ets2panda/lexer/lexer.cpp | 15 ++++++++++-- ets2panda/lexer/token/letters.h | 24 ++++++++++++------- .../test/runtime/ets/unicode_whitespace.ets | 17 +++++++++++++ 3 files changed, 46 insertions(+), 10 deletions(-) create mode 100644 ets2panda/test/runtime/ets/unicode_whitespace.ets diff --git a/ets2panda/lexer/lexer.cpp b/ets2panda/lexer/lexer.cpp index 3868b42336..5cbf89f97c 100644 --- a/ets2panda/lexer/lexer.cpp +++ b/ets2panda/lexer/lexer.cpp @@ -1340,17 +1340,27 @@ bool Lexer::SkipWhiteSpacesHelperDefault(const char32_t &cp) size_t cpSize {}; - switch (Iterator().PeekCp(&cpSize)) { + char32_t ch = Iterator().PeekCp(&cpSize); + switch (ch) { case LEX_CHAR_LS: case LEX_CHAR_PS: pos_.nextTokenLine_++; [[fallthrough]]; case LEX_CHAR_NBSP: case LEX_CHAR_ZWNBSP: + case LEX_CHAR_OGHAM: + case LEX_CHAR_NARROW_NO_BREAK_SP: + case LEX_CHAR_MATHEMATICAL_SP: + case LEX_CHAR_IDEOGRAPHIC_SP: Iterator().Forward(cpSize); return true; default: - return false; + if (ch >= LEX_CHAR_ENQUAD && ch <= LEX_CHAR_ZERO_WIDTH_SP) { + Iterator().Forward(cpSize); + return true; + } else { + return false; + } } } @@ -1376,6 +1386,7 @@ void Lexer::SkipWhiteSpaces() case LEX_CHAR_FF: case LEX_CHAR_SP: case LEX_CHAR_TAB: + case LEX_CHAR_NEXT_LINE: Iterator().Forward(1); continue; case LEX_CHAR_SLASH: diff --git a/ets2panda/lexer/token/letters.h b/ets2panda/lexer/token/letters.h index 222aa6ca68..e33d21b114 100644 --- a/ets2panda/lexer/token/letters.h +++ b/ets2panda/lexer/token/letters.h @@ -82,14 +82,22 @@ inline constexpr char32_t LEX_CHAR_UPPERCASE_X = 0x58; /* X */ inline constexpr char32_t LEX_CHAR_UPPERCASE_Y = 0x59; /* Y */ inline constexpr char32_t LEX_CHAR_UPPERCASE_Z = 0x5A; /* Y */ -inline constexpr char32_t LEX_CHAR_BS = 0x08; /* backspace */ -inline constexpr char32_t LEX_CHAR_TAB = 0x09; /* character tabulation */ -inline constexpr char32_t LEX_CHAR_VT = 0x0B; /* liner tabulation */ -inline constexpr char32_t LEX_CHAR_FF = 0x0C; /* form feed */ -inline constexpr char32_t LEX_CHAR_SP = 0x20; /* space */ -inline constexpr char32_t LEX_CHAR_NBSP = 0xA0; /* no-break space */ -inline constexpr char32_t LEX_CHAR_ZWNBSP = 0xFEFF; /* zero width no-break space */ -inline constexpr char32_t LEX_CHAR_MVS = 0x180e; /* MONGOLIAN VOWEL SEPARATOR (U+180E) */ +inline constexpr char32_t LEX_CHAR_BS = 0x08; /* backspace */ +inline constexpr char32_t LEX_CHAR_TAB = 0x09; /* character tabulation */ +inline constexpr char32_t LEX_CHAR_VT = 0x0B; /* liner tabulation */ +inline constexpr char32_t LEX_CHAR_FF = 0x0C; /* form feed */ +inline constexpr char32_t LEX_CHAR_SP = 0x20; /* space */ +inline constexpr char32_t LEX_CHAR_NBSP = 0xA0; /* no-break space */ +inline constexpr char32_t LEX_CHAR_ZWNBSP = 0xFEFF; /* zero width no-break space */ +inline constexpr char32_t LEX_CHAR_MVS = 0x180e; /* MONGOLIAN VOWEL SEPARATOR (U+180E) */ +inline constexpr char32_t LEX_CHAR_NEXT_LINE = 0x85; /* next line */ +inline constexpr char32_t LEX_CHAR_OGHAM = 0x1680; /* ogham */ +inline constexpr char32_t LEX_CHAR_ENQUAD = 0X2000; +inline constexpr char32_t LEX_CHAR_ZERO_WIDTH_SP = 0x200B; +inline constexpr char32_t LEX_CHAR_NARROW_NO_BREAK_SP = 0x202F; +inline constexpr char32_t LEX_CHAR_MATHEMATICAL_SP = 0x205F; +inline constexpr char32_t LEX_CHAR_IDEOGRAPHIC_SP = 0x3000; + inline constexpr char32_t LEX_CHAR_DOUBLE_QUOTE = 0x22; /* " */ inline constexpr char32_t LEX_CHAR_DOLLAR_SIGN = 0x24; /* $ */ inline constexpr char32_t LEX_CHAR_SINGLE_QUOTE = 0x27; /* ' */ diff --git a/ets2panda/test/runtime/ets/unicode_whitespace.ets b/ets2panda/test/runtime/ets/unicode_whitespace.ets new file mode 100644 index 0000000000..dc0042c7b9 --- /dev/null +++ b/ets2panda/test/runtime/ets/unicode_whitespace.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. + */ + +// this function intentionally contains unicode whitespace +function main() { assertTrue(true) } -- Gitee From 510a06d964e43c0492cedb53009923f711e24746 Mon Sep 17 00:00:00 2001 From: ertugrulfarukpiskin Date: Fri, 20 Jun 2025 11:29:57 +0300 Subject: [PATCH 013/145] Crash with readonly Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGEEY Description: Crash with readonly when class or interface has nullable properties Signed-off-by: ertugrulfarukpiskin --- .../lowering/ets/objectLiteralLowering.cpp | 6 ++- .../ets/nullable_readonly_property.ets | 53 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/runtime/ets/nullable_readonly_property.ets diff --git a/ets2panda/compiler/lowering/ets/objectLiteralLowering.cpp b/ets2panda/compiler/lowering/ets/objectLiteralLowering.cpp index e24fe2ea47..bcc71b964c 100644 --- a/ets2panda/compiler/lowering/ets/objectLiteralLowering.cpp +++ b/ets2panda/compiler/lowering/ets/objectLiteralLowering.cpp @@ -14,7 +14,6 @@ */ #include "objectLiteralLowering.h" - #include "checker/ETSchecker.h" #include "compiler/lowering/scopesInit/scopesInitPhase.h" #include "compiler/lowering/util.h" @@ -130,6 +129,11 @@ static void PopulateCtorArgumentsFromMap(public_lib::Context *ctx, ir::ObjectExp ctorArguments.push_back(allocator->New()); continue; } + if (ctorArgument == nullptr && param->TsType()->PossiblyETSUndefined()) { + ctorArguments.push_back(allocator->New()); + continue; + } + ES2PANDA_ASSERT(ctorArgument != nullptr); ctorArguments.push_back(ctorArgument); } } diff --git a/ets2panda/test/runtime/ets/nullable_readonly_property.ets b/ets2panda/test/runtime/ets/nullable_readonly_property.ets new file mode 100644 index 0000000000..ab468df7ed --- /dev/null +++ b/ets2panda/test/runtime/ets/nullable_readonly_property.ets @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Actions { + readonly type: string; + readonly id: string; +} + +export interface VerifyCodeFixAvailableOptions { + readonly description: string; + readonly actions?: ReadonlyArray; + readonly commands?: ReadonlyArray; +} + +class verify { + static codeFixAvailable(options?: ReadonlyArray): void { + arktest.assertEQ(options![0].description, "Implement interface 'I1'"); + arktest.assertEQ(options![0].actions, undefined); + arktest.assertEQ(options![0].commands, undefined); + arktest.assertEQ(options![1].description, "Implement interface 'I2'"); + arktest.assertEQ(options![1].actions, undefined); + arktest.assertEQ(options![1].commands, undefined); + arktest.assertEQ(options![2].description, "Implement interface 'I3'"); + arktest.assertEQ(options![2].actions![0].type, "IA"); + arktest.assertEQ(options![2].actions![0].id, "IA1"); + arktest.assertEQ(options![2].commands, undefined); + arktest.assertEQ(options![3].description, "Implement interface 'I4'"); + arktest.assertEQ(options![3].actions![0].type, "IB"); + arktest.assertEQ(options![3].actions![0].id, "IB1"); + arktest.assertEQ(options![3].commands![0], "CMD1"); + }; +} + +function main() { + verify.codeFixAvailable([ + { description: "Implement interface 'I1'" }, + { description: "Implement interface 'I2'" }, + { description: "Implement interface 'I3'", actions: [ { type: "IA", id: "IA1" } ] as Actions[] }, + { description: "Implement interface 'I4'", actions: [ { type: "IB", id: "IB1" } ] as Actions[], commands: [ "CMD1" ] } + ] as VerifyCodeFixAvailableOptions[]) +} \ No newline at end of file -- Gitee From 56092a663f04888b2a488d51b48c0d3cec0ef5f1 Mon Sep 17 00:00:00 2001 From: Tamas Toth Date: Tue, 3 Jun 2025 12:55:24 +0200 Subject: [PATCH 014/145] Throw error when setter return type is void Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICCAJQ Fixes #25831 internal issue Change-Id: I185d3df441f95b639d335c198d12b6b6f4ec1ebf Signed-off-by: Tamas Toth --- ets2panda/parser/ETSparserClasses.cpp | 5 ++++ .../parser/ets/setter_with_return_type.ets | 28 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 ets2panda/test/ast/parser/ets/setter_with_return_type.ets diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index c1dc7c92e0..fcfad7919b 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -834,6 +834,11 @@ ir::MethodDefinition *ETSParser::ParseInterfaceGetterSetterMethod(const ir::Modi method->Function()->SetIdent(method->Id()->Clone(Allocator(), nullptr)); method->Function()->AddModifier(method->Modifiers()); + bool hasReturn = method->Function()->ReturnTypeAnnotation() != nullptr; + if (hasReturn && methodKind == ir::MethodDefinitionKind::SET) { + LogError(diagnostic::SETTER_NO_RETURN_TYPE, {}, method->Function()->Range().start); + } + return method; } diff --git a/ets2panda/test/ast/parser/ets/setter_with_return_type.ets b/ets2panda/test/ast/parser/ets/setter_with_return_type.ets new file mode 100644 index 0000000000..6764147803 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/setter_with_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 C{ + n: number = 42 +} + +interface I{ + get n(): number + set n(v:number):void +} + +class D extends C implements I{ +} + +/* @@? 22:10 Error SyntaxError: Setter must not have return type even if it is void. */ -- Gitee From 179ab08237d10fa816389b395f2b6bd5325db3ef Mon Sep 17 00:00:00 2001 From: lihao <1453238523@qq.com> Date: Tue, 24 Jun 2025 00:33:24 +0800 Subject: [PATCH 015/145] cherry pick 0603 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICH92U Signed-off-by: lihao Change-Id: Ic883b20718a4024206b67bee518d79e1da37718f --- ets2panda/driver/build_system/src/build/base_mode.ts | 3 ++- 1 file changed, 2 insertions(+), 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 c5282cded0..5862c017b1 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -558,7 +558,8 @@ export abstract class BaseMode { } this.entryFiles.forEach((file: string) => { for (const [packageName, moduleInfo] of this.moduleInfos) { - if (!file.startsWith(moduleInfo.moduleRootPath)) { + const relativePath = path.relative(moduleInfo.moduleRootPath, file); + if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) { continue; } let filePathFromModuleRoot: string = path.relative(moduleInfo.moduleRootPath, file); -- Gitee From 29a778cccc69e1e18944c37f6ed7ce6d5f60d80a Mon Sep 17 00:00:00 2001 From: liushitong Date: Mon, 23 Jun 2025 16:39:29 +0800 Subject: [PATCH 016/145] [LSP]: fix getDefinitionAtPosition Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHJ7J Signed-off-by: liushitong --- ets2panda/bindings/test/cases.ts | 3 +- .../expected/getDefinitionAtPosition.json | 5 ++++ .../expected/getSyntacticDiagnostics.json | 4 +-- ets2panda/bindings/test/run_tests.ts | 28 +++++++++++++++++++ .../getDefinitionAtPosition19.ets | 16 +++++++++++ ets2panda/lsp/src/api.cpp | 19 ++++++++----- .../get_definition_and_bound_span_test.cpp | 17 ++++++----- .../lsp/get_definition_at_position_test.cpp | 20 +++++++++++++ 8 files changed, 93 insertions(+), 19 deletions(-) create mode 100644 ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition19.ets diff --git a/ets2panda/bindings/test/cases.ts b/ets2panda/bindings/test/cases.ts index 87a87dc23e..3c4cde6076 100644 --- a/ets2panda/bindings/test/cases.ts +++ b/ets2panda/bindings/test/cases.ts @@ -44,7 +44,8 @@ export const testCases: TestCases = { '7': [resolveTestPath('test/testcases/getDefinitionAtPosition/getDefinitionAtPosition13.ets'), 664], '8': [resolveTestPath('test/testcases/getDefinitionAtPosition/getDefinitionAtPosition15.ets'), 617], '9': [resolveTestPath('test/testcases/getDefinitionAtPosition/getDefinitionAtPosition17.ets'), 677], - '10': [resolveTestPath('test/testcases/getDefinitionAtPosition/getDefinitionAtPosition18.ets'), 930] + '10': [resolveTestPath('test/testcases/getDefinitionAtPosition/getDefinitionAtPosition18.ets'), 930], + '11': [resolveTestPath('test/testcases/getDefinitionAtPosition/getDefinitionAtPosition19.ets'), 634] }, getSemanticDiagnostics: { expectedFilePath: resolveTestPath('test/expected/getSemanticDiagnostics.json'), diff --git a/ets2panda/bindings/test/expected/getDefinitionAtPosition.json b/ets2panda/bindings/test/expected/getDefinitionAtPosition.json index 74bd51b3c2..73b1339876 100644 --- a/ets2panda/bindings/test/expected/getDefinitionAtPosition.json +++ b/ets2panda/bindings/test/expected/getDefinitionAtPosition.json @@ -48,5 +48,10 @@ "fileName": "text.d.ets", "start": 7586, "length": 4 + }, + "11": { + "fileName": "taskpool.ets", + "start": 686, + "length": 4 } } \ No newline at end of file diff --git a/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json b/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json index 2ed128d561..35b5984191 100644 --- a/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json +++ b/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json @@ -247,8 +247,8 @@ } }, { - "message": "Unexpected token ')'.", - "source": "*ERROR_LITERAL*", + "message": "Unexpected token '{'.", + "source": "{\n return ((a) + (b));\n}", "range": { "start": { "line": 16, diff --git a/ets2panda/bindings/test/run_tests.ts b/ets2panda/bindings/test/run_tests.ts index ecb0adaa16..7d6edb92a1 100644 --- a/ets2panda/bindings/test/run_tests.ts +++ b/ets2panda/bindings/test/run_tests.ts @@ -241,6 +241,21 @@ function findTextDefinitionPosition(sourceCode: string): number { throw new Error('Could not find Text definition in source code'); } +// CC-OFFNXT(huge_cyclomatic_complexity, huge_depth, huge_method) false positive +function findTaskDefinitionPosition(sourceCode: string): number { + const taskDefinitionPattern = /export\s+class\s+Task\s+{/; + const match = taskDefinitionPattern.exec(sourceCode); + if (match) { + const classTaskPattern = /class\s+Task\s+{/; + const subMatch = classTaskPattern.exec(sourceCode.substring(match.index)); + if (subMatch) { + const positionOfT = match.index + subMatch.index + 'class '.length; + return positionOfT; + } + } + throw new Error('Could not find Task definition in source code'); +} + function compareGetDefinitionResult(testName: string, actual: any, expected: Record): boolean { // This is the definition info for the UI component. // File in the SDK might changed, so the offset needs to be checked dynamically. @@ -255,6 +270,19 @@ function compareGetDefinitionResult(testName: string, actual: any, expected: Rec }; return compareResultsHelper(testName, normalizeData(actual), expectedResult); } + // This is the definition info for the class in std library. + // File in the SDK might changed, so the offset needs to be checked dynamically. + if (expected['fileName'] === 'taskpool.ets') { + const actualDef = actual as LspDefinitionData; + const fileName = actualDef.fileName as string; + const fileContent = fs.readFileSync(fileName, 'utf8'); + const expectedStart = findTaskDefinitionPosition(fileContent); + const expectedResult = { + ...expected, + start: expectedStart + }; + return compareResultsHelper(testName, normalizeData(actual), expectedResult); + } return compareResultsHelper(testName, normalizeData(actual), expected); } diff --git a/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition19.ets b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition19.ets new file mode 100644 index 0000000000..fc811ab595 --- /dev/null +++ b/ets2panda/bindings/test/testcases/getDefinitionAtPosition/getDefinitionAtPosition19.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. + */ + +const task = new taskpool.Task(()=>{}); diff --git a/ets2panda/lsp/src/api.cpp b/ets2panda/lsp/src/api.cpp index 9c9b217952..aeca335a37 100644 --- a/ets2panda/lsp/src/api.cpp +++ b/ets2panda/lsp/src/api.cpp @@ -51,19 +51,24 @@ DefinitionInfo GetDefinitionAtPosition(es2panda_Context *context, size_t positio auto declInfo = GetDefinitionAtPositionImpl(context, position); DefinitionInfo result {}; auto node = declInfo.first; + auto targetNode = declInfo.first->FindChild([&declInfo](ir::AstNode *childNode) { + return childNode->IsIdentifier() && childNode->AsIdentifier()->Name() == declInfo.second; + }); + std::string name; while (node != nullptr) { + if (node->Range().start.Program() != nullptr) { + name = std::string(node->Range().start.Program()->SourceFile().GetAbsolutePath().Utf8()); + break; + } if (node->IsETSModule()) { - auto name = std::string(node->AsETSModule()->Program()->SourceFilePath()); - auto targetNode = declInfo.first->FindChild([&declInfo](ir::AstNode *childNode) { - return childNode->IsIdentifier() && childNode->AsIdentifier()->Name() == declInfo.second; - }); - if (targetNode != nullptr) { - result = {name, targetNode->Start().index, targetNode->End().index - targetNode->Start().index}; - } + name = std::string(node->AsETSModule()->Program()->SourceFilePath()); break; } node = node->Parent(); } + if (targetNode != nullptr) { + result = {name, targetNode->Start().index, targetNode->End().index - targetNode->Start().index}; + } return result; } diff --git a/ets2panda/test/unit/lsp/get_definition_and_bound_span_test.cpp b/ets2panda/test/unit/lsp/get_definition_and_bound_span_test.cpp index af99f95900..6476359c37 100644 --- a/ets2panda/test/unit/lsp/get_definition_and_bound_span_test.cpp +++ b/ets2panda/test/unit/lsp/get_definition_and_bound_span_test.cpp @@ -25,7 +25,7 @@ class LSPGetDefinitionAndBoundSpanTests : public LSPAPITests {}; TEST_F(LSPGetDefinitionAndBoundSpanTests, GetDefinitionAndBoundSpan_FunctionReference) { - const auto fileName = "definition1.ets"; + const auto fileName = "GetDefinitionAndBoundSpan1.ets"; const auto fileContent = R"( function sum(a: number, b: number): number { return a + b; @@ -44,11 +44,12 @@ let total = sum(5, 10); auto filePaths = CreateTempFile(files, texts); ark::es2panda::lsp::Initializer initializer; - es2panda_Context *ctx = initializer.CreateContext(files.at(index0).c_str(), ES2PANDA_STATE_CHECKED, fileContent); + es2panda_Context *ctx = initializer.CreateContext(filePaths.at(index0).c_str(), ES2PANDA_STATE_CHECKED); const auto result = ark::es2panda::lsp::GetDefinitionAndBoundSpan(ctx, offset); EXPECT_FALSE(result.definitionInfo.fileName.empty()); + EXPECT_EQ(result.definitionInfo.fileName, filePaths.at(index0)); EXPECT_EQ(result.definitionInfo.length, index3); EXPECT_EQ(result.boundSpan.length, index3); EXPECT_EQ(result.definitionInfo.start + result.definitionInfo.length, index13); @@ -60,7 +61,7 @@ let total = sum(5, 10); TEST_F(LSPGetDefinitionAndBoundSpanTests, GetDefinitionAndBoundSpan_FunctionReferenceTwoFile) { - std::vector fileNames = {"lsp_api_test_export_1.ets", "lsp_api_test_file_1.ets"}; + std::vector fileNames = {"GetDefinitionAndBoundSpan_export.ets", "GetDefinitionAndBoundSpan2.ets"}; std::vector texts = { R"(export function A(a:number, b:number): number { return a + b; @@ -68,8 +69,8 @@ TEST_F(LSPGetDefinitionAndBoundSpanTests, GetDefinitionAndBoundSpan_FunctionRefe export function B(a:number, b:number): number { return a + b; })", - R"(import {A} from "./lsp_api_test_export_1"; -import {B} from "./lsp_api_test_export_1.ets"; + R"(import {A} from "./GetDefinitionAndBoundSpan_export"; +import {B} from "./GetDefinitionAndBoundSpan_export.ets"; A(1, 2); B(1, 2);)"}; @@ -77,15 +78,13 @@ B(1, 2);)"}; int const expectedFileCount = 2; ASSERT_EQ(filePaths.size(), expectedFileCount); - const size_t offset = 94; + const size_t offset = 116; const size_t index0 = 0; const size_t index1 = 1; const size_t index13 = 17; ark::es2panda::lsp::Initializer initializer; - es2panda_Context *ctx = - initializer.CreateContext(filePaths.at(index1).c_str(), ES2PANDA_STATE_CHECKED, texts.at(index1).c_str()); + es2panda_Context *ctx = initializer.CreateContext(filePaths.at(index1).c_str(), ES2PANDA_STATE_CHECKED); - std::cout << "offset: " << offset << std::endl; const auto result = ark::es2panda::lsp::GetDefinitionAndBoundSpan(ctx, offset); EXPECT_FALSE(result.definitionInfo.fileName.empty()); diff --git a/ets2panda/test/unit/lsp/get_definition_at_position_test.cpp b/ets2panda/test/unit/lsp/get_definition_at_position_test.cpp index 77ee577273..e5636a2807 100644 --- a/ets2panda/test/unit/lsp/get_definition_at_position_test.cpp +++ b/ets2panda/test/unit/lsp/get_definition_at_position_test.cpp @@ -294,3 +294,23 @@ a.Foo(1, 2);)"}; ASSERT_EQ(result1.start, expectedStart1); ASSERT_EQ(result1.length, expectedLength1); } + +TEST_F(LspGetDefTests, GetDefinitionAtPositionForStdLibraryTaskPool) +{ + std::vector files = {"getDefinitionAtPositionForStdLibraryTaskPool.ets"}; + std::vector texts = {R"(const task = new taskpool.Task(()=>{});)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 21; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto result = lspApi->getDefinitionAtPosition(ctx, offset); + initializer.DestroyContext(ctx); + std::string expectedFileName = "taskpool.ets"; + size_t const expectedLength = 8; + ASSERT_TRUE(result.fileName.find(expectedFileName) != std::string::npos); + ASSERT_EQ(result.length, expectedLength); +} -- Gitee From ae0f0868ce4ca1bdfdbda117ee16a35e388c6e52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A2=81=E5=AE=B6=E7=86=99?= Date: Tue, 10 Jun 2025 15:44:40 +0800 Subject: [PATCH 017/145] Fix several compile errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICE1XP Signed-off-by: 梁家熙 --- ets2panda/checker/ETSAnalyzer.cpp | 23 +++- ets2panda/checker/ets/function.cpp | 4 + ets2panda/checker/ets/helpers.cpp | 4 + ets2panda/checker/ets/typeCheckingHelpers.cpp | 4 + ets2panda/compiler/base/lreference.cpp | 4 + .../ets/optionalArgumentsLowering.cpp | 5 + ets2panda/ir/brokenTypeNode.cpp | 9 ++ ets2panda/ir/brokenTypeNode.h | 2 + .../ets/anno_interface_invalid_error.ets | 49 ++++++++ .../ets/recursive_clousre_reference_error.ets | 23 ++++ .../ets/recursive_exported_structure.ets | 110 ++++++++++++++++++ .../ast/parser/ets/update_funcscope_error.ets | 41 +++++++ 12 files changed, 273 insertions(+), 5 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/anno_interface_invalid_error.ets create mode 100644 ets2panda/test/ast/parser/ets/recursive_clousre_reference_error.ets create mode 100644 ets2panda/test/ast/parser/ets/recursive_exported_structure.ets create mode 100644 ets2panda/test/ast/parser/ets/update_funcscope_error.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 2c0fd6a3fc..5fb41310c5 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -1500,6 +1500,10 @@ checker::Type *ETSAnalyzer::GetCallExpressionReturnType(ir::CallExpression *expr return returnType; } + if (!signature->HasFunction()) { + return checker->GlobalTypeError(); + } + auto owner = const_cast(util::Helpers::GetContainingObjectType(signature->Function())); SavedCheckerContext savedCtx(ReconstructOwnerClassContext(checker, owner)); @@ -1879,7 +1883,15 @@ static void SetTypeforRecordProperties(const ir::ObjectExpression *expr, checker auto *const valueType = typeArguments[1]; // Record type arguments for (auto *const recordProperty : recordProperties) { - auto *const recordPropertyExpr = recordProperty->AsProperty()->Value(); + ir::Expression *recordPropertyExpr = nullptr; + if (recordProperty->IsProperty()) { + recordPropertyExpr = recordProperty->AsProperty()->Value(); + } else if (recordProperty->IsSpreadElement()) { + recordPropertyExpr = recordProperty->AsSpreadElement()->Argument(); + } else { + ES2PANDA_UNREACHABLE(); + } + ETSChecker::SetPreferredTypeIfPossible(recordPropertyExpr, valueType); recordPropertyExpr->Check(checker); } @@ -2390,6 +2402,11 @@ checker::Type *ETSAnalyzer::Check(ir::SuperExpression *expr) const checker::Type *ETSAnalyzer::Check(ir::TemplateLiteral *expr) const { ETSChecker *checker = GetETSChecker(); + + for (auto *it : expr->Expressions()) { + it->Check(checker); + } + if (expr->TsType() != nullptr) { return expr->TsType(); } @@ -2400,10 +2417,6 @@ checker::Type *ETSAnalyzer::Check(ir::TemplateLiteral *expr) const return expr->TsType(); } - for (auto *it : expr->Expressions()) { - it->Check(checker); - } - for (auto *it : expr->Quasis()) { it->Check(checker); } diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 167f9e40b2..b99e372375 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1090,6 +1090,10 @@ Signature *ETSChecker::ResolvePotentialTrailingLambdaWithReceiver(ir::CallExpres ArenaVector sigContainLambdaWithReceiverAsParam(ProgramAllocator()->Adapter()); Signature *signature = nullptr; for (auto sig : signatures) { + if (!sig->HasFunction()) { + continue; + } + if (!IsLastParameterLambdaWithReceiver(sig)) { normalSig.emplace_back(sig); continue; diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index c799944902..a1e1239e7a 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -780,6 +780,10 @@ static void CheckRecordType(ir::Expression *init, checker::Type *annotationType, auto properties = objectExpr->Properties(); for (const auto &property : properties) { + if (!property->IsProperty()) { + checker->LogError(diagnostic::IMPROPER_NESTING_INTERFACE, {}, property->Start()); + continue; + } ES2PANDA_ASSERT(property->IsProperty()); auto p = property->AsProperty(); diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 1fa0493279..ce9a69bfb6 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -1143,6 +1143,10 @@ void ETSChecker::CheckMultiplePropertiesAnnotation(ir::AnnotationUsage *st, util continue; } + if (result->second == nullptr || result->second->TypeAnnotation() == nullptr) { + continue; + } + // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto clone = result->second->TypeAnnotation()->Clone(ProgramAllocator(), param); param->SetTypeAnnotation(clone); diff --git a/ets2panda/compiler/base/lreference.cpp b/ets2panda/compiler/base/lreference.cpp index 240aa09bd3..f9651af734 100644 --- a/ets2panda/compiler/base/lreference.cpp +++ b/ets2panda/compiler/base/lreference.cpp @@ -69,6 +69,10 @@ LReference::LReferenceBase LReference::CreateBase(CodeGen *cg, const ir::AstNode case ir::AstNodeType::TS_NON_NULL_EXPRESSION: { return CreateBase(cg, node->AsTSNonNullExpression()->Expr(), isDeclaration); } + case ir::AstNodeType::ETS_NEW_CLASS_INSTANCE_EXPRESSION: { + ES2PANDA_ASSERT(node->AsETSNewClassInstanceExpression()->GetArguments().size() == 1); + return CreateBase(cg, node->AsETSNewClassInstanceExpression()->GetArguments()[0], isDeclaration); + } default: { ES2PANDA_UNREACHABLE(); } diff --git a/ets2panda/compiler/lowering/ets/optionalArgumentsLowering.cpp b/ets2panda/compiler/lowering/ets/optionalArgumentsLowering.cpp index 701623fc52..969fabd2d2 100644 --- a/ets2panda/compiler/lowering/ets/optionalArgumentsLowering.cpp +++ b/ets2panda/compiler/lowering/ets/optionalArgumentsLowering.cpp @@ -71,6 +71,11 @@ bool OptionalArgumentsLowering::PerformForModule(public_lib::Context *ctx, parse [ctx](ir::AstNode *const node) -> ir::AstNode * { if (node->IsCallExpression()) { auto callExpr = node->AsCallExpression(); + if (callExpr->Signature() == nullptr) { + ctx->parser->LogError(diagnostic::IMPROPER_NESTING_INTERFACE, {}, node->Start()); + return node; + } + callExpr->IsTrailingCall() ? TransformArgumentsForTrailingLambda(ctx, callExpr->AsCallExpression(), callExpr->Signature()) : TransformArguments(ctx, callExpr, callExpr->Signature(), callExpr->Arguments()); diff --git a/ets2panda/ir/brokenTypeNode.cpp b/ets2panda/ir/brokenTypeNode.cpp index 7194b87d8d..110222066d 100644 --- a/ets2panda/ir/brokenTypeNode.cpp +++ b/ets2panda/ir/brokenTypeNode.cpp @@ -68,4 +68,13 @@ checker::VerifiedType BrokenTypeNode::Check([[maybe_unused]] checker::ETSChecker { return {this, checker->GetAnalyzer()->Check(this)}; } + +BrokenTypeNode *BrokenTypeNode::Clone(ArenaAllocator *const allocator, AstNode *const parent) +{ + auto *const clone = allocator->New(allocator); + if (parent != nullptr) { + clone->SetParent(parent); + } + return clone; +} } // namespace ark::es2panda::ir diff --git a/ets2panda/ir/brokenTypeNode.h b/ets2panda/ir/brokenTypeNode.h index 81df2eeea8..f4143f6adf 100644 --- a/ets2panda/ir/brokenTypeNode.h +++ b/ets2panda/ir/brokenTypeNode.h @@ -43,6 +43,8 @@ public: checker::VerifiedType Check([[maybe_unused]] checker::ETSChecker *checker) override; checker::Type *GetType([[maybe_unused]] checker::ETSChecker *checker) override; + [[nodiscard]] BrokenTypeNode *Clone(ArenaAllocator *allocator, AstNode *parent) override; + void Accept(ASTVisitorT *v) override { v->Accept(this); diff --git a/ets2panda/test/ast/parser/ets/anno_interface_invalid_error.ets b/ets2panda/test/ast/parser/ets/anno_interface_invalid_error.ets new file mode 100644 index 0000000000..f8549d0093 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/anno_interface_invalid_error.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. + */ + +const enum E { + A = 10, + B = 20, + C = 30 +} + +const enum E1 { + A = "A", + B = "B" +} + +@interface Anno { + a: number + b = [(10 + 3), E.A] + c: string + d: boolean + e: E[] = [E.A, E.B, E.C] + f: number[] + g: number[][][] + h: E + i: E[][][] + j: E1 + k: E1[][][] +} + + +@Anno({a: E.A + 10, c: "a" + "b", d: (1 === 1), f: [], g: [[[0]]], h: E.A, i: [], j: E1.B, k: []}) +class C{ + @Anno({a: 10, b: [1, 2, 3], c: "cde", d: true, f: [1], g:[[[0], [1]]], h: E.A, i: [[[E.A], [E.B]]], j: E1.B, k: [[[E1.A], [E1.B]]]}) + public foo() {} +} + +/* @@? 29:4 Error SyntaxError: Missing type annotation for property 'b'. */ +/* @@? 42:11 Error SyntaxError: Only constant expression is expected in the field */ diff --git a/ets2panda/test/ast/parser/ets/recursive_clousre_reference_error.ets b/ets2panda/test/ast/parser/ets/recursive_clousre_reference_error.ets new file mode 100644 index 0000000000..5f86308441 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/recursive_clousre_reference_error.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 foo() { + let x = () => y(); + let y = () => x(); + x(); +} + +/* @@? 17:19 Error TypeError: Variable 'y' is accessed before it's initialization. */ +/* @@? 18:9 Error TypeError: Circular dependency detected for identifier: y */ diff --git a/ets2panda/test/ast/parser/ets/recursive_exported_structure.ets b/ets2panda/test/ast/parser/ets/recursive_exported_structure.ets new file mode 100644 index 0000000000..f9dc3af5f8 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/recursive_exported_structure.ets @@ -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. + */ + +const TopLevelSym: string = "TopLevelSym"; +const InnerSym: string = "InnerSym"; + +const _topLevelFunc = (x: number | undefined): number => { + if (x === undefined) { + return 12; + } + return x; +}; + +const _innerFunc = (arg: { x: number } | undefined): number => { + if (arg === undefined) { + return 12; + } + return arg.x; +}; + +type NumberFunc = () => number; + +// Indexable type for items +type IndexableType = Record; + +// Explicitly typed indexable object +const _items: IndexableType = {}; +const innerFunction: NumberFunc = () => { + return _innerFunc({ x: 12 }); +}; + +// Fix: Assign computed property safely (done after object creation) +_items[InnerSym] = innerFunction; + +const topLevelWrapper: NumberFunc = () => { + return _topLevelFunc(12); +}; + +// Inner map using the same indexable type +const innerMap: IndexableType = {}; +const innerMapFunction: NumberFunc = () => { + const result = _innerFunc({ x: 12 }); + return result; +}; + +innerMap[InnerSym] = innerMapFunction; + +// Define the exported structure explicitly +type ExportedType = Record & { + items: IndexableType; +}; + +// Create a base object without computed properties +class ExportedStructure implements ExportedType { + items: IndexableType; + + constructor() { + this.items = innerMap; + } + + [key: string]: NumberFunc | IndexableType; + + static createBase(): ExportedType { + return new ExportedStructure() as ExportedType; + } +} + +// Create the exported structure and assign dynamic keys safely +const baseExportedStructure: ExportedType = ExportedStructure.createBase(); +const _exportedStructure: ExportedType = { ...baseExportedStructure }; + +// Assign computed key after object creation (not in literal) +_exportedStructure[TopLevelSym] = topLevelWrapper; + +const _exported: ExportedType = _exportedStructure; + +export default _exported; + +/* @@? 26:26 Error SyntaxError: Invalid Type. */ +/* @@? 41:12 Error TypeError: No matching call signature for (...) */ +/* @@? 41:23 Error TypeError: need to specify target type for class composite */ +/* @@? 54:20 Error TypeError: No matching call signature for (...) */ +/* @@? 54:31 Error TypeError: need to specify target type for class composite */ +/* @@? 61:64 Error SyntaxError: Unexpected token '&'. */ +/* @@? 61:66 Error SyntaxError: Unexpected token '{'. */ +/* @@? 62:12 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 62:12 Error TypeError: Type name 'IndexableType' used in the wrong context */ +/* @@? 66:36 Error TypeError: Interface expected here. */ +/* @@? 73:6 Error SyntaxError: Unexpected token 'key'. */ +/* @@? 73:9 Error SyntaxError: Unexpected token ':'. */ +/* @@? 73:17 Error SyntaxError: Field type annotation expected. */ +/* @@? 73:17 Error SyntaxError: Unexpected token ']'. */ +/* @@? 73:18 Error SyntaxError: Unexpected token ':'. */ +/* @@? 73:31 Error SyntaxError: Unexpected token '|'. */ +/* @@? 73:31 Error SyntaxError: Field type annotation expected. */ +/* @@? 73:46 Error SyntaxError: Field type annotation expected. */ +/* @@? 76:16 Error TypeError: Cannot cast type 'ExportedStructure' to 'Record Double|Record Double>>' */ +/* @@? 82:44 Error SyntaxError: Property or signature expected. */ diff --git a/ets2panda/test/ast/parser/ets/update_funcscope_error.ets b/ets2panda/test/ast/parser/ets/update_funcscope_error.ets new file mode 100644 index 0000000000..5d2ca8cb59 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/update_funcscope_error.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. + */ + +type UpdateFunc = (u: Record) => Record; +type ReducerFunc = (key: string) => Record; + +export const updateIfChanged = (t: Record) => { + const reducerFunc: ReducerFunc = (key) => { + const value = u[key]; + const reduceResult = reduce( + value as Record, + (v: Record) => { + const baseU = u; + const updatedU: Record = { + ...baseU, + [key]: v + }; + return update(updatedU); + } + ); + return reduceResult; + }; +}; + +/* @@? 21:19 Error TypeError: Unresolved reference u */ +/* @@? 21:19 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 24:7 Error TypeError: Type '(v: Record) => Boolean' is not compatible with type '(previousValue: Boolean, currentValue: Boolean, index: Double, array: FixedArray) => Boolean' at index 2 */ +/* @@? 27:11 Error SyntaxError: Property or signature expected. */ +/* @@? 30:16 Error TypeError: Unresolved reference update */ -- Gitee From 058d97808f674d01e2d0dbff11dda9ee06b4e0bc Mon Sep 17 00:00:00 2001 From: nikozer Date: Tue, 3 Jun 2025 14:13:46 +0300 Subject: [PATCH 018/145] transfer stdlib from no-primitives Issue: [cherry-pick to 0603] transfer stdlib for primitives https://gitee.com/openharmony/arkcompiler_runtime_core/issues/ICI2AJ Test: ninja etsstdlib Signed-off-by: nikozer --- ets2panda/driver/build_system/src/build/build_mode.ts | 2 +- ets2panda/test/ast/parser/ets/recordKeyTypeCheck01.ets | 4 ++-- ets2panda/test/ast/parser/ets/recordKeyTypeCheck02.ets | 4 ++-- ets2panda/test/ast/parser/ets/recordKeyTypeCheck03.ets | 2 +- ets2panda/test/ast/parser/ets/type_from_utility_type.ets | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/build_mode.ts b/ets2panda/driver/build_system/src/build/build_mode.ts index 59bdb759ab..b1643a8d9c 100644 --- a/ets2panda/driver/build_system/src/build/build_mode.ts +++ b/ets2panda/driver/build_system/src/build/build_mode.ts @@ -26,6 +26,6 @@ export class BuildMode extends BaseMode { } public async run(): Promise { - await super.runParallell(); + await super.run(); } } \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/recordKeyTypeCheck01.ets b/ets2panda/test/ast/parser/ets/recordKeyTypeCheck01.ets index 982bba0c4e..2566f9cbb7 100644 --- a/ets2panda/test/ast/parser/ets/recordKeyTypeCheck01.ets +++ b/ets2panda/test/ast/parser/ets/recordKeyTypeCheck01.ets @@ -17,6 +17,6 @@ function main(){ let a: Record/* @@ label */ = { "key1": 1, "key2": 2 - } + } } -/* @@@ label Error TypeError: Type Char|String is not assignable to constraint type Numeric|String */ +/* @@@ label Error TypeError: Type Char|String is not assignable to constraint type Numeric|String|BaseEnum|BaseEnum|BaseEnum */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/recordKeyTypeCheck02.ets b/ets2panda/test/ast/parser/ets/recordKeyTypeCheck02.ets index 71687363c5..7d56f11a52 100644 --- a/ets2panda/test/ast/parser/ets/recordKeyTypeCheck02.ets +++ b/ets2panda/test/ast/parser/ets/recordKeyTypeCheck02.ets @@ -19,6 +19,6 @@ function main(){ let a: Record/* @@ label */ = { 1: 1, 2: 2 - } + } } -/* @@@ label Error TypeError: Type A|Double is not assignable to constraint type Numeric|String */ +/* @@@ label Error TypeError: Type A|Double is not assignable to constraint type Numeric|String|BaseEnum|BaseEnum|BaseEnum */ diff --git a/ets2panda/test/ast/parser/ets/recordKeyTypeCheck03.ets b/ets2panda/test/ast/parser/ets/recordKeyTypeCheck03.ets index 316c665343..e8ea8a181e 100644 --- a/ets2panda/test/ast/parser/ets/recordKeyTypeCheck03.ets +++ b/ets2panda/test/ast/parser/ets/recordKeyTypeCheck03.ets @@ -18,4 +18,4 @@ class A{} function main(){ let a: Record/* @@ label */ } -/* @@@ label Error TypeError: Type BigInt is not assignable to constraint type Numeric|String */ +/* @@@ label Error TypeError: Type BigInt is not assignable to constraint type Numeric|String|BaseEnum|BaseEnum|BaseEnum */ diff --git a/ets2panda/test/ast/parser/ets/type_from_utility_type.ets b/ets2panda/test/ast/parser/ets/type_from_utility_type.ets index 36718f3d1e..f36c443a76 100644 --- a/ets2panda/test/ast/parser/ets/type_from_utility_type.ets +++ b/ets2panda/test/ast/parser/ets/type_from_utility_type.ets @@ -35,5 +35,5 @@ /* @@? 30:19 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ /* @@? 30:29 Error TypeError: No static $_invoke method and static $_instantiate method in Record. Record() is not allowed. */ /* @@? 30:29 Error TypeError: Type 'Record' has no call signatures. */ - /* @@? 31:38 Error TypeError: Type Array is not assignable to constraint type Numeric|String */ - /* @@? 32:38 Error TypeError: Type Array is not assignable to constraint type Numeric|String */ \ No newline at end of file + /* @@? 31:38 Error TypeError: Type Array is not assignable to constraint type Numeric|String|BaseEnum|BaseEnum|BaseEnum */ + /* @@? 32:38 Error TypeError: Type Array is not assignable to constraint type Numeric|String|BaseEnum|BaseEnum|BaseEnum */ \ No newline at end of file -- Gitee From ae3e25228177d1a7d93f04ae36425e7ac098c82c Mon Sep 17 00:00:00 2001 From: oh_ci Date: Thu, 26 Jun 2025 12:24:53 +0000 Subject: [PATCH 019/145] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: oh_ci --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index 2ab6c79989..672cb47d20 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -108,3 +108,8 @@ debug模式: - [ ] 不涉及 **Email:** chenqiuyao@huawei.com + +### L0新增用例自检结果 +- [ ] 是,有新增L0用例,且完成自检 +- [ ] 否 + -- Gitee From 4aa055fe0584333d216c8d881bb89bcb5495d4c2 Mon Sep 17 00:00:00 2001 From: fcc Date: Wed, 11 Jun 2025 17:16:10 +0800 Subject: [PATCH 020/145] fix duplicate names with builtins Avoid name conflict with builtins. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICEJG7 Signed-off-by: fcc --- ets2panda/checker/ETSchecker.cpp | 14 ++++++++------ .../ets/typealias_conflict_with_builtin.ets | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/typealias_conflict_with_builtin.ets diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index 452cf67b95..227ef17874 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -76,13 +76,15 @@ static util::StringView InitBuiltin(ETSChecker *checker, std::string_view signat ES2PANDA_ASSERT(iterator != varMap.end()); auto *var = iterator->second; Type *type {nullptr}; - if (var->Declaration()->Node()->IsClassDefinition()) { - type = checker->BuildBasicClassProperties(var->Declaration()->Node()->AsClassDefinition()); - } else { - ES2PANDA_ASSERT(var->Declaration()->Node()->IsTSInterfaceDeclaration()); - type = checker->BuildBasicInterfaceProperties(var->Declaration()->Node()->AsTSInterfaceDeclaration()); + if (var->HasFlag(varbinder::VariableFlags::BUILTIN_TYPE)) { + if (var->Declaration()->Node()->IsClassDefinition()) { + type = checker->BuildBasicClassProperties(var->Declaration()->Node()->AsClassDefinition()); + } else { + ES2PANDA_ASSERT(var->Declaration()->Node()->IsTSInterfaceDeclaration()); + type = checker->BuildBasicInterfaceProperties(var->Declaration()->Node()->AsTSInterfaceDeclaration()); + } + checker->GetGlobalTypesHolder()->InitializeBuiltin(iterator->first, type); } - checker->GetGlobalTypesHolder()->InitializeBuiltin(iterator->first, type); return iterator->first; } diff --git a/ets2panda/test/ast/compiler/ets/typealias_conflict_with_builtin.ets b/ets2panda/test/ast/compiler/ets/typealias_conflict_with_builtin.ets new file mode 100644 index 0000000000..80fc58e641 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/typealias_conflict_with_builtin.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. + */ + +type Type = int; + +/* @@? 1:3 Error TypeError: Class 'Type' is already defined with different type. */ -- Gitee From ba3ccaa19b28232b2069e04ba7affa346b719b08 Mon Sep 17 00:00:00 2001 From: "584648456@qq.com" <584648456@qq.com> Date: Sat, 21 Jun 2025 20:54:20 +0800 Subject: [PATCH 021/145] Title: Unresolved reference identifier Description(optional): Unresolved reference identifier Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHRTR Signed-off-by: semon <584648456@qq.com> --- ets2panda/checker/ETSAnalyzer.cpp | 3 +++ ets2panda/checker/ets/helpers.cpp | 3 +++ .../unresolved_reference_identifier/file1.ets | 27 +++++++++++++++++++ .../main_test.ets | 20 ++++++++++++++ 4 files changed, 53 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/unresolved_reference_identifier/file1.ets create mode 100644 ets2panda/test/ast/compiler/ets/unresolved_reference_identifier/main_test.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 2c0fd6a3fc..9d8896a13d 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -1680,6 +1680,9 @@ checker::Type *ETSAnalyzer::Check(ir::Identifier *expr) const auto *identType = TransformTypeForMethodReference(checker, expr, checker->ResolveIdentifier(expr)); + if (expr->TsType() != nullptr && expr->TsType()->IsTypeError()) { + return expr->TsType(); + } ES2PANDA_ASSERT(expr->Variable() != nullptr); if (expr->Parent() == nullptr || !expr->Parent()->IsAssignmentExpression() || expr != expr->Parent()->AsAssignmentExpression()->Left()) { diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index c799944902..d7dce10622 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -287,6 +287,9 @@ Type *ETSChecker::ResolveIdentifier(ir::Identifier *ident) if (resolved == nullptr) { resolved = ExtraCheckForResolvedError(ident); if (resolved == nullptr) { + if (VarBinder()->GetScope()->IsClassScope() && this->IsAnyError()) { + return ident->SetTsType(GlobalTypeError()); + } auto [decl, var] = VarBinder()->NewVarDecl( ident->Start(), !ident->IsErrorPlaceHolder() ? ident->Name() : compiler::GenName(ProgramAllocator()).View()); diff --git a/ets2panda/test/ast/compiler/ets/unresolved_reference_identifier/file1.ets b/ets2panda/test/ast/compiler/ets/unresolved_reference_identifier/file1.ets new file mode 100644 index 0000000000..3267724fdd --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/unresolved_reference_identifier/file1.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. + */ + + +export function atomicTask() { + const buffer = new ArrayBuffer(4); + const sharedArray = new Int32Array() + for (let i = 0; i < 10; i++) { + Atomics.add(shareArray, 0, 1); + } + return Atomics.load(shareArray, 0); +} + +/* @@? 21:17 Error TypeError: Unresolved reference shareArray */ +/* @@? 23:12 Error TypeError: Call to `load` is ambiguous as `2` versions of `load` are available: `load(typedArray: BigInt64Array, index: double): BigInt` and `load(typedArray: BigUint64Array, index: double): BigInt` */ diff --git a/ets2panda/test/ast/compiler/ets/unresolved_reference_identifier/main_test.ets b/ets2panda/test/ast/compiler/ets/unresolved_reference_identifier/main_test.ets new file mode 100644 index 0000000000..2c13d474c1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/unresolved_reference_identifier/main_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 {atomicTask} from "./file1" +const task = new taskpool.Task(atomicTask); + +/* @@? file1.ets:23:12 Error TypeError: Call to `load` is ambiguous as `2` versions of `load` are available: `load(typedArray: BigInt64Array, index: double): BigInt` and `load(typedArray: BigUint64Array, index: double): BigInt` */ +/* @@? file1.ets:23:25 Error TypeError: Unresolved reference shareArray */ -- Gitee From 84877b7706733a57230ade0edb66fc99a3b8ce4f Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Mon, 23 Jun 2025 15:29:46 +0800 Subject: [PATCH 022/145] 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 0603, 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 | 25 ++++++++++++++--- .../ets/topLevelStmts/globalClassHandler.h | 1 + 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 | 27 +++++++++++++++++++ .../compiler/ets/invalid_namespace_neg2.ets | 22 +++++++++++++++ 11 files changed, 122 insertions(+), 10 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 a914f8ad66..9370597459 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp @@ -189,6 +189,23 @@ ArenaVector GlobalClassHandler::TransformNamespaces(Aren return classDecls; } +void GlobalClassHandler::TransformBrokenNamespace(ir::AstNode *node, parser::Program *program) +{ + node->TransformChildrenRecursively( + // clang-format off + // CC-OFFNXT(G.FMT.14-CPP) project code style + [this, &program](ir::AstNode *child) -> ir::AstNode* { + if (child->IsETSModule() && child->AsETSModule()->IsNamespace()) { + auto res = TransformNamespace(child->AsETSModule(), program); + res->SetParent(child->Parent()); + return res; + } + return child; + }, + // clang-format on + "TransformBrokenNamespace"); +} + ir::ClassDeclaration *GlobalClassHandler::TransformNamespace(ir::ETSModule *ns, parser::Program *program) { ir::ClassDeclaration *const globalDecl = CreateTransformedClass(ns); @@ -312,7 +329,6 @@ void GlobalClassHandler::SetupGlobalClass(const ArenaVector & CollectProgramGlobalClasses(globalProgram, namespaces); auto initializerBlockStmts = FormInitStaticBlockMethodStatements(globalProgram, moduleDependencies, std::move(initializerBlock)); - CollectExportedClasses(globalClass, globalProgram->Ast()->Statements()); // NOTE(vpukhov): stdlib checks are to be removed - do not extend the existing logic @@ -423,11 +439,12 @@ ArenaVector GlobalClassHandler::FormInitMethodStatements(parser FormDependentInitTriggers(statements, moduleDependencies); } for (const auto &[p, ps] : initStatements) { + for (auto st : ps) { + TransformBrokenNamespace(st, p); + st->SetParent(nullptr); + } 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 ae589327d1..fc726e8dd6 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h @@ -76,6 +76,7 @@ private: ArenaVector> FormInitStaticBlockMethodStatements( parser::Program *program, const ModuleDependencies *moduleDependencies, ArenaVector &&initStatements); + void TransformBrokenNamespace(ir::AstNode *node, parser::Program *program); ArenaVector FormInitMethodStatements(parser::Program *program, const ModuleDependencies *moduleDependencies, diff --git a/ets2panda/parser/ETSFormattedParser.cpp b/ets2panda/parser/ETSFormattedParser.cpp index 93fac4b3e5..4be9f1d50c 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 6c905bafe6..f038afa6f2 100644 --- a/ets2panda/parser/ETSparser.h +++ b/ets2panda/parser/ETSparser.h @@ -390,7 +390,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 ea4a8feb4b..53e582726f 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 8e8d168f73..85634a4e63 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -166,7 +166,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]]; } @@ -221,6 +221,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..8b71c849f8 --- /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 'end of stream'. */ +/* @@? 21:93 Error SyntaxError: Unexpected token 'end of stream'. */ +/* @@? 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..2f3707f2ac --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/invalid_namespace_neg.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. + */ + +namespace C{ + { + let y: number = + /* @@ label1 */} + + namespace C { + let xsx = 1 + } +} + +/* @@@ label1 Error SyntaxError: Unexpected token '}'. */ +/* @@? 28:1 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 4d6b1421ce473dbd5e4fb9beeaa310c00096e331 Mon Sep 17 00:00:00 2001 From: ertugrulfarukpiskin Date: Tue, 24 Jun 2025 11:24:16 +0300 Subject: [PATCH 023/145] Assertion Fails on import Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGUIM Description: Assert fail on scoped import Signed-off-by: ertugrulfarukpiskin --- .../import_within_scope/export_file.ets | 16 ++++++++++++++ .../import_within_scope/scope_import_1.ets | 21 ++++++++++++++++++ .../import_within_scope/scope_import_2.ets | 22 +++++++++++++++++++ .../import_within_scope/scope_import_3.ets | 22 +++++++++++++++++++ ets2panda/varbinder/scope.cpp | 4 ++++ 5 files changed, 85 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/export_file.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_3.ets diff --git a/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/export_file.ets b/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/export_file.ets new file mode 100644 index 0000000000..e5c45ec62b --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/export_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 class Host {} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_1.ets b/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_1.ets new file mode 100644 index 0000000000..f6843e6780 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_1.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 ns { + import * as nsi from './export_file'; +} + +/* @@? 17:5 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ +/* @@? 17:12 Error TypeError: Variable 'nsi' has already been declared. */ diff --git a/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_2.ets b/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_2.ets new file mode 100644 index 0000000000..e5dbc4c1f5 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_2.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 main() { + { + import * as sci from './export_file'; + } +} + +/* @@? 18:9 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ diff --git a/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_3.ets b/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_3.ets new file mode 100644 index 0000000000..b57db80392 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_tests/import_within_scope/scope_import_3.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 main() { + if (true) { + import * as ici from './export_file'; + } +} + +/* @@? 18:9 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ \ No newline at end of file diff --git a/ets2panda/varbinder/scope.cpp b/ets2panda/varbinder/scope.cpp index ed4d78ebdb..fb13142b90 100644 --- a/ets2panda/varbinder/scope.cpp +++ b/ets2panda/varbinder/scope.cpp @@ -866,6 +866,10 @@ Variable *ClassScope::FindLocal(const util::StringView &name, ResolveBindingOpti void ClassScope::SetBindingProps(Decl *newDecl, BindingProps *props, bool isStatic) { + if (newDecl->IsImportDecl()) { + return; + } + switch (newDecl->Type()) { case DeclType::CONST: [[fallthrough]]; -- Gitee From 9ac5c7f1d487f8c83a18ba4dc5556dd8817fb02a Mon Sep 17 00:00:00 2001 From: fcc Date: Tue, 24 Jun 2025 16:24:45 +0800 Subject: [PATCH 024/145] fix crash related to rest parameter Avoid crash related to rest parameter. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICFY21 Signed-off-by: fcc --- ets2panda/checker/ets/function.cpp | 7 +++--- .../ast/compiler/ets/restvar_type_infer.ets | 22 +++++++++++++++++++ .../annotationUsage_bad_param07.ets | 1 + 3 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/restvar_type_infer.ets diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 167f9e40b2..b725bc4de3 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1377,10 +1377,6 @@ static varbinder::LocalVariable *SetupSignatureParameter(ir::ETSParameterExpress // Should be moved to original ComposeSignatureInfo after AST fix static bool AppendSignatureInfoParam(ETSChecker *checker, SignatureInfo *sigInfo, ir::ETSParameterExpression *param) { - if (param->IsRestParameter()) { - return true; - } - auto variable = SetupSignatureParameter(param, [checker, param]() { if (param->TypeAnnotation() != nullptr) { auto type = param->TypeAnnotation()->GetType(checker); @@ -1399,6 +1395,9 @@ static bool AppendSignatureInfoParam(ETSChecker *checker, SignatureInfo *sigInfo if (variable == nullptr) { // #23134 return false; } + if (param->IsRestParameter()) { + return true; + } sigInfo->params.push_back(variable); if (!param->IsOptional()) { diff --git a/ets2panda/test/ast/compiler/ets/restvar_type_infer.ets b/ets2panda/test/ast/compiler/ets/restvar_type_infer.ets new file mode 100644 index 0000000000..578567a54a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/restvar_type_infer.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 main() { + let r1 = ((...args) =>{ return args.length; })(1,2,3); + let r2 = ((a:number, ...args)=> { return args.length; })(1,2,3,4,5) +} + +/* @@? 17:16 Error TypeError: The type of parameter 'args' cannot be inferred */ +/* @@? 18:26 Error TypeError: The type of parameter 'args' cannot be inferred */ diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets index c1e3d6541e..93b781dc7b 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets @@ -23,3 +23,4 @@ function foo(@MyAnno ...a/* @@ label */){} /* @@@ label Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 22:15 Error TypeError: The required field 'testProperty1' must be specified. Fields without default values cannot be omitted. */ +/* @@? 22:22 Error TypeError: The type of parameter 'a' cannot be inferred */ -- Gitee From 13cab0e0cceaf931ae012df8738f199e1e80341b Mon Sep 17 00:00:00 2001 From: oh_ci Date: Fri, 27 Jun 2025 09:37:50 +0000 Subject: [PATCH 025/145] 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 672cb47d20..88f741c618 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -109,7 +109,7 @@ debug模式: **Email:** chenqiuyao@huawei.com -### L0新增用例自检结果 -- [ ] 是,有新增L0用例,且完成自检 -- [ ] 否 +### 是否已执行L0用例 +- [ ] 已验证 +- [ ] 不涉及。如不涉及,请写明理由 -- Gitee From 1d4b9d641b1895d7ab9661c322787765c25f9af3 Mon Sep 17 00:00:00 2001 From: gizembusraturan Date: Wed, 25 Jun 2025 08:43:14 +0300 Subject: [PATCH 026/145] Title: union type crash Issue: ICG6QA Testing: Build Signed-off-by: gizembusraturan --- ets2panda/checker/ETSAnalyzer.cpp | 4 +- ets2panda/checker/types/ets/etsUnionType.cpp | 1 + ets2panda/ir/statements/forOfStatement.cpp | 16 +++--- .../forof_iterator_doesnt_return_iteartor.ets | 54 +++++++++++++++++++ .../ets/forof_iterator_missing_next.ets | 40 ++++++++++++++ .../ets/forof_missing_iterator_method.ets | 31 +++++++++++ ...forof_missing_iterator_method_with_sig.ets | 37 +++++++++++++ .../ast/compiler/ets/forof_prop_is_static.ets | 47 ++++++++++++++++ .../ast/compiler/ets/union_types_forof_1.ets | 34 ++++++++++++ 9 files changed, 254 insertions(+), 10 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/forof_iterator_doesnt_return_iteartor.ets create mode 100644 ets2panda/test/ast/compiler/ets/forof_iterator_missing_next.ets create mode 100644 ets2panda/test/ast/compiler/ets/forof_missing_iterator_method.ets create mode 100644 ets2panda/test/ast/compiler/ets/forof_missing_iterator_method_with_sig.ets create mode 100644 ets2panda/test/ast/compiler/ets/forof_prop_is_static.ets create mode 100644 ets2panda/test/ast/compiler/ets/union_types_forof_1.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 2c0fd6a3fc..86485d23f6 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -2980,7 +2980,7 @@ checker::Type *ETSAnalyzer::Check(ir::ForOfStatement *const st) const return checker->GlobalTypeError(); } - checker::Type *elemType = nullptr; + checker::Type *elemType = checker->GlobalTypeError(); if (exprType->IsETSStringType()) { elemType = checker->GetGlobalTypesHolder()->GlobalCharType(); @@ -2990,7 +2990,7 @@ checker::Type *ETSAnalyzer::Check(ir::ForOfStatement *const st) const elemType = st->CheckIteratorMethod(checker); } - if (elemType == nullptr) { + if (elemType == checker->GlobalTypeError()) { checker->LogError(diagnostic::FOROF_SOURCE_NONITERABLE, {}, st->Right()->Start()); return checker->GlobalTypeError(); } diff --git a/ets2panda/checker/types/ets/etsUnionType.cpp b/ets2panda/checker/types/ets/etsUnionType.cpp index 2bbdf54442..7893a517a9 100644 --- a/ets2panda/checker/types/ets/etsUnionType.cpp +++ b/ets2panda/checker/types/ets/etsUnionType.cpp @@ -265,6 +265,7 @@ void ETSUnionType::LinearizeAndEraseIdentical(TypeRelation *relation, ArenaVecto size_t const initialSz = types.size(); for (size_t i = 0; i < initialSz; ++i) { auto ct = types[i]; + ES2PANDA_ASSERT(ct != nullptr); if (ct->IsETSUnionType()) { auto const &otherTypes = ct->AsETSUnionType()->ConstituentTypes(); types.insert(types.end(), otherTypes.begin(), otherTypes.end()); diff --git a/ets2panda/ir/statements/forOfStatement.cpp b/ets2panda/ir/statements/forOfStatement.cpp index 31198b09a9..d6eee195c8 100644 --- a/ets2panda/ir/statements/forOfStatement.cpp +++ b/ets2panda/ir/statements/forOfStatement.cpp @@ -35,7 +35,7 @@ checker::Type *ForOfStatement::CreateUnionIteratorTypes(checker::ETSChecker *che checker->GetGlobalTypesHolder())); types.back()->RemoveTypeFlag(checker::TypeFlag::CONSTANT); } else { - return nullptr; + return checker->GlobalTypeError(); } } @@ -158,7 +158,7 @@ checker::Type *ForOfStatement::CheckIteratorMethodForObject(checker::ETSChecker auto *const method = sourceType->GetProperty(compiler::Signatures::ITERATOR_METHOD, searchFlag); if (method == nullptr || !method->HasFlag(varbinder::VariableFlags::METHOD)) { checker->LogError(diagnostic::MISSING_ITERATOR_METHOD, {}, position); - return nullptr; + return checker->GlobalTypeError(); } ArenaVector arguments {checker->Allocator()->Adapter()}; @@ -167,27 +167,27 @@ checker::Type *ForOfStatement::CheckIteratorMethodForObject(checker::ETSChecker checker::TypeRelationFlag::NO_THROW); if (signature == nullptr) { checker->LogError(diagnostic::MISSING_ITERATOR_METHOD_WITH_SIG, {}, position); - return nullptr; + return checker->GlobalTypeError(); } checker->ValidateSignatureAccessibility(sourceType, signature, position, {{diagnostic::INVISIBLE_ITERATOR, {}}}); ES2PANDA_ASSERT(signature->Function() != nullptr); if (!CheckReturnTypeOfIteratorMethod(checker, sourceType, signature, position)) { - return nullptr; + return checker->GlobalTypeError(); } if (checker->IsClassStaticMethod(sourceType, signature)) { checker->LogError(diagnostic::PROP_IS_STATIC, {compiler::Signatures::ITERATOR_METHOD, sourceType->Name()}, position); - return nullptr; + return checker->GlobalTypeError(); } auto *const nextMethod = signature->ReturnType()->AsETSObjectType()->GetProperty(ITERATOR_INTERFACE_METHOD, searchFlag); if (nextMethod == nullptr || !nextMethod->HasFlag(varbinder::VariableFlags::METHOD)) { checker->LogError(diagnostic::ITERATOR_MISSING_NEXT, {}, position); - return nullptr; + return checker->GlobalTypeError(); } auto &nextSignatures = checker->GetTypeOfVariable(nextMethod)->AsETSFunctionType()->CallSignatures(); @@ -200,7 +200,7 @@ checker::Type *ForOfStatement::CheckIteratorMethodForObject(checker::ETSChecker } } - return nullptr; + return checker->GlobalTypeError(); } bool ForOfStatement::CheckReturnTypeOfIteratorMethod(checker::ETSChecker *checker, checker::ETSObjectType *sourceType, @@ -251,6 +251,6 @@ checker::Type *ForOfStatement::CheckIteratorMethod(checker::ETSChecker *const ch } } - return nullptr; + return checker->GlobalTypeError(); } } // namespace ark::es2panda::ir diff --git a/ets2panda/test/ast/compiler/ets/forof_iterator_doesnt_return_iteartor.ets b/ets2panda/test/ast/compiler/ets/forof_iterator_doesnt_return_iteartor.ets new file mode 100644 index 0000000000..e340e0579b --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/forof_iterator_doesnt_return_iteartor.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. + */ + +class A { + data: FixedArray = [1,2,3]; + $_iterator() : CIterator | undefined { + return new CIterator(this); + } +} + +class CIterator implements Iterator { + index = 0; + base: A; + constructor (base: A) { + this.base = base; + } + next(): IteratorResult { + if (this.index >= this.base.data.length) { + return { + done: true, + value: undefined + } + } + return { + done: this.index >= this.base.data.length, + value: this.base.data[this.index++] + } + } +} + +function main(): void { + let res = 0; + let a = new A(); + for (let x of a) res += x; + arktest.assertEQ(res, 6); +} + + +/* @@? 18:15 Error TypeError: The return type of '$_iterator' must be a type that implements Iterator interface.*/ +/* @@? 46:19 Error TypeError: Iterator method must return an object which implements Iterator */ +/* @@? 46:19 Error TypeError: 'For-of' statement source expression is not of iterable type. */ + diff --git a/ets2panda/test/ast/compiler/ets/forof_iterator_missing_next.ets b/ets2panda/test/ast/compiler/ets/forof_iterator_missing_next.ets new file mode 100644 index 0000000000..f513a77c6e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/forof_iterator_missing_next.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 { + data: FixedArray = [1,2,3]; + $_iterator() : CIterator | undefined { + return new CIterator(this); + } +} + +class CIterator { + index = 0; + base: A; + constructor (base: A) { + this.base = base; + } +} + +function main(): void { + let res = 0; + let a = new A(); + for (let x of a) res += x; + arktest.assertEQ(res, 6); +} + +/* @@? 18:15 Error TypeError: The return type of '$_iterator' must be a type that implements Iterator interface.*/ +/* @@? 34:19 Error TypeError: Iterator method must return an object which implements Iterator */ +/* @@? 34:19 Error TypeError: 'For-of' statement source expression is not of iterable type. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/forof_missing_iterator_method.ets b/ets2panda/test/ast/compiler/ets/forof_missing_iterator_method.ets new file mode 100644 index 0000000000..8952030938 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/forof_missing_iterator_method.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 C { + index = 0 +} + +function main(): int { + let c = new C() + let res = '' + for (let x of c) { + res += x + } + if (res != '6') return 1 + return 0 +} + +/* @@? 23:17 Error TypeError: Object type doesn't have proper iterator method. */ +/* @@? 23:17 Error TypeError: 'For-of' statement source expression is not of iterable type. */ diff --git a/ets2panda/test/ast/compiler/ets/forof_missing_iterator_method_with_sig.ets b/ets2panda/test/ast/compiler/ets/forof_missing_iterator_method_with_sig.ets new file mode 100644 index 0000000000..0adcb03bf1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/forof_missing_iterator_method_with_sig.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 C { + $_iterator(param: int): string { + return "notAnIterator"; + } +} + +function main(): int { + let c = new C(); + let res = ""; + + for (let x of c) { + res += x; + } + + if (res != "6") return 1; + return 0; +} + +/* @@? 17:3 Error SyntaxError: The special predefined method '$_iterator' should not have parameters. */ +/* @@? 17:13 Error TypeError: The return type of '$_iterator' must be a type that implements Iterator interface. */ +/* @@? 26:17 Error TypeError: Cannot find iterator method with the required signature. */ +/* @@? 26:17 Error TypeError: 'For-of' statement source expression is not of iterable type. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/forof_prop_is_static.ets b/ets2panda/test/ast/compiler/ets/forof_prop_is_static.ets new file mode 100644 index 0000000000..ff9986cb41 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/forof_prop_is_static.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. + */ + +class C { + data: int[] = [1,2,3] + static $_iterator() { + return new CIterator(new C()) + } +} +class CIterator implements Iterator { + index = 0 + base: C + constructor (base: C) { + this.base = base + } + next(): IteratorResult { + return { + done: this.index >= this.base.data.length, + value: this.index >= this.base.data.length ? undefined : this.base.data[this.index++] + } + } +} + +function main(): int { + let c = new C() + let res = '' + for (let x of c) { + res += x + } + if (res != '6') return 1 + return 0 +} + +/* @@? 39:17 Error TypeError: '$_iterator' is a static property of 'C' */ +/* @@? 39:17 Error TypeError: 'For-of' statement source expression is not of iterable type. */ diff --git a/ets2panda/test/ast/compiler/ets/union_types_forof_1.ets b/ets2panda/test/ast/compiler/ets/union_types_forof_1.ets new file mode 100644 index 0000000000..b13724b2d1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_types_forof_1.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. + */ + +function processValue(value: string | number): void { + if (typeof value === 'string') { + // Handle string case + for (const it of value) { + console.log(it); + } + } else { + // Handle number case + console.log(value.toString()); + } +} + +const testValues: (string | number)[] = ['hello', 42, 'world', 7]; + +for (const item of testValues) { + processValue(item); +} + +/* @@? 19:26 Error TypeError: Object type doesn't have proper iterator method. */ -- Gitee From a7ada651ecd1522ca310393ce01dec9120b0fb35 Mon Sep 17 00:00:00 2001 From: fcc Date: Wed, 11 Jun 2025 11:46:25 +0800 Subject: [PATCH 027/145] fix return object literal as Promise type When function signature requires a Promise of interface as return type, and it actually returns object literal, there should be no CTE. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICE95T Signed-off-by: fcc --- ets2panda/checker/ETSAnalyzer.cpp | 5 +++ .../compiler/lowering/ets/recordLowering.cpp | 4 ++ .../ets/objectLiteral_promise_interface.ets | 45 +++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 ets2panda/test/runtime/ets/objectLiteral_promise_interface.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 97bbfddfb7..909ef18421 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -2220,6 +2220,10 @@ static checker::ETSObjectType *ResolveObjectTypeFromPreferredType(ETSChecker *ch // Assume not null, checked by caller in Check() checker::Type *preferredType = expr->PreferredType(); + if (preferredType->IsETSAsyncFuncReturnType()) { + preferredType = preferredType->AsETSAsyncFuncReturnType()->GetPromiseTypeArg(); + } + if (preferredType->IsETSUnionType()) { return ResolveUnionObjectTypeForObjectLiteral(checker, expr, preferredType->AsETSUnionType()); } @@ -2354,6 +2358,7 @@ void ETSAnalyzer::CheckObjectExprProps(const ir::ObjectExpression *expr, } ETSChecker::SetPreferredTypeIfPossible(value, propType); + propExpr->SetTsType(propType); key->SetTsType(propType); value->SetTsType(value->Check(checker)); diff --git a/ets2panda/compiler/lowering/ets/recordLowering.cpp b/ets2panda/compiler/lowering/ets/recordLowering.cpp index 8897cd7ddb..5522c4a3f6 100644 --- a/ets2panda/compiler/lowering/ets/recordLowering.cpp +++ b/ets2panda/compiler/lowering/ets/recordLowering.cpp @@ -16,6 +16,7 @@ #include "recordLowering.h" #include "checker/ETSchecker.h" +#include "checker/types/ets/etsAsyncFuncReturnType.h" #include "compiler/lowering/scopesInit/scopesInitPhase.h" #include "compiler/lowering/util.h" @@ -155,6 +156,9 @@ ir::Statement *RecordLowering::CreateStatement(const std::string &src, ir::Expre ir::Expression *RecordLowering::UpdateObjectExpression(ir::ObjectExpression *expr, public_lib::Context *ctx) { auto checker = ctx->checker->AsETSChecker(); + if (expr->PreferredType()->IsETSAsyncFuncReturnType()) { + expr->SetPreferredType(expr->PreferredType()->AsETSAsyncFuncReturnType()->GetPromiseTypeArg()); + } if (!expr->PreferredType()->IsETSObjectType()) { // Unexpected preferred type diff --git a/ets2panda/test/runtime/ets/objectLiteral_promise_interface.ets b/ets2panda/test/runtime/ets/objectLiteral_promise_interface.ets new file mode 100644 index 0000000000..4ea3743c3d --- /dev/null +++ b/ets2panda/test/runtime/ets/objectLiteral_promise_interface.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. + */ + +interface Foo { + a: int +} + +async function foo1() : Promise { + return { a: 0 } +} + +async function foo2() : Promise> { + return { "b": 10 } +} + +async function foo3() : Promise> { + return { "c": 20 } +} + +async function startTest() { + let r1 = await foo1() + arktest.assertEQ(r1.a, 0) + + let r2 = await foo2() + arktest.assertEQ(r2["b"], 10) + + let r3 = await foo3() + arktest.assertEQ(r3.get("c"), 20) +} + +function main() { + startTest() +} \ No newline at end of file -- Gitee From d5dd1cee1849e7186416d1f9aa7bce1543f92848 Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Wed, 25 Jun 2025 21:03:25 +0800 Subject: [PATCH 028/145] Fix bugs from fuzzer Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIGQ2?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 aa9d61d049..64c9e8ffe5 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 ProgramAllocator()->New(std::numeric_limits::min()); + } + result = leftValue / rightValue; break; } diff --git a/ets2panda/parser/ETSparserAnnotations.cpp b/ets2panda/parser/ETSparserAnnotations.cpp index 25c6ec13c3..1f37cf4605 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..32781a0e03 --- /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 'end of stream'. */ diff --git a/ets2panda/test/runtime/ets/MaxBoundInt.ets b/ets2panda/test/runtime/ets/MaxBoundInt.ets new file mode 100644 index 0000000000..b03c7c4655 --- /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. + */ + +arktest.assertEQ(-2147483648 / -1, -2147483648) +arktest.assertEQ(-9223372036854775808 / -1, -9223372036854775808) -- Gitee From d97e7d3d5713656520051c593979654e761208d1 Mon Sep 17 00:00:00 2001 From: Janos Pantos Date: Wed, 25 Jun 2025 11:17:38 +0200 Subject: [PATCH 029/145] Fix invalid local enum declaration parsing Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHS52 Fixes internal issue #26725 Change-Id: Ibbdc4865693c5327bb46e3fba489a094e38990dc Signed-off-by: Janos Pantos --- ets2panda/parser/ETSparser.cpp | 3 +++ ets2panda/test/ast/parser/ets/local-enum.ets | 22 ++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 ets2panda/test/ast/parser/ets/local-enum.ets diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 8161f7438f..39c9f511e4 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -505,6 +505,9 @@ ir::AstNode *ETSParser::ParseInnerTypeDeclaration(ir::ModifierFlags memberModifi Lexer()->GetToken().SetTokenType(Lexer()->GetToken().KeywordType()); ir::AstNode *typeDecl = ParseTypeDeclaration(true); + if (typeDecl == nullptr) { + return nullptr; + } memberModifiers &= (ir::ModifierFlags::PUBLIC | ir::ModifierFlags::PROTECTED | ir::ModifierFlags::PRIVATE | ir::ModifierFlags::INTERNAL); typeDecl->AddModifier(memberModifiers); diff --git a/ets2panda/test/ast/parser/ets/local-enum.ets b/ets2panda/test/ast/parser/ets/local-enum.ets new file mode 100644 index 0000000000..2e3a21b49c --- /dev/null +++ b/ets2panda/test/ast/parser/ets/local-enum.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 A { + /* @@ label */enum E { + C + } +} + +/* @@@ label Error SyntaxError: Unexpected token. A constructor, method, accessor, or property was expected. */ -- Gitee From 443c558b9a891d53eb9744b410494cfad9e19e3f Mon Sep 17 00:00:00 2001 From: nikozer Date: Thu, 26 Jun 2025 23:40:03 +0300 Subject: [PATCH 030/145] fiix segv in alias types Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICI4X1 Tests: ets-runtime Signed-off-by: nikozer --- ets2panda/checker/ets/typeCheckingHelpers.cpp | 1 - .../checker/types/ets/etsTypeAliasType.cpp | 28 ------------------- .../checker/types/ets/etsTypeAliasType.h | 2 -- .../test/runtime/ets/RecursiveTypeAlias12.ets | 21 ++++++++++++++ .../ets-runtime/ets-runtime-ignored.txt | 3 ++ 5 files changed, 24 insertions(+), 31 deletions(-) create mode 100644 ets2panda/test/runtime/ets/RecursiveTypeAlias12.ets diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index ce9a69bfb6..2848d1fa2b 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -761,7 +761,6 @@ Type *ETSChecker::GetTypeFromTypeAliasReference(varbinder::Variable *var) aliasTypeNode->Check(this); Type *targetType = aliasTypeNode->TypeAnnotation()->GetType(this); typeAliasType->AsETSTypeAliasType()->SetTargetType(targetType); - typeAliasType->AsETSTypeAliasType()->ApplySubstitution(Relation()); var->SetTsType(targetType); return targetType; diff --git a/ets2panda/checker/types/ets/etsTypeAliasType.cpp b/ets2panda/checker/types/ets/etsTypeAliasType.cpp index 411b0bbe09..9b1578ba75 100644 --- a/ets2panda/checker/types/ets/etsTypeAliasType.cpp +++ b/ets2panda/checker/types/ets/etsTypeAliasType.cpp @@ -257,34 +257,6 @@ bool ETSTypeAliasType::SubstituteTypeArgs(TypeRelation *const relation, ArenaVec return anyChange; } -void ETSTypeAliasType::ApplySubstitution(TypeRelation *relation) -{ - ES2PANDA_ASSERT(base_ == nullptr); - - const util::StringView hash = relation->GetChecker()->AsETSChecker()->GetHashFromTypeArguments(typeArguments_); - EmplaceInstantiatedType(hash, this); - - auto getTypes = [this]() { - std::vector types; - - for (auto [name, type] : instantiationMap_) { - if (type->targetType_ == nullptr) { - types.push_back(type); - } - } - - return types; - }; - - std::vector types; - - while (!(types = getTypes(), types.empty())) { - for (auto type : types) { - type->SetTargetType(type->parent_->targetType_->Substitute(relation, type->substitution_)); - } - } -} - void ETSTypeAliasType::SetTypeArguments(ArenaVector typeArguments) { typeArguments_ = std::move(typeArguments); diff --git a/ets2panda/checker/types/ets/etsTypeAliasType.h b/ets2panda/checker/types/ets/etsTypeAliasType.h index a0811891f9..1f497bf669 100644 --- a/ets2panda/checker/types/ets/etsTypeAliasType.h +++ b/ets2panda/checker/types/ets/etsTypeAliasType.h @@ -87,8 +87,6 @@ public: Type *Substitute(TypeRelation *relation, const Substitution *substitution) override; - void ApplySubstitution(TypeRelation *relation); - void SetTypeArguments(ArenaVector typeArguments); private: diff --git a/ets2panda/test/runtime/ets/RecursiveTypeAlias12.ets b/ets2panda/test/runtime/ets/RecursiveTypeAlias12.ets new file mode 100644 index 0000000000..c09580617a --- /dev/null +++ b/ets2panda/test/runtime/ets/RecursiveTypeAlias12.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. + */ + +class A {} + +type M = A>; +type F = A>; + +let a = new M(); \ 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 bdff84c10b..2f2ad719d1 100644 --- a/ets2panda/test/test-lists/ets-runtime/ets-runtime-ignored.txt +++ b/ets2panda/test/test-lists/ets-runtime/ets-runtime-ignored.txt @@ -86,3 +86,6 @@ import_self_head_tests/B/test.d.ets #Issue 25550 enum-initialize-with-enum3.ets + +# 27159 Recursive type alias with generics +RecursiveTypeAlias10.ets -- Gitee From c35460e13728b576f2f7ff0d7b3d7b10cb42c082 Mon Sep 17 00:00:00 2001 From: Tatiana Titova Date: Fri, 27 Jun 2025 15:42:13 +0300 Subject: [PATCH 031/145] Fix id's type for nodes in a lambda's body Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIET3 Signed-off-by: Tatiana Titova --- ets2panda/compiler/core/ETSCompiler.cpp | 1 + .../compiler/lowering/ets/lambdaLowering.cpp | 1 + .../ets/LambdaParameterWithImplicitType.ets | 26 +++++++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/LambdaParameterWithImplicitType.ets diff --git a/ets2panda/compiler/core/ETSCompiler.cpp b/ets2panda/compiler/core/ETSCompiler.cpp index 86ee12f811..76dc7e8bdf 100644 --- a/ets2panda/compiler/core/ETSCompiler.cpp +++ b/ets2panda/compiler/core/ETSCompiler.cpp @@ -833,6 +833,7 @@ void ETSCompiler::Compile(const ir::Identifier *expr) const ETSGen *etsg = GetETSGen(); auto const *smartType = expr->TsType(); + ES2PANDA_ASSERT(smartType != nullptr); if (smartType->IsETSTypeParameter() || smartType->IsETSPartialTypeParameter() || smartType->IsETSNonNullishType()) { smartType = etsg->Checker()->GetApparentType(smartType); } diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index 15f279ea37..df7f1a1a0b 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -225,6 +225,7 @@ static void ProcessCalleeMethodBody(ir::AstNode *body, checker::ETSChecker *chec auto *id = node->AsIdentifier(); if (auto ref = varMap.find(id->Variable()); ref != varMap.end()) { id->SetVariable(ref->second); + id->Check(checker); } } if (substitution == nullptr) { diff --git a/ets2panda/test/ast/compiler/ets/LambdaParameterWithImplicitType.ets b/ets2panda/test/ast/compiler/ets/LambdaParameterWithImplicitType.ets new file mode 100644 index 0000000000..2cde0dd689 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/LambdaParameterWithImplicitType.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. + */ + +const foo = async (): Promise => { + return 42.0; // Return a double to satisfy the Promise +}; + +foo().then((result) => { // crash - issue #26815 + console.log(`Async function returned: ${result}`); +}); + +let fooArray = ["a", "b", "c"]; +let fooArrayMapped = fooArray.map(x => x + " is mapped"); // crash - issue #26856 +let fooArrayMappedAndChecked = fooArray.map(x => x == "a"); // crash - issue #26856 -- Gitee From 604a454764a4c713de2552bc55b9c8d610fa1022 Mon Sep 17 00:00:00 2001 From: huyunhui Date: Thu, 26 Jun 2025 16:12:10 +0800 Subject: [PATCH 032/145] Fix array expression assignment Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICI17Q Signed-off-by: huyunhui --- ets2panda/checker/ETSAnalyzer.cpp | 3 ++- .../parser/ets/array_literal_inference.ets | 20 +++++++++++++++++++ .../ast/parser/ets/tuple_trailing_comma.ets | 1 + 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/parser/ets/array_literal_inference.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index d39bb43ab9..9c5c1c1bdd 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -902,7 +902,8 @@ checker::Type *ETSAnalyzer::Check(ir::ArrayExpression *expr) const expr->SetPreferredType(InferPreferredTypeFromElements(checker, expr)); } - if (!CheckArrayExpressionElements(checker, expr)) { + if (!ValidArrayExprSizeForTupleSize(checker, expr->GetPreferredType(), expr) || + !CheckArrayExpressionElements(checker, expr)) { return checker->InvalidateType(expr); } } diff --git a/ets2panda/test/ast/parser/ets/array_literal_inference.ets b/ets2panda/test/ast/parser/ets/array_literal_inference.ets new file mode 100644 index 0000000000..9ab410b887 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/array_literal_inference.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 foo(): void { + let b: [] = /* @@ label */[ 1 ] +} + +/* @@@ label Error TypeError: Initializer has 1 elements, but tuple requires 0 */ \ No newline at end of file diff --git a/ets2panda/test/ast/parser/ets/tuple_trailing_comma.ets b/ets2panda/test/ast/parser/ets/tuple_trailing_comma.ets index 093fa956be..7cfc6830a2 100644 --- a/ets2panda/test/ast/parser/ets/tuple_trailing_comma.ets +++ b/ets2panda/test/ast/parser/ets/tuple_trailing_comma.ets @@ -28,3 +28,4 @@ let b: [number, /* @@ label */,number, number,] = [1, 2, 3,]; /* @@? 17:34 Error SyntaxError: Unexpected token ','. */ /* @@? 17:35 Error SyntaxError: Unexpected token ']'. */ /* @@@ label Error SyntaxError: Invalid Type. */ +/* @@? 18:51 Error TypeError: Initializer has 3 elements, but tuple requires 4 */ -- Gitee From c9ea1fe1c076d5e781ae5afdeaad0399c602fbf3 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Tue, 24 Jun 2025 16:38:56 +0800 Subject: [PATCH 033/145] Fixed type alias with default typeParam bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHGPX?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ets/helpers.cpp | 29 +++++++++------ ets2panda/checker/ets/validateHelpers.cpp | 2 +- .../compiler/ets/generic_typealias_2_neg.ets | 4 +-- .../ets/typealias_default_type_01.ets | 26 ++++++++++++++ .../ets/typealias_default_type_02.ets | 36 +++++++++++++++++++ .../runtime/ets/typealias_default_type.ets | 31 ++++++++++++++++ ets2panda/util/diagnostic/semantic.yaml | 2 +- 7 files changed, 115 insertions(+), 15 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/typealias_default_type_01.ets create mode 100644 ets2panda/test/ast/compiler/ets/typealias_default_type_02.ets create mode 100644 ets2panda/test/runtime/ets/typealias_default_type.ets diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index a9b83658ec..d3ade50666 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -1564,7 +1564,7 @@ bool ETSChecker::CheckMinimumTypeArgsPresent(const ir::TSTypeAliasDeclaration *t ir::TypeNode *ETSChecker::ResolveTypeNodeForTypeArg(const ir::TSTypeAliasDeclaration *typeAliasNode, const ir::TSTypeParameterInstantiation *typeParams, size_t idx) { - if (typeParams->Params().size() > idx) { + if (typeParams != nullptr && typeParams->Params().size() > idx) { return typeParams->Params().at(idx); } @@ -1574,34 +1574,41 @@ ir::TypeNode *ETSChecker::ResolveTypeNodeForTypeArg(const ir::TSTypeAliasDeclara Type *ETSChecker::HandleTypeAlias(ir::Expression *const name, const ir::TSTypeParameterInstantiation *const typeParams, ir::TSTypeAliasDeclaration *const typeAliasNode) { - // NOTE (mmartin): modify for default params - if ((typeParams == nullptr) != (typeAliasNode->TypeParams() == nullptr)) { - if (typeParams == nullptr) { + if (typeParams == nullptr && typeAliasNode->TypeParams() != nullptr) { + auto declTypeParams = typeAliasNode->TypeParams()->Params(); + auto isAllTypeParamsHasDefaultType = + std::find_if(declTypeParams.begin(), declTypeParams.end(), [](ir::TSTypeParameter *param) { + return param->DefaultType() == nullptr; + }) == declTypeParams.end(); + if (!isAllTypeParamsHasDefaultType) { LogError(diagnostic::GENERIC_ALIAS_WITHOUT_PARAMS, {}, name->Start()); return GlobalTypeError(); } + } + if (typeParams != nullptr && typeAliasNode->TypeParams() == nullptr) { LogError(diagnostic::NON_GENERIC_ALIAS_WITH_PARAMS, {}, typeParams->Start()); return GlobalTypeError(); } - if (typeParams == nullptr) { + if (typeParams == nullptr && typeAliasNode->TypeParams() == nullptr) { // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) return GetReferencedTypeBase(name); } - for (auto *const origTypeParam : typeParams->Params()) { - origTypeParam->Check(this); + if (typeParams != nullptr) { + for (auto *const origTypeParam : typeParams->Params()) { + origTypeParam->Check(this); + } + if (CheckMinimumTypeArgsPresent(typeAliasNode, typeParams)) { + return GlobalTypeError(); + } } // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) Type *const aliasType = GetReferencedTypeBase(name); auto *substitution = NewSubstitution(); - if (CheckMinimumTypeArgsPresent(typeAliasNode, typeParams)) { - return GlobalTypeError(); - } - std::set parametersNeedToBeBoxed; auto expandedAliasType = aliasType->Substitute(Relation(), substitution); CollectAliasParametersForBoxing(expandedAliasType, parametersNeedToBeBoxed, false); diff --git a/ets2panda/checker/ets/validateHelpers.cpp b/ets2panda/checker/ets/validateHelpers.cpp index f3ad9a385b..babeed542d 100644 --- a/ets2panda/checker/ets/validateHelpers.cpp +++ b/ets2panda/checker/ets/validateHelpers.cpp @@ -279,7 +279,7 @@ void ETSChecker::ValidateGenericTypeAliasForClonedNode(ir::TSTypeAliasDeclaratio ir::TypeNode *typeParamType = nullptr; - if (exactTypeParams->Params().size() > typeParamIdx) { + if (exactTypeParams != nullptr && exactTypeParams->Params().size() > typeParamIdx) { typeParamType = exactTypeParams->Params().at(typeParamIdx); } else { typeParamType = typeAliasNode->TypeParams()->Params().at(typeParamIdx)->DefaultType(); diff --git a/ets2panda/test/ast/compiler/ets/generic_typealias_2_neg.ets b/ets2panda/test/ast/compiler/ets/generic_typealias_2_neg.ets index d8f74a0d2b..2ce7f0e30f 100644 --- a/ets2panda/test/ast/compiler/ets/generic_typealias_2_neg.ets +++ b/ets2panda/test/ast/compiler/ets/generic_typealias_2_neg.ets @@ -17,7 +17,7 @@ type my_type = T; function main(): void { - let a: /* @@ label */my_type = new Int(); + let a: my_type = new Int(); } -/* @@@ label Error TypeError: Type alias declaration is generic, but no type parameters were provided */ +/* @@? 20:12 Error TypeError: Type alias declaration is generic, but too few type arguments were provided */ diff --git a/ets2panda/test/ast/compiler/ets/typealias_default_type_01.ets b/ets2panda/test/ast/compiler/ets/typealias_default_type_01.ets new file mode 100644 index 0000000000..b7051016a8 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/typealias_default_type_01.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. + */ + +type ErrorCallBack1 = (err: T) => void + +type ErrorCallBack2 = (err: T) => void + +function test1(call: ErrorCallBack1) { } // should be ok + +function test2(call: ErrorCallBack2) { } // should be error because typeParam has no default type + +function test3(call: ErrorCallBack2) { } // should be ok because we have explicitly provided a type. + +/* @@? 22:22 Error TypeError: Type alias declaration is generic, but too few type arguments were provided */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/typealias_default_type_02.ets b/ets2panda/test/ast/compiler/ets/typealias_default_type_02.ets new file mode 100644 index 0000000000..9f91a1fe20 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/typealias_default_type_02.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. + */ + +type ErrorCallBack1 = (err: T) => R + +type ErrorCallBack2 = (err: T) => R + +type ErrorCallBack3 = (err: T) => R + +function test1(call: ErrorCallBack1) { } // should be ok + +function test2(call: ErrorCallBack2) { } // should be error because typeParam has no default type + +function test3(call: ErrorCallBack2) { } // should be error because we have not provided all types. + +function test4(call: ErrorCallBack2) { } // should be ok because we have provided all types. + +function test5(call: ErrorCallBack3) { } // should be ok because the second type param has a default type + +function test6(call: ErrorCallBack3) { } // should be error + +/* @@? 24:22 Error TypeError: Type alias declaration is generic, but too few type arguments were provided */ +/* @@? 26:36 Error TypeError: Expected at least 2 type arguments, but got 1. */ +/* @@? 32:22 Error TypeError: Type alias declaration is generic, but too few type arguments were provided */ \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/typealias_default_type.ets b/ets2panda/test/runtime/ets/typealias_default_type.ets new file mode 100644 index 0000000000..5cbd994ced --- /dev/null +++ b/ets2panda/test/runtime/ets/typealias_default_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 BusinessError extends Error { + constructor(message?: String) { + super(message) + } +} + +type ErrorCallBack = (err: T) => void +function test(call: ErrorCallBack) { // type of typeAnnotation should be `(err: BusinessError) => void` + call(new BusinessError("I am a error")) +} + +function main() { + test((err: BusinessError) => { + arktest.assertEQ(err.message, "I am a error") + }) // ok +} diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index ba0191e4ad..d18d0d4971 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -629,7 +629,7 @@ semantic: - name: GENERIC_ALIAS_WITHOUT_PARAMS id: 155 - message: "Type alias declaration is generic, but no type parameters were provided" + message: "Type alias declaration is generic, but too few type arguments were provided" - name: NON_GENERIC_ALIAS_WITH_PARAMS id: 156 -- Gitee From d0bcfae8b9c8807dc530c4fae6b1675a8b461d1f Mon Sep 17 00:00:00 2001 From: abdulsamethaymana Date: Fri, 20 Jun 2025 14:33:56 +0300 Subject: [PATCH 034/145] Fix: readonly modifier for union types Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGR0I?from=project-issue Signed-off-by: abdulsamethaymana --- ets2panda/parser/ETSparserTypes.cpp | 46 ++++---- .../ets/readonly/label_readonly_true.ets | 2 - .../ets/readonly/readonly_static_var.ets | 1 - .../ets/readonlyFunctionTypeAnnotation.ets | 1 - .../parser/ets/readonly_union_negative.ets | 64 +++++++++++ .../runtime/ets/readonly_union_positive.ets | 107 ++++++++++++++++++ 6 files changed, 198 insertions(+), 23 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/readonly_union_negative.ets create mode 100644 ets2panda/test/runtime/ets/readonly_union_positive.ets diff --git a/ets2panda/parser/ETSparserTypes.cpp b/ets2panda/parser/ETSparserTypes.cpp index c88b813839..ba9bc16a21 100644 --- a/ets2panda/parser/ETSparserTypes.cpp +++ b/ets2panda/parser/ETSparserTypes.cpp @@ -488,11 +488,6 @@ ir::TypeNode *ETSParser::ParseTypeAnnotationNoPreferParam(TypeAnnotationParsingO typeAnnotation = ParseTsArrayType(typeAnnotation, options); - if (((*options) & TypeAnnotationParsingOptions::DISALLOW_UNION) == 0 && - Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_BITWISE_OR) { - ApplyAnnotationsToNode(typeAnnotation, std::move(annotations), startPos); - return ParseUnionType(typeAnnotation); - } ApplyAnnotationsToNode(typeAnnotation, std::move(annotations), startPos, *options); return typeAnnotation; } @@ -511,30 +506,43 @@ bool ETSParser::ParseReadonlyInTypeAnnotation() return false; } +static bool IsReadonlyApplicableType(ir::TypeNode *typeNode) +{ + return typeNode->IsTSArrayType() || typeNode->IsETSTuple() || + (typeNode->IsETSTypeReference() && + typeNode->AsETSTypeReference()->BaseName()->Name() == compiler::Signatures::ARRAY); +} + ir::TypeNode *ETSParser::ParseTypeAnnotation(TypeAnnotationParsingOptions *options) { 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)) { - return ParseTypeAnnotationNoPreferParam(options); - } + bool hasReadonly = Lexer()->TryEatTokenFromKeywordType(lexer::TokenType::KEYW_READONLY); const auto beforeTypeAnnotation = Lexer()->GetToken().Loc(); auto typeAnnotation = ParseTypeAnnotationNoPreferParam(options); if (typeAnnotation == nullptr) { - LogError(diagnostic::INVALID_TYPE); + if ((*options & TypeAnnotationParsingOptions::REPORT_ERROR) != 0) { + LogError(diagnostic::INVALID_TYPE); + } return AllocBrokenType(beforeTypeAnnotation); } - if (!typeAnnotation->IsTSArrayType() && !typeAnnotation->IsETSTuple() && - !(typeAnnotation->IsETSTypeReference() && - typeAnnotation->AsETSTypeReference()->BaseName()->Name() == compiler::Signatures::ARRAY)) { - if (!ParseReadonlyInTypeAnnotation()) { - LogError(diagnostic::READONLY_ONLY_ON_ARRAY_OR_TUPLE); - } else { - LogError(diagnostic::READONLY_TYPE_EXPECTED); + + if (hasReadonly) { + if (!IsReadonlyApplicableType(typeAnnotation)) { + if (!ParseReadonlyInTypeAnnotation()) { + LogError(diagnostic::READONLY_ONLY_ON_ARRAY_OR_TUPLE); + } else { + LogError(diagnostic::READONLY_TYPE_EXPECTED); + } } + typeAnnotation->SetStart(startPos); + typeAnnotation->AddModifier(ir::ModifierFlags::READONLY_PARAMETER); } - typeAnnotation->SetStart(startPos); - typeAnnotation->AddModifier(ir::ModifierFlags::READONLY_PARAMETER); + + if (((*options) & TypeAnnotationParsingOptions::DISALLOW_UNION) == 0 && + Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_BITWISE_OR) { + return ParseUnionType(typeAnnotation); + } + return typeAnnotation; } diff --git a/ets2panda/test/ast/compiler/ets/readonly/label_readonly_true.ets b/ets2panda/test/ast/compiler/ets/readonly/label_readonly_true.ets index e096cf9167..7a6e516d42 100644 --- a/ets2panda/test/ast/compiler/ets/readonly/label_readonly_true.ets +++ b/ets2panda/test/ast/compiler/ets/readonly/label_readonly_true.ets @@ -18,9 +18,7 @@ let: readonly; /* @@? 16:5 Error SyntaxError: Label must be followed by a loop statement. */ /* @@? 16:5 Error TypeError: Unresolved reference readonly */ -/* @@? 16:14 Error SyntaxError: Invalid Type. */ /* @@? 16:14 Error SyntaxError: Unexpected token 'true'. */ /* @@? 17:4 Error SyntaxError: Identifier expected, got ':'. */ /* @@? 17:6 Error SyntaxError: Variable must be initialized or it's type must be declared. */ /* @@? 17:6 Error SyntaxError: Unexpected token 'readonly'. */ -/* @@? 17:14 Error SyntaxError: Invalid Type. */ diff --git a/ets2panda/test/ast/compiler/ets/readonly/readonly_static_var.ets b/ets2panda/test/ast/compiler/ets/readonly/readonly_static_var.ets index b29d1d1ad6..46ad39e55c 100644 --- a/ets2panda/test/ast/compiler/ets/readonly/readonly_static_var.ets +++ b/ets2panda/test/ast/compiler/ets/readonly/readonly_static_var.ets @@ -16,7 +16,6 @@ readonly static S = c' '; /* @@? 16:1 Error TypeError: Unresolved reference readonly */ -/* @@? 16:10 Error SyntaxError: Invalid Type. */ /* @@? 16:10 Error SyntaxError: Unexpected token 'static'. */ /* @@? 16:17 Error SyntaxError: Unexpected token 'S'. */ /* @@? 16:17 Error TypeError: Unresolved reference S */ diff --git a/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets b/ets2panda/test/ast/parser/ets/readonlyFunctionTypeAnnotation.ets index e2fd0dddf4..686f313ee0 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:22 Error SyntaxError: Unexpected token 'object'. */ diff --git a/ets2panda/test/ast/parser/ets/readonly_union_negative.ets b/ets2panda/test/ast/parser/ets/readonly_union_negative.ets new file mode 100644 index 0000000000..afaff7a466 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/readonly_union_negative.ets @@ -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. + */ + +// Negative test cases for readonly union types - these should fail compilation + +// Error: readonly on a non-applicable primitive type in a union +function test_negative_1(param: readonly number | string): void { +} + +// Error: readonly on a non-applicable object type in a union +class MyObject {} +function test_negative_2(param: readonly MyObject | string): void { +} + +// Error: readonly on a non-applicable type, even if another member is applicable +function test_negative_5(param: readonly boolean | string[]): void { +} + +// Error: readonly on void type +function test_negative_6(param: readonly void | number): void { +} + +// Error: readonly on function type +function test_negative_7(param: readonly (() => void) | string): void { +} + +function main(): void { + // Function calls to trigger parsing of parameter types + test_negative_1(42, "test"); + test_negative_2(new MyObject(), "test"); + test_negative_5(true, ["test"]); + test_negative_6(undefined, 42); + test_negative_7(() => {}, "test"); +} + + +/* @@? 19:49 Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ +/* @@? 24:51 Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ +/* @@? 28:50 Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ +/* @@? 32:33 Error TypeError: 'void' used as type annotation. */ +/* @@? 32:47 Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ +/* @@? 36:55 Error SyntaxError: 'readonly' type modifier is only permitted on resizable array and tuple types. */ +/* @@? 41:5 Error TypeError: No matching call signature for test_negative_1(int, "test") */ +/* @@? 41:5 Error TypeError: Expected 1 arguments, got 2. */ +/* @@? 42:5 Error TypeError: Expected 1 arguments, got 2. */ +/* @@? 42:5 Error TypeError: No matching call signature for test_negative_2(MyObject, "test") */ +/* @@? 43:5 Error TypeError: Expected 1 arguments, got 2. */ +/* @@? 43:5 Error TypeError: No matching call signature for test_negative_5(boolean, Array) */ +/* @@? 44:5 Error TypeError: Expected 1 arguments, got 2. */ +/* @@? 44:5 Error TypeError: No matching call signature for test_negative_6(undefined, int) */ +/* @@? 45:5 Error TypeError: Expected 1 arguments, got 2. */ +/* @@? 45:5 Error TypeError: No matching call signature for test_negative_7(() => void, "test") */ \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/readonly_union_positive.ets b/ets2panda/test/runtime/ets/readonly_union_positive.ets new file mode 100644 index 0000000000..70b1f0498c --- /dev/null +++ b/ets2panda/test/runtime/ets/readonly_union_positive.ets @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 getTypeInfo(param: readonly number[] | string): string { + if (typeof param === "string") { + return "string"; + } else { + return "array"; + } +} + +function getTypeInfoGeneric(param: readonly Array | boolean): string { + if (typeof param === "boolean") { + return "boolean"; + } else { + return "generic_array"; + } +} + +function getMultiUnionType(param: readonly string[] | number | boolean): string { + if (typeof param === "boolean") { + return "boolean"; + } else if (typeof param === "number") { + return "number"; + } else { + return "readonly_string_array"; + } +} + +function getDoubleReadonlyArrays(param: readonly number[] | readonly string[]): string { + // Simple type check without complex operations + return "readonly_array"; +} + +function getTupleUnion(param: readonly [number, string] | boolean): string { + if (typeof param === "boolean") { + return "boolean"; + } else { + return "readonly_tuple"; + } +} + +function getReadonlyWithNull(param: readonly string[] | null): string { + if (param === null) { + return "null"; + } else { + return "readonly_string_array"; + } +} + +function main(): void { + // Test basic readonly union - the core fix + let result1 = getTypeInfo("hello"); + arktest.assertEQ(result1, "string"); + + let result2 = getTypeInfo([1, 2, 3] as readonly number[]); + arktest.assertEQ(result2, "array"); + + // Test readonly generic union + let result3 = getTypeInfoGeneric(true); + arktest.assertEQ(result3, "boolean"); + + let result4 = getTypeInfoGeneric([10, 20] as readonly Array); + arktest.assertEQ(result4, "generic_array"); + + let result5 = getMultiUnionType(true); + arktest.assertEQ(result5, "boolean"); + + let result6 = getMultiUnionType(42); + arktest.assertEQ(result6, "number"); + + let result7 = getMultiUnionType(["a", "b"] as readonly string[]); + arktest.assertEQ(result7, "readonly_string_array"); + + // Test readonly number[] | readonly string[] + let result8 = getDoubleReadonlyArrays([1, 2] as readonly number[]); + arktest.assertEQ(result8, "readonly_array"); + + let result9 = getDoubleReadonlyArrays(["x", "y"] as readonly string[]); + arktest.assertEQ(result9, "readonly_array"); + + // Test readonly tuple + let result10 = getTupleUnion(true); + arktest.assertEQ(result10, "boolean"); + + let result11 = getTupleUnion([42, "test"] as readonly [number, string]); + arktest.assertEQ(result11, "readonly_tuple"); + + // Test readonly with null + let result12 = getReadonlyWithNull(null); + arktest.assertEQ(result12, "null"); + + let result13 = getReadonlyWithNull(["test"] as readonly string[]); + arktest.assertEQ(result13, "readonly_string_array"); +} \ No newline at end of file -- Gitee From f5e42d4e3ddf52ab8e80454e0e29fd269daa7ce7 Mon Sep 17 00:00:00 2001 From: fanglou Date: Mon, 30 Jun 2025 11:28:22 +0800 Subject: [PATCH 035/145] sync 0328 to 0603 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICH8PP Signed-off-by: fanglou --- ets2panda/linter/.gitignore | 1 + .../arkanalyzer/config/arkanalyzer.json | 5 +- .../arkanalyzer/src/core/common/SdkUtils.ts | 13 +- .../checker/migration/CustomBuilderCheck.ts | 50 +- .../checker/migration/InteropAssignCheck.ts | 50 +- .../InteropDeprecatedBuiltInAPICheck.ts | 187 +- .../InteropDynamicObjectLiteralsCheck.ts | 66 +- .../InteropS2DObjectLiteralsCheck.ts | 6 + .../src/checker/migration/NoTSLikeAsCheck.ts | 228 +- .../checker/migration/ObjectLiteralCheck.ts | 21 +- .../migration/ObservedDecoratorCheck.ts | 26 +- .../homecheck/src/utils/common/CheckEntry.ts | 8 +- ets2panda/linter/package-lock.json | 5657 +++++++++++++++++ ets2panda/linter/package.json | 17 +- .../scripts/testRunner/coverage_collect.js | 147 + .../scripts/testRunner/coverage_prepare.js | 64 + .../scripts/testRunner/coverage_report.js | 56 + ets2panda/linter/src/cli/CommandLineParser.ts | 39 +- ets2panda/linter/src/cli/LinterCLI.ts | 182 +- .../linter/src/lib/BaseTypeScriptLinter.ts | 55 +- .../linter/src/lib/CommandLineOptions.ts | 3 +- ets2panda/linter/src/lib/CookBookMsg.ts | 9 +- ets2panda/linter/src/lib/FaultAttrs.ts | 4 +- ets2panda/linter/src/lib/FaultDesc.ts | 4 +- ets2panda/linter/src/lib/LintRunResult.ts | 2 + ets2panda/linter/src/lib/LinterOptions.ts | 4 + ets2panda/linter/src/lib/LinterRunner.ts | 55 +- ets2panda/linter/src/lib/Problems.ts | 4 +- ets2panda/linter/src/lib/TypeScriptLinter.ts | 911 ++- .../linter/src/lib/autofixes/AutofixTitles.ts | 3 +- .../linter/src/lib/autofixes/Autofixer.ts | 149 +- .../src/lib/statistics/scan/CountFile.ts | 216 + .../src/lib/statistics/scan/CountNapiFile.ts | 151 + .../statistics/scan/FloderScanResultInfo.ts | 25 + .../statistics/scan/NapiFileStatisticInfo.ts | 22 + .../lib/statistics/scan/ProblemNumbersInfo.ts | 22 + .../scan/ProblemStatisticsCommonFunction.ts | 232 + .../statistics/scan/ProblemStatisticsInfo.ts | 24 + .../statistics/scan/RuleDetailedErrorInfo.ts | 20 + .../statistics/scan/ScanTaskRelatedInfo.ts | 31 + .../scan/StatisticsReportInPutInfo.ts | 27 + .../src/lib/statistics/scan/TimeRecorder.ts | 54 + .../src/lib/statistics/scan/WorkLoadInfo.ts | 59 + ets2panda/linter/src/lib/utils/TsUtils.ts | 58 +- .../src/lib/utils/consts/ArkTS2Rules.ts | 20 +- .../src/lib/utils/consts/ArkuiConstants.ts | 3 +- .../src/lib/utils/consts/ArkuiImportList.ts | 53 + .../src/lib/utils/consts/AsyncLifecycleSDK.ts | 31 + .../linter/src/lib/utils/consts/ErrorProp.ts | 7 + .../linter/src/lib/utils/consts/InteropAPI.ts | 7 +- .../src/lib/utils/consts/LimitedStdAPI.ts | 3 + .../src/lib/utils/consts/MapKeyConst.ts | 28 + .../lib/utils/consts/WorkloadRelatedConst.ts | 20 + .../utils/functions/ConfiguredRulesProcess.ts | 68 + .../src/lib/utils/functions/CookBookUtils.ts | 35 + .../src/lib/utils/functions/ProcessWrite.ts | 30 + ets2panda/linter/src/testRunner/LintTest.ts | 14 +- ets2panda/linter/src/testRunner/TestRunner.ts | 15 + .../linter/test/builtin/builtin_thisArgs.ets | 10 +- ... no_support_arktsutils_locks_asynclock.ets | 20 + ...arktsutils_locks_asynclock.ets.arkts2.json | 38 + ...rktsutils_locks_asynclock.ets.autofix.json | 38 + ...upport_arktsutils_locks_asynclock.ets.json | 17 + ...arktsutils_locks_asynclock.ets.migrate.ets | 20 + ...rktsutils_locks_asynclock.ets.migrate.json | 38 + .../no_support_isconcurrent.ets.arkts2.json | 20 + .../no_support_isconcurrent2.ets.arkts2.json | 20 - .../binary_operation_js_obj.ets.autofix.json | 38 +- .../binary_operation_js_obj.ets.migrate.ets | 12 +- .../binary_operation_js_obj.ets.migrate.json | 10 +- .../call_object_methods.ets.autofix.json | 2 +- .../call_object_methods.ets.migrate.ets | 2 +- .../call_object_methods.ets.migrate.json | 2 +- .../test/interop/ignore_files/unique_types.ts | 223 +- ...ncreases_decreases_js_obj.ets.autofix.json | 36 +- ...increases_decreases_js_obj.ets.migrate.ets | 34 +- ...ncreases_decreases_js_obj.ets.migrate.json | 10 +- .../instantiated_js_obj.ets.autofix.json | 2 +- .../instantiated_js_obj.ets.migrate.ets | 4 +- .../instantiated_js_obj.ets.migrate.json | 4 +- .../test/interop/interop_convert_import.ets | 26 +- .../interop_convert_import.ets.arkts2.json | 84 +- .../interop_convert_import.ets.autofix.json | 230 +- .../interop/interop_convert_import.ets.json | 4 +- .../interop_convert_import.ets.migrate.ets | 50 +- .../interop_convert_import.ets.migrate.json | 44 +- ...interop_equality_judgment.ets.autofix.json | 2 +- .../interop_equality_judgment.ets.migrate.ets | 4 +- ...interop_equality_judgment.ets.migrate.json | 4 +- .../test/interop/interop_export_js_rules.ets | 4 - .../interop_export_js_rules.ets.arkts2.json | 144 +- .../interop_import_js.ets.autofix.json | 12 +- .../interop/interop_import_js.ets.migrate.ets | 22 +- .../interop_import_js.ets.migrate.json | 22 +- ...interop_import_js_compare.ets.autofix.json | 30 +- .../interop_import_js_compare.ets.migrate.ets | 12 +- ...interop_import_js_compare.ets.migrate.json | 10 +- .../interop_import_js_index.ets.autofix.json | 32 +- .../interop_import_js_index.ets.migrate.ets | 24 +- .../interop_import_js_index.ets.migrate.json | 10 +- .../interop_import_js_rules.ets.autofix.json | 42 +- .../interop_import_typeof_js.ets.autofix.json | 22 +- .../interop_import_typeof_js.ets.migrate.ets | 24 +- .../interop_import_typeof_js.ets.migrate.json | 18 +- ..._not_have_property_arkts2.ets.autofix.json | 32 +- ...p_not_have_property_arkts2.ets.migrate.ets | 28 +- ..._not_have_property_arkts2.ets.migrate.json | 14 +- ..._have_property_num_arkts2.ets.autofix.json | 34 +- ...t_have_property_num_arkts2.ets.migrate.ets | 18 +- ..._have_property_num_arkts2.ets.migrate.json | 14 +- .../no_await_js_promise.ets.autofix.json | 2 +- .../no_await_js_promise.ets.migrate.ets | 10 +- .../no_await_js_promise.ets.migrate.json | 10 +- .../interop/no_js_instanceof.ets.autofix.json | 8 +- .../interop/no_js_instanceof.ets.migrate.ets | 14 +- .../interop/no_js_instanceof.ets.migrate.json | 14 +- .../linter/test/interop/object_built_in.ets | 8 + .../interop/object_built_in.ets.arkts2.json | 14 +- .../test/interop/object_built_in.ets.json | 14 +- .../interop/reflect_built_in.ets.arkts2.json | 62 +- .../test/interop/reflect_built_in.ets.json | 62 +- .../unary_operation_js_obj.ets.autofix.json | 18 +- .../unary_operation_js_obj.ets.migrate.ets | 10 +- .../unary_operation_js_obj.ets.migrate.json | 8 +- .../linter/test/interop/unique_types.ets | 389 +- .../test/interop/unique_types.ets.arkts2.json | 530 +- .../interop/unique_types.ets.autofix.json | 608 +- .../linter/test/interop/unique_types.ets.json | 113 +- .../test/interop/unique_types.ets.migrate.ets | 389 +- .../interop/unique_types.ets.migrate.json | 468 +- ...atable_extend_decorator_1.ets.autofix.json | 16 +- ...matable_extend_decorator_1.ets.migrate.ets | 12 +- ...atable_extend_decorator_1.ets.migrate.json | 16 +- .../test/main/arkts-array-type-immutable.ets | 6 +- ...arkts-array-type-immutable.ets.arkts2.json | 30 + .../main/arkts_promise_need_void_resolve.ets | 17 + ...ts_promise_need_void_resolve.ets.args.json | 19 + ..._promise_need_void_resolve.ets.arkts2.json | 28 + .../arkts_promise_need_void_resolve.ets.json | 17 + .../test/main/avoid_using_union_types.ets | 10 +- .../test/main/custom_layout.ets.arkts2.json | 6 +- .../test/main/custom_layout.ets.autofix.json | 78 +- .../test/main/custom_layout.ets.migrate.ets | 17 +- .../test/main/custom_layout.ets.migrate.json | 12 +- .../main/dollar_binding_1.ets.autofix.json | 16 +- .../main/dollar_binding_1.ets.migrate.ets | 9 +- .../double_dollar_binding_1.ets.autofix.json | 20 +- .../double_dollar_binding_1.ets.migrate.ets | 11 +- .../double_excla_binding_1.ets.autofix.json | 70 +- .../double_excla_binding_1.ets.migrate.ets | 18 +- .../double_excla_binding_1.ets.migrate.json | 4 +- .../double_excla_binding_3.ets.autofix.json | 14 +- .../double_excla_binding_3.ets.migrate.ets | 8 +- .../main/dynamic_ctor_call.ets.arkts2.json | 10 - .../test/main/explicit_function_type.ets | 7 +- .../explicit_function_type.ets.arkts2.json | 10 + .../explicit_function_type.ets.autofix.json | 35 +- .../explicit_function_type.ets.migrate.ets | 7 +- .../main/extend_decorator_1.ets.autofix.json | 8 +- .../main/extend_decorator_1.ets.migrate.ets | 8 +- .../main/extend_decorator_1.ets.migrate.json | 64 +- .../test/main/func_inferred_type_args_2.ets | 4 + .../func_inferred_type_args_2.ets.arkts2.json | 120 +- ...func_inferred_type_args_2.ets.autofix.json | 161 +- .../func_inferred_type_args_2.ets.migrate.ets | 10 +- ...func_inferred_type_args_2.ets.migrate.json | 178 +- ...index_access_static_and_class_instance.ets | 24 + ...ss_static_and_class_instance.ets.args.json | 21 + ..._static_and_class_instance.ets.arkts2.json | 38 + ...static_and_class_instance.ets.autofix.json | 60 + ..._access_static_and_class_instance.ets.json | 28 + ..._static_and_class_instance.ets.migrate.ets | 24 + ...static_and_class_instance.ets.migrate.json | 17 + .../main/interface_import_1.ets.autofix.json | 30 +- .../main/interface_import_1.ets.migrate.ets | 15 +- .../main/interface_import_1.ets.migrate.json | 32 +- .../main/interface_import_3.ets.autofix.json | 4 +- .../main/interface_import_3.ets.migrate.ets | 5 +- .../main/interface_import_3.ets.migrate.json | 8 +- .../main/interface_import_4.ets.autofix.json | 26 +- .../main/interface_import_4.ets.migrate.ets | 15 +- .../main/interface_import_4.ets.migrate.json | 4 +- .../literals_as_prop_names.ets.arkts2.json | 10 - .../literals_as_prop_names.ets.autofix.json | 14 +- .../literals_as_prop_names.ets.migrate.ets | 5 +- .../literals_as_prop_names.ets.migrate.json | 104 +- .../test/main/localBuilder_1.ets.autofix.json | 12 +- .../test/main/localBuilder_1.ets.migrate.ets | 9 +- .../linter/test/main/method_inheritance.ets | 36 + .../linter/test/main/no_sparse_array.ets | 26 +- .../test/main/no_sparse_array.ets.arkts2.json | 150 + .../test/main/no_ts_like_smart_type.ets | 57 + .../no_ts_like_smart_type.ets.arkts2.json | 140 + .../main/numeric_semantics.ets.autofix.json | 18 +- .../main/numeric_semantics.ets.migrate.ets | 9 +- .../main/numeric_semantics.ets.migrate.json | 44 +- .../test/main/object_literals_properties.ets | 20 +- .../object_literals_properties.ets.args.json | 38 +- ...object_literals_properties.ets.arkts2.json | 4 +- ...bject_literals_properties.ets.autofix.json | 20 +- ...object_literals_properties.ets.migrate.ets | 20 +- ...bject_literals_properties.ets.migrate.json | 4 +- .../test/main/oh_modules/@arkts.utils.d.ets | 14 +- .../test/main/oh_modules/@kit.ArkTS.d.ets | 3 +- ...corators_and_interfaces_1.ets.autofix.json | 10 +- ...ecorators_and_interfaces_1.ets.migrate.ets | 13 +- ...corators_and_interfaces_1.ets.migrate.json | 12 +- ...corators_and_interfaces_4.ets.autofix.json | 60 +- ...ecorators_and_interfaces_4.ets.migrate.ets | 10 +- ...corators_and_interfaces_4.ets.migrate.json | 24 +- .../provide_annotation_1.ets.autofix.json | 20 +- .../main/provide_annotation_1.ets.migrate.ets | 6 +- .../provide_annotation_1.ets.migrate.json | 14 +- .../provide_annotation_2.ets.autofix.json | 18 +- .../main/provide_annotation_2.ets.migrate.ets | 6 +- .../provide_annotation_2.ets.migrate.json | 12 +- .../linter/test/main/runtime_array_bound.ets | 5 + .../main/runtime_array_bound.ets.arkts2.json | 30 + .../main/runtime_array_bound.ets.migrate.ets | 5 + .../main/structural_identity.ets.arkts2.json | 80 +- .../styles_decorator_anon_1.ets.arkts2.json | 4 +- .../styles_decorator_anon_1.ets.autofix.json | 16 +- .../styles_decorator_anon_1.ets.migrate.ets | 10 +- ...styles_decorator_global_1.ets.autofix.json | 18 +- .../styles_decorator_global_1.ets.migrate.ets | 13 +- .../test/main/styles_decorator_global_2.ets | 10 +- .../styles_decorator_global_2.ets.arkts2.json | 43 +- ...styles_decorator_global_2.ets.autofix.json | 87 +- .../styles_decorator_global_2.ets.migrate.ets | 2 + .../styles_decorator_mix_1.ets.arkts2.json | 16 +- .../styles_decorator_mix_1.ets.autofix.json | 56 +- .../styles_decorator_mix_1.ets.migrate.ets | 14 +- .../test/main/styles_decorator_mix_2.ets | 4 +- .../styles_decorator_mix_2.ets.migrate.ets | 4 +- ...styles_decorator_struct_1.ets.autofix.json | 46 +- .../styles_decorator_struct_1.ets.migrate.ets | 27 +- ...styles_decorator_struct_1.ets.migrate.json | 8 +- .../test/main/styles_decorator_struct_2.ets | 16 +- .../styles_decorator_struct_2.ets.arkts2.json | 28 +- ...styles_decorator_struct_2.ets.autofix.json | 50 +- .../main/styles_decorator_struct_2.ets.json | 4 +- .../styles_decorator_struct_2.ets.migrate.ets | 12 +- ...styles_decorator_struct_2.ets.migrate.json | 8 +- .../test/main/styles_decorator_struct_3.ets | 38 + .../styles_decorator_struct_3.ets.args.json | 21 + .../styles_decorator_struct_3.ets.arkts2.json | 108 + ...styles_decorator_struct_3.ets.autofix.json | 225 + .../main/styles_decorator_struct_3.ets.json | 17 + .../styles_decorator_struct_3.ets.migrate.ets | 50 + ...styles_decorator_struct_3.ets.migrate.json | 17 + .../test/main/ts_overload.ets.arkts2.json | 20 - .../linter/test/rules/rule37.ets.migrate.json | 13 +- .../sdk_ability_asynchronous_lifecycle.ets | 41 + ...ility_asynchronous_lifecycle.ets.args.json | 19 + ...ity_asynchronous_lifecycle.ets.arkts2.json | 148 + ...dk_ability_asynchronous_lifecycle.ets.json | 17 + .../sdkwhite/decl_with_duplicate_name_sdk.ets | 28 +- ...cl_with_duplicate_name_sdk.ets.arkts2.json | 284 +- .../decl_with_duplicate_name_sdk.ets.json | 32 +- .../return_new_interface.ets.arkts2.json | 20 - ets2panda/linter/webpack.config.js | 4 +- 261 files changed, 14853 insertions(+), 2922 deletions(-) create mode 100755 ets2panda/linter/package-lock.json create mode 100644 ets2panda/linter/scripts/testRunner/coverage_collect.js create mode 100644 ets2panda/linter/scripts/testRunner/coverage_prepare.js create mode 100644 ets2panda/linter/scripts/testRunner/coverage_report.js create mode 100644 ets2panda/linter/src/lib/statistics/scan/CountFile.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/CountNapiFile.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/FloderScanResultInfo.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/NapiFileStatisticInfo.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/ProblemNumbersInfo.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsCommonFunction.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsInfo.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/RuleDetailedErrorInfo.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/ScanTaskRelatedInfo.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/StatisticsReportInPutInfo.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/TimeRecorder.ts create mode 100644 ets2panda/linter/src/lib/statistics/scan/WorkLoadInfo.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/AsyncLifecycleSDK.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/MapKeyConst.ts create mode 100644 ets2panda/linter/src/lib/utils/consts/WorkloadRelatedConst.ts create mode 100644 ets2panda/linter/src/lib/utils/functions/ConfiguredRulesProcess.ts create mode 100644 ets2panda/linter/src/lib/utils/functions/CookBookUtils.ts create mode 100644 ets2panda/linter/src/lib/utils/functions/ProcessWrite.ts create mode 100644 ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets create mode 100644 ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.arkts2.json create mode 100644 ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.autofix.json create mode 100644 ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.json create mode 100644 ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.migrate.ets create mode 100644 ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.migrate.json create mode 100755 ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets create mode 100755 ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets.args.json create mode 100755 ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets.arkts2.json create mode 100755 ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets.json create mode 100644 ets2panda/linter/test/main/index_access_static_and_class_instance.ets create mode 100755 ets2panda/linter/test/main/index_access_static_and_class_instance.ets.args.json create mode 100644 ets2panda/linter/test/main/index_access_static_and_class_instance.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/index_access_static_and_class_instance.ets.autofix.json create mode 100644 ets2panda/linter/test/main/index_access_static_and_class_instance.ets.json create mode 100644 ets2panda/linter/test/main/index_access_static_and_class_instance.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/index_access_static_and_class_instance.ets.migrate.json create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_3.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_3.ets.args.json create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_3.ets.arkts2.json create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_3.ets.autofix.json create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_3.ets.json create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_3.ets.migrate.ets create mode 100644 ets2panda/linter/test/main/styles_decorator_struct_3.ets.migrate.json create mode 100644 ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets create mode 100644 ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.args.json create mode 100644 ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.arkts2.json create mode 100644 ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.json diff --git a/ets2panda/linter/.gitignore b/ets2panda/linter/.gitignore index 4343cbbd9d..a84c3073e0 100644 --- a/ets2panda/linter/.gitignore +++ b/ets2panda/linter/.gitignore @@ -5,3 +5,4 @@ dist node_modules package-lock.json panda-tslinter-1.0.0.tgz +coverage/ \ No newline at end of file diff --git a/ets2panda/linter/arkanalyzer/config/arkanalyzer.json b/ets2panda/linter/arkanalyzer/config/arkanalyzer.json index 17df9e7480..ad4da7a31d 100644 --- a/ets2panda/linter/arkanalyzer/config/arkanalyzer.json +++ b/ets2panda/linter/arkanalyzer/config/arkanalyzer.json @@ -19,7 +19,8 @@ "sdkGlobalFolders": [ "component", "@internal", - "ohos-typescript" + "ohos-typescript", + "dist" ], "tsconfig": "tsconfig.json" -} \ 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 index aa3b7fd421..4696d9d522 100644 --- a/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts +++ b/ets2panda/linter/arkanalyzer/src/core/common/SdkUtils.ts @@ -67,12 +67,19 @@ export class SdkUtils { } catch { logger.debug(`use builtin sdk file in ${builtInPath}.`); } - const filePath = path.resolve(builtInPath, this.esVersionMap.get(this.esVersion) ?? ''); - this.BUILT_IN_SDK.path = path.resolve(builtInPath); + let filePath = path.resolve(builtInPath, this.esVersionMap.get(this.esVersion) ?? ''); if (!fs.existsSync(filePath)) { logger.error(`built in directory ${filePath} is not exist, please check!`); - return []; + // This is the temporarily solution for linter, will update with using config to set builtin sdk path + builtInPath = 'dist'; + filePath = path.resolve(builtInPath, this.esVersionMap.get(this.esVersion) ?? ''); + logger.debug(`use new builtin sdk file in ${builtInPath}.`); + if (!fs.existsSync(filePath)) { + logger.error(`new built in directory ${filePath} is not exist, please check!`); + return []; + } } + this.BUILT_IN_SDK.path = path.resolve(builtInPath); const result = new Set(); this.dfsFiles(filePath, result); return Array.from(result); diff --git a/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts index 5243a14f39..e5591c8c30 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/CustomBuilderCheck.ts @@ -23,19 +23,14 @@ import { 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 { FixInfo, RuleFix } from '../../model/Fix'; +import { RuleFix } from '../../model/Fix'; import { FixPosition, FixUtils } from '../../utils/common/FixUtils'; import { WarnInfo } from '../../utils/common/Utils'; @@ -79,52 +74,9 @@ 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; diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts index a17b9064ba..4a15f6af6a 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropAssignCheck.ts @@ -95,33 +95,35 @@ export class InteropAssignCheck implements BaseChecker { 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(); - if (argTy instanceof PrimitiveType || this.isBoxedType(argTy)) { + callsites + .filter(cs => cs.getCfg().getDeclaringMethod().getLanguage() === Language.ARKTS1_1) + .forEach(cs => { + let hasTargetArg = false; + const invoke = cs.getInvokeExpr()!; + const csMethod = cs.getCfg().getDeclaringMethod(); + invoke.getArgs().forEach(arg => { + const argTy = arg.getType(); + if (argTy instanceof PrimitiveType || this.isBoxedType(argTy)) { + return; + } + const argTyLang = this.getTypeDefinedLang(argTy, scene) ?? csMethod?.getLanguage() ?? Language.UNKNOWN; + if (argTyLang === Language.ARKTS1_1) { + hasTargetArg = true; + } + }); + if (!hasTargetArg) { return; } - const argTyLang = this.getTypeDefinedLang(argTy, scene) ?? csMethod?.getLanguage() ?? Language.UNKNOWN; - if (argTyLang === Language.ARKTS1_1) { - hasTargetArg = true; - } + 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)); }); - 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 isBoxedType(checkType: Type): boolean { diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropDeprecatedBuiltInAPICheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropDeprecatedBuiltInAPICheck.ts index b8af6a32c8..02b2b9170d 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/InteropDeprecatedBuiltInAPICheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropDeprecatedBuiltInAPICheck.ts @@ -27,7 +27,6 @@ import { ArkNamespace, Local, ClassType, - ArkField, ClassSignature, Type, BooleanType, @@ -60,6 +59,7 @@ import { WarnInfo } from '../../utils/common/Utils'; import { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass'; import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; import { MethodParameter } from 'arkanalyzer/lib/core/model/builder/ArkMethodBuilder'; +import { AbstractFieldRef, ArkReturnStmt } from 'arkanalyzer'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'DeprecatedBuiltInAPICheck'); const gMetaData: BaseMetaData = { @@ -226,7 +226,7 @@ class DeprecatedAPIList { this.createMapForEachAPI(), this.createArraySymbolIteratorAPI(), this.createSetSymbolIteratorAPI(), - this.createMapSymbolIteratorAPI() + this.createMapSymbolIteratorAPI(), ]; private static createArrayEveryAPI1(): DeprecatedAPIInfo { @@ -385,9 +385,8 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { }; public processArkClass(arkClass: ArkClass, globalVarMap: Map): void { - for (let field of arkClass.getFields()) { - this.processClassField(field, globalVarMap); - } + this.processArkMethod(arkClass.getInstanceInitMethod(), globalVarMap); + this.processArkMethod(arkClass.getStaticInitMethod(), globalVarMap); for (let mtd of arkClass.getMethods()) { this.processArkMethod(mtd, globalVarMap); } @@ -402,16 +401,6 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { } } - public processClassField(field: ArkField, globalVarMap: Map): void { - const stmts = field.getInitializer(); - for (const stmt of stmts) { - const invokeExpr = this.getInvokeExpr(stmt); - if (invokeExpr === null) { - continue; - } - } - } - public processArkMethod(target: ArkMethod, globalVarMap: Map): void { const stmts = target.getBody()?.getCfg().getStmts() ?? []; for (const stmt of stmts) { @@ -438,7 +427,7 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { let checkAll = { value: true }; let visited: Set = new Set(); if (this.checkFromStmt(checkStmt, globalVarMap, checkAll, visited)) { - this.addIssueReport(stmt, targetLocal); + this.addIssueReport(stmt, targetLocal, checkAll.value); } } } @@ -514,13 +503,14 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { if (this.isInstanceCallMethodInDeprecatedAPIs(base, stmt, invokeExpr.getMethodSignature(), invokeExpr.getArgs())) { return base; } - // instance invoke未匹配到,继续匹配静态调用。Array.from的API调用ArkAnalyzer也表示为ArkInstanceInvokeExpr,因为API定义里没有明确的static标识。 - return this.getTargetValueInStaticInvokeWithDeprecatedAPIs(invokeExpr); + // Array.from的API调用ArkAnalyzer也表示为ArkInstanceInvokeExpr,因为API定义里没有明确的static标识 + return this.getTargetLocalInArrayFrom(invokeExpr); } else if (invokeExpr instanceof ArkPtrInvokeExpr) { // TODO:可能存在ptr invoke的场景吗? return null; } else if (invokeExpr instanceof ArkStaticInvokeExpr) { - return null; + // Symbol.iterator API 检测的Reflect.get场景,是static invoke + return this.getTargetLocalInReflectGet(invokeExpr); } return null; } @@ -553,8 +543,64 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { return true; } - private getTargetValueInStaticInvokeWithDeprecatedAPIs(staticInvokeExpr: ArkStaticInvokeExpr): Local | null { - const callApiMethod = staticInvokeExpr.getMethodSignature(); + // 此函数仅用作Symbol.iterator API 检测的Reflect.get场景 + private getTargetLocalInReflectGet(staticInvokeExpr: ArkStaticInvokeExpr): Local | null { + const method = staticInvokeExpr.getMethodSignature(); + const methodName = method.getMethodSubSignature().getMethodName(); + const namespaceName = method.getDeclaringClassSignature().getDeclaringNamespaceSignature()?.getNamespaceName(); + if (namespaceName !== 'Reflect' || methodName !== 'get') { + return null; + } + + const args = staticInvokeExpr.getArgs(); + if (args.length < 2) { + return null; + } + const targetLocal = args[0]; + const apiCall = args[1]; + if (!(targetLocal instanceof Local) || !(apiCall instanceof Local)) { + return null; + } + + const declaringStmt = apiCall.getDeclaringStmt(); + if (declaringStmt === null || !(declaringStmt instanceof ArkAssignStmt)) { + return null; + } + const rightOp = declaringStmt.getRightOp(); + if (!(rightOp instanceof ArkInstanceFieldRef)) { + return null; + } + const fieldBaseName = rightOp.getBase().getName(); + const fieldName = rightOp.getFieldName(); + if (fieldBaseName !== 'Symbol' || fieldName !== 'iterator') { + return null; + } + + for (const api of DeprecatedAPIList.DeprecatedAPIs) { + if (api.name !== 'Symbol.iterator') { + continue; + } + if (api.base === APIBaseCategory.Array && targetLocal.getType() instanceof ArrayType) { + return targetLocal; + } + if (api.base === APIBaseCategory.Set) { + const localType = targetLocal.getType(); + if (localType instanceof ClassType && localType.getClassSignature().getClassName() === 'Set') { + return targetLocal; + } + } + if (api.base === APIBaseCategory.Map) { + const localType = targetLocal.getType(); + if (localType instanceof ClassType && localType.getClassSignature().getClassName() === 'Map') { + return targetLocal; + } + } + } + return null; + } + + private getTargetLocalInArrayFrom(invokeExpr: ArkInstanceInvokeExpr): Local | null { + const callApiMethod = invokeExpr.getMethodSignature(); const callApiClass = callApiMethod.getDeclaringClassSignature(); for (const api of DeprecatedAPIList.DeprecatedAPIs) { if (!api.isStatic) { @@ -572,7 +618,7 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { continue; } if (this.compareParamTypes(api.params, callApiMethod.getMethodSubSignature().getParameters())) { - const args = staticInvokeExpr.getArgs(); + const args = invokeExpr.getArgs(); // 形参匹配的情况下,进一步比较传入的实参,因为当前废弃接口大多数为去掉any类型的第二个可选参数 // TODO:这里需要考虑如何做的更通用 if (args.length !== api.params.length) { @@ -600,24 +646,6 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { return null; } - private isMatchSymbolIterator(apiName: string, callApiName: string, stmt: Stmt): boolean { - // 对于map[Symbol.iterator]这样的API,这里会存在%0 = Symbol.iterator的操作 - if (apiName !== 'Symbol.iterator' || !callApiName.startsWith('%')) { - return false; - } - const tempLocalDeclaring = stmt.getCfg().getDeclaringMethod().getBody()?.getLocals().get(callApiName)?.getDeclaringStmt(); - if (tempLocalDeclaring && tempLocalDeclaring instanceof ArkAssignStmt) { - const rightOp = tempLocalDeclaring.getRightOp(); - if (!(rightOp instanceof ArkInstanceFieldRef)) { - return false; - } - if (rightOp.getFieldName() === 'iterator' && rightOp.getBase().getName() === 'Symbol') { - return true; - } - } - return false; - } - private isInstanceCallMethodInDeprecatedAPIs(callBase: Local, stmt: Stmt, callMethod: MethodSignature, args: Value[]): boolean { const callApiName = callMethod.getMethodSubSignature().getMethodName(); const callApiParams = callMethod.getMethodSubSignature().getParameters(); @@ -626,6 +654,10 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { if (api.name !== callApiName) { continue; } + // 对于for...of的语句,ArkAnalyzer会为其生成Symbol.iterator的调用语句,此处从源码中查找关键字以区分是源码中有还是自动生成的 + if (api.name === 'Symbol.iterator' && !stmt.getOriginalText()?.includes('Symbol.iterator')) { + continue; + } if (api.isStatic) { continue; } @@ -634,7 +666,7 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { } // Array concat API ArkAnalyzer当前无法很好处理...items形式的入参,此处作为特例处理 - if (api.name === 'concat') { + if (api.name === 'concat' && api.base === APIBaseCategory.Array) { return this.isMatchArrayConcatAPI(args); } @@ -642,18 +674,7 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { if (apiParams === undefined) { return true; } - let allParamTypeMatch = true; - if (apiParams.length !== callApiParams.length) { - allParamTypeMatch = false; - } else { - for (let i = 0; i < apiParams.length; i++) { - if (!this.isTypeMatch(apiParams[i], callApiParams[i].getType())) { - allParamTypeMatch = false; - break; - } - } - } - + let allParamTypeMatch = this.compareParamTypes(apiParams, callApiParams); if (allParamTypeMatch) { // 形参匹配的情况下,进一步比较传入的实参,因为当前废弃接口大多数为去掉any类型的第二个可选参数 // TODO:这里需要考虑如何做的更通用 @@ -705,7 +726,10 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { if (apiMatch === null || callApiMatch === null) { return false; } - return apiMatch[0] === callApiMatch[0]; + // 移除字符串中的类型的文件签名、类签名、泛型等信息后进行比较 + let apiParamsStr = apiMatch[0].replace(/@[^:]+:/, '').replace(/<[^>]+>/, ''); + let callApiParamsStr = callApiMatch[0].replace(/@[^:]+:/, '').replace(/<[^>]+>/, ''); + return apiParamsStr === callApiParamsStr; } else if (callApiType instanceof ClassType && apiType instanceof ClassType) { // 若类型为FunctionType,仅需匹配class name,因为apiTypeStr类型推导后有可能为@%unk/%unk: ArrayLike,而callApiTypeStr有明确的declaring file return callApiType.getClassSignature().getClassName() === apiType.getClassSignature().getClassName(); @@ -735,7 +759,7 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { private checkFromStmt(stmt: Stmt, globalVarMap: Map, checkAll: { value: boolean }, visited: Set, depth: number = 0): boolean { if (depth > CALL_DEPTH_LIMIT) { checkAll.value = false; - return false; + return true; } const node = this.dvfg.getOrNewDVFGNode(stmt); let worklist: DVFGNode[] = [node]; @@ -747,10 +771,11 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { } visited.add(currentStmt); - if (this.isLeftOpDefinedInStaticArkTS(currentStmt)) { + if (this.isLeftOpOrReturnOpDefinedInStaticArkTS(currentStmt)) { return true; } + // 当前语句的右值是全局变量,查找全局变量的定义语句 const gv = this.isRightOpGlobalVar(currentStmt); if (gv) { const globalDefs = globalVarMap.get(gv.getName()); @@ -766,6 +791,7 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { continue; } + // 当前语句的右值是函数返回值,查找调用函数的所有return语句 const callsite = this.cg.getCallSiteByStmt(currentStmt); for (const cs of callsite) { const declaringMtd = this.cg.getArkMethodByFuncID(cs.calleeFuncID); @@ -784,6 +810,8 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { } } } + + // 当前语句的右值是函数参数赋值语句,查找所有调用处的入参情况 const paramRef = this.isFromParameter(currentStmt); if (paramRef) { const paramIdx = paramRef.getIndex(); @@ -797,6 +825,31 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { } } } + + // 当前语句的右值是属性赋值语句,查找该属性的初始化语句 + if (currentStmt instanceof ArkAssignStmt && currentStmt.getRightOp() instanceof AbstractFieldRef) { + const fieldSignature = (currentStmt.getRightOp() as AbstractFieldRef).getFieldSignature(); + const classSignature = fieldSignature.getDeclaringSignature(); + if (classSignature instanceof ClassSignature) { + const field = this.scene.getClass(classSignature)?.getField(fieldSignature); + if (field) { + field.getInitializer().forEach(s => worklist.push(this.dvfg.getOrNewDVFGNode(s))); + } + } + } + + // 当前语句是return语句,查找return操作数的相关语句 + if (currentStmt instanceof ArkReturnStmt) { + const returnOp = currentStmt.getOp(); + if (returnOp instanceof Local) { + let checkStmt = + this.getLastAssignStmt(returnOp, stmt) ?? + this.checkTargetLocalAsGlobal(currentStmt.getCfg().getDeclaringMethod(), stmt, returnOp, globalVarMap); + if (checkStmt !== null) { + worklist.push(this.dvfg.getOrNewDVFGNode(checkStmt)); + } + } + } current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); } return false; @@ -843,15 +896,20 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { } // 判断语句是否为赋值语句,且左值的定义来自于ArkTS1.2 - private isLeftOpDefinedInStaticArkTS(stmt: Stmt): boolean { - if (!(stmt instanceof ArkAssignStmt)) { + private isLeftOpOrReturnOpDefinedInStaticArkTS(stmt: Stmt): boolean { + if (!(stmt instanceof ArkAssignStmt) && !(stmt instanceof ArkReturnStmt)) { return false; } - const leftOp = stmt.getLeftOp(); - if (!(leftOp instanceof Local)) { + let operand: Value; + if (stmt instanceof ArkAssignStmt) { + operand = stmt.getLeftOp(); + } else { + operand = stmt.getOp(); + } + if (!(operand instanceof Local)) { return false; } - return this.isLocalDefinedInStaticArkTS(leftOp); + return this.isLocalDefinedInStaticArkTS(operand); } private isFromParameter(stmt: Stmt): ArkParameterRef | undefined { @@ -888,11 +946,14 @@ export class InteropDeprecatedBuiltInAPICheck implements BaseChecker { }); } - private addIssueReport(stmt: Stmt, operand: Value): void { + private addIssueReport(stmt: Stmt, operand: Value, checkAll: boolean = true): void { const severity = this.rule.alert ?? this.metaData.severity; const warnInfo = this.getLineAndColumn(stmt, operand); const problem = 'builtin-api'; - const desc = `Builtin API is not support in ArkTS1.2 (${this.rule.ruleId.replace('@migration/', '')})`; + let desc = `Builtin API is not support in ArkTS1.2 (${this.rule.ruleId.replace('@migration/', '')})`; + if (!checkAll) { + desc = `Can not check when function call chain depth exceeds ${CALL_DEPTH_LIMIT}, please check it manually (${this.rule.ruleId.replace('@migration/', '')})`; + } let defects = new Defects( warnInfo.line, diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropDynamicObjectLiteralsCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropDynamicObjectLiteralsCheck.ts index 3b59046d94..9d93f7f9c6 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/InteropDynamicObjectLiteralsCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropDynamicObjectLiteralsCheck.ts @@ -110,12 +110,11 @@ export class InteropObjectLiteralCheck implements BaseChecker { 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) { + if (this.checkFromStmt(stmt, scene, checkAll, visited)) { const opType = rightOp.getOp().getType(); if (!(opType instanceof ClassType)) { continue; @@ -124,27 +123,17 @@ export class InteropObjectLiteralCheck implements BaseChecker { 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()); + if (opTypeClass.getLanguage() === Language.TYPESCRIPT || opTypeClass.getLanguage() === Language.ARKTS1_1) { + this.addIssueReport(stmt, rightOp, opTypeClass.getLanguage(), checkAll.value); } } } } - private checkFromStmt( - stmt: Stmt, - scene: Scene, - res: Stmt[], - checkAll: { value: boolean }, - visited: Set, - depth: number = 0 - ): void { + private checkFromStmt(stmt: Stmt, scene: Scene, checkAll: { value: boolean }, visited: Set, depth: number = 0): boolean { if (depth > CALL_DEPTH_LIMIT) { checkAll.value = false; - return; + return true; } const node = this.dvfg.getOrNewDVFGNode(stmt); let worklist: DVFGNode[] = [node]; @@ -156,36 +145,42 @@ export class InteropObjectLiteralCheck implements BaseChecker { } visited.add(currentStmt); if (this.isObjectLiteral(currentStmt, scene)) { - res.push(currentStmt); - continue; + return true; } const callsite = this.cg.getCallSiteByStmt(currentStmt); - callsite.forEach(cs => { + for (const cs of callsite) { const declaringMtd = this.cg.getArkMethodByFuncID(cs.calleeFuncID); if (!declaringMtd || !declaringMtd.getCfg()) { - return; + return false; } 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 returnStmts = declaringMtd.getReturnStmt(); + for (const stmt of returnStmts) { + const res = this.checkFromStmt(stmt, scene, checkAll, visited, depth + 1); + if (res) { + return true; + } + } + } const paramRef = this.isFromParameter(currentStmt); if (paramRef) { const paramIdx = paramRef.getIndex(); - const callsites = this.cg.getInvokeStmtByMethod( - currentStmt.getCfg().getDeclaringMethod().getSignature() - ); + 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) - ); + const argDefs = this.collectArgDefs(paramIdx, callsites); + for (const def of argDefs) { + const res = this.checkFromStmt(def, scene, checkAll, visited, depth + 1); + if (res) { + return true; + } + } } current.getIncomingEdge().forEach(e => worklist.push(e.getSrcNode() as DVFGNode)); } + return false; } private processCallsites(callsites: Stmt[]): void { @@ -235,7 +230,7 @@ export class InteropObjectLiteralCheck implements BaseChecker { }); } - private addIssueReport(stmt: Stmt, operand: Value, result: Stmt[], targetLanguage: Language): void { + private addIssueReport(stmt: Stmt, operand: Value, targetLanguage: Language, checkAll: boolean = true): void { const interopRuleId = this.getInteropRule(targetLanguage); if (interopRuleId === null) { return; @@ -244,10 +239,11 @@ export class InteropObjectLiteralCheck implements BaseChecker { 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 desc = `instanceof including object literal with class type from ${targetLan} (${interopRuleId})`; + if (!checkAll) { + desc = `Can not check when function call chain depth exceeds ${CALL_DEPTH_LIMIT}, please check it manually (${interopRuleId})`; + } let defects = new Defects( warnInfo.line, warnInfo.startCol, diff --git a/ets2panda/linter/homecheck/src/checker/migration/InteropS2DObjectLiteralsCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/InteropS2DObjectLiteralsCheck.ts index 79c14788bd..9e316294f2 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/InteropS2DObjectLiteralsCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/InteropS2DObjectLiteralsCheck.ts @@ -33,6 +33,7 @@ import { IssueReport } from '../../model/Defects'; import { ArkClass, ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; import { getLanguageStr, getLineAndColumn } from './Utils'; +import { ArkThisRef } from 'arkanalyzer'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'InteropS2DObjectLiteralCheck'); const gMetaData: BaseMetaData = { @@ -105,6 +106,11 @@ export class InteropS2DObjectLiteralCheck implements BaseChecker { } private checkAssignWithObjectLiteral(stmt: ArkAssignStmt, target: ArkMethod): void { + // this = thisRef 赋值语句需要跳过,否则该class一定会被扫描一遍,此次扫描多余,且可能会产生行号为-1的错误issue + // 若此class有问题,会在真正使用到此class的源码处进行告警,无需查找this ref语句 + if (stmt.getRightOp() instanceof ArkThisRef) { + return; + } const leftOpType = stmt.getLeftOp().getType(); if (!(leftOpType instanceof ClassType)) { return; diff --git a/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts index 3e6f594aa1..3c7fb7450a 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/NoTSLikeAsCheck.ts @@ -15,46 +15,46 @@ import path from 'path'; import { - ArkMethod, + AbstractFieldRef, ArkAssignStmt, - FieldSignature, - Stmt, - Scene, - Value, - DVFGBuilder, - ArkInstanceOfExpr, - CallGraph, - ArkParameterRef, - ArkInstanceFieldRef, - ArkNamespace, - Local, ArkCastExpr, - ClassType, - classSignatureCompare, ArkField, - fileSignatureCompare, - Cfg, - BasicBlock, ArkIfStmt, + ArkInstanceFieldRef, + ArkInstanceOfExpr, + ArkMethod, + ArkNamespace, + ArkNormalBinopExpr, + ArkParameterRef, ArkUnopExpr, - RelationalBinaryOperator, + BasicBlock, + CallGraph, + Cfg, + ClassSignature, + classSignatureCompare, + ClassType, + DVFGBuilder, + FieldSignature, + fileSignatureCompare, LineColPosition, - UnaryOperator, - ArkNormalBinopExpr, + Local, NormalBinaryOperator, - AbstractFieldRef, - ClassSignature, + RelationalBinaryOperator, + Scene, + Stmt, + UnaryOperator, + Value, } 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 { Defects, MatcherCallback, Rule } 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 { CALL_DEPTH_LIMIT, getGlobalsDefineInDefaultMethod, getLineAndColumn, GlobalCallGraphHelper } from './Utils'; import { ClassCategory } from 'arkanalyzer/lib/core/model/ArkClass'; import { Language } from 'arkanalyzer/lib/core/model/ArkFile'; -import { BooleanConstant } from 'arkanalyzer/lib/core/base/Constant'; +import { BooleanConstant, NumberConstant } from 'arkanalyzer/lib/core/base/Constant'; +import { ArkClass, NumberType } from 'arkanalyzer'; const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoTSLikeAsCheck'); const gMetaData: BaseMetaData = { @@ -74,6 +74,7 @@ export class NoTSLikeAsCheck implements BaseChecker { public rule: Rule; public defects: Defects[] = []; public issues: IssueReport[] = []; + private scene: Scene; private cg: CallGraph; private dvfg: DVFG; private dvfgBuilder: DVFGBuilder; @@ -88,6 +89,7 @@ export class NoTSLikeAsCheck implements BaseChecker { } public check = (scene: Scene): void => { + this.scene = scene; this.cg = GlobalCallGraphHelper.getCGInstance(scene); this.dvfg = new DVFG(this.cg); @@ -105,58 +107,38 @@ export class NoTSLikeAsCheck implements BaseChecker { 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); - } + this.processClass(clazz, globalVarMap); } for (let namespace of arkFile.getAllNamespacesUnderThisFile()) { - this.processNameSpace(namespace, globalVarMap, scene); + this.processNameSpace(namespace, globalVarMap); } } }; - public processNameSpace(namespace: ArkNamespace, globalVarMap: Map, scene: Scene): void { + public processClass(arkClass: ArkClass, globalVarMap: Map): void { + for (let field of arkClass.getFields()) { + this.processClassField(field, globalVarMap); + } + for (let mtd of arkClass.getMethods()) { + this.processArkMethod(mtd, globalVarMap); + } + } + + public processNameSpace(namespace: ArkNamespace, globalVarMap: Map): void { for (let ns of namespace.getNamespaces()) { - this.processNameSpace(ns, globalVarMap, scene); + this.processNameSpace(ns, globalVarMap); } 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); - } + this.processClass(clazz, globalVarMap); } } - 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 processClassField(field: ArkField, globalVarMap: Map): void { + const instInit = field.getDeclaringArkClass().getInstanceInitMethod(); + this.processArkMethod(instInit, globalVarMap); } - public processArkMethod(target: ArkMethod, globalVarMap: Map, scene: Scene): void { + public processArkMethod(target: ArkMethod, globalVarMap: Map): void { const stmts = target.getBody()?.getCfg().getStmts() ?? []; for (const stmt of stmts) { // cast表达式所在语句为sink点,从该点开始进行逆向数据流分析 @@ -164,6 +146,13 @@ export class NoTSLikeAsCheck implements BaseChecker { if (castExpr === null) { continue; } + + // 判断是否为cast表达式的自增自减运算,属于告警场景之一 + if (this.isCastExprWithIncrementDecrement(stmt)) { + this.addIssueReport(stmt, castExpr, undefined, true); + continue; + } + // 判断cast类型断言的类型是否是class,非class的场景不在本规则检查范围内 if (!(castExpr.getType() instanceof ClassType)) { continue; @@ -178,7 +167,7 @@ export class NoTSLikeAsCheck implements BaseChecker { let checkAll = { value: true }; let visited: Set = new Set(); - const result = this.checkFromStmt(stmt, scene, globalVarMap, checkAll, visited); + const result = this.checkFromStmt(stmt, globalVarMap, checkAll, visited); if (result !== null) { this.addIssueReport(stmt, castExpr, result); } else { @@ -189,6 +178,62 @@ export class NoTSLikeAsCheck implements BaseChecker { } } + private isCastExprWithIncrementDecrement(stmt: Stmt): boolean { + if (!(stmt instanceof ArkAssignStmt) || !(stmt.getRightOp() instanceof ArkCastExpr)) { + return false; + } + const castLocal = stmt.getLeftOp(); + if (!(castLocal instanceof Local)) { + return false; + } + // 判断是否为自增或自减语句,需要判断used stmt是否至少包含%0 = %0 + 1 和 castExpr = %0两条语句,不新增临时变量 + // 非自增或自减语句,used stmt中仅包含%1 = %0 + 1 + const usedStmts = castLocal.getUsedStmts(); + if (usedStmts.length !== 2) { + return false; + } + let selfAssignFlag = false; + let assignBackFlag = false; + for (const usedStmt of usedStmts) { + if (!(usedStmt instanceof ArkAssignStmt)) { + return false; + } + const leftOp = usedStmt.getLeftOp(); + const rightOp = usedStmt.getRightOp(); + if (leftOp instanceof Local) { + if (leftOp !== castLocal) { + return false; + } + if (!(rightOp instanceof ArkNormalBinopExpr)) { + return false; + } + const op1 = rightOp.getOp1(); + const op2 = rightOp.getOp2(); + const operator = rightOp.getOperator(); + if (op1 !== castLocal) { + return false; + } + if (operator !== NormalBinaryOperator.Addition && operator !== NormalBinaryOperator.Subtraction) { + return false; + } + if (!(op2 instanceof NumberConstant) || !(op2.getType() instanceof NumberType) || op2.getValue() !== '1') { + return false; + } + selfAssignFlag = true; + } + if (leftOp instanceof ArkCastExpr) { + if (leftOp !== stmt.getRightOp()) { + return false; + } + if (rightOp !== castLocal) { + return false; + } + assignBackFlag = true; + } + } + return selfAssignFlag && assignBackFlag; + } + private hasCheckedWithInstanceof(cfg: Cfg, stmt: Stmt): boolean { const castExpr = this.getCastExpr(stmt); if (castExpr === null) { @@ -346,14 +391,7 @@ export class NoTSLikeAsCheck implements BaseChecker { return null; } - private checkFromStmt( - stmt: Stmt, - scene: Scene, - globalVarMap: Map, - checkAll: { value: boolean }, - visited: Set, - depth: number = 0 - ): Stmt | null { + private checkFromStmt(stmt: Stmt, globalVarMap: Map, checkAll: { value: boolean }, visited: Set, depth: number = 0): Stmt | null { if (depth > CALL_DEPTH_LIMIT) { checkAll.value = false; return null; @@ -367,11 +405,11 @@ export class NoTSLikeAsCheck implements BaseChecker { continue; } visited.add(currentStmt); - if (this.isWithInterfaceAnnotation(currentStmt, scene)) { + if (this.isWithInterfaceAnnotation(currentStmt)) { return currentStmt; } - const fieldDeclareStmt = this.isCastOpFieldWithInterfaceType(currentStmt, scene); + const fieldDeclareStmt = this.isCastOpFieldWithInterfaceType(currentStmt); if (fieldDeclareStmt) { return fieldDeclareStmt; } @@ -401,7 +439,7 @@ export class NoTSLikeAsCheck implements BaseChecker { } const returnStmts = declaringMtd.getReturnStmt(); for (const stmt of returnStmts) { - const res = this.checkFromStmt(stmt, scene, globalVarMap, checkAll, visited, depth + 1); + const res = this.checkFromStmt(stmt, globalVarMap, checkAll, visited, depth + 1); if (res !== null) { return res; } @@ -414,7 +452,7 @@ export class NoTSLikeAsCheck implements BaseChecker { 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); + const res = this.checkFromStmt(stmt, globalVarMap, checkAll, visited, depth + 1); if (res !== null) { return res; } @@ -425,7 +463,7 @@ export class NoTSLikeAsCheck implements BaseChecker { return null; } - private isCastOpFieldWithInterfaceType(stmt: Stmt, scene: Scene): Stmt | undefined { + private isCastOpFieldWithInterfaceType(stmt: Stmt): Stmt | undefined { const obj = this.getCastOp(stmt); if (obj === null || !(obj instanceof Local)) { return undefined; @@ -440,13 +478,13 @@ export class NoTSLikeAsCheck implements BaseChecker { } const fieldDeclaring = rightOp.getFieldSignature().getDeclaringSignature(); if (fieldDeclaring instanceof ClassSignature) { - const field = scene.getClass(fieldDeclaring)?.getField(rightOp.getFieldSignature()); + const field = this.scene.getClass(fieldDeclaring)?.getField(rightOp.getFieldSignature()); if (!field) { return undefined; } const fieldInitializer = field.getInitializer(); const lastStmt = fieldInitializer[fieldInitializer.length - 1]; - if (this.isWithInterfaceAnnotation(lastStmt, scene)) { + if (this.isWithInterfaceAnnotation(lastStmt)) { return lastStmt; } } @@ -497,7 +535,7 @@ export class NoTSLikeAsCheck implements BaseChecker { } // 判断语句是否为赋值语句,且左值的类型注解为Interface,右值的类型与左值不一样 - private isWithInterfaceAnnotation(stmt: Stmt, scene: Scene): boolean { + private isWithInterfaceAnnotation(stmt: Stmt): boolean { if (!(stmt instanceof ArkAssignStmt)) { return false; } @@ -505,7 +543,7 @@ export class NoTSLikeAsCheck implements BaseChecker { if (!(leftOpType instanceof ClassType)) { return false; } - const leftOpTypeclass = scene.getClass(leftOpType.getClassSignature()); + const leftOpTypeclass = this.scene.getClass(leftOpType.getClassSignature()); if (leftOpTypeclass === null) { return false; } @@ -567,15 +605,17 @@ export class NoTSLikeAsCheck implements BaseChecker { }); } - private addIssueReport(stmt: Stmt, operand: ArkCastExpr, relatedStmt?: Stmt): void { + private addIssueReport(stmt: Stmt, operand: ArkCastExpr, relatedStmt?: Stmt, incrementCase: boolean = false): void { const severity = this.rule.alert ?? this.metaData.severity; - const warnInfo = this.getLineAndColumn(stmt, operand); + const warnInfo = 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; + if (incrementCase) { + desc = 'Can not use neither increment nor decrement with cast expression ' + desc; + } else if (relatedStmt === undefined) { + desc = `Can not check when function call chain depth exceeds ${CALL_DEPTH_LIMIT}, please check it manually ` + desc; } else { const sinkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); const relatedFile = relatedStmt.getCfg().getDeclaringMethod().getDeclaringArkFile(); @@ -585,6 +625,7 @@ export class NoTSLikeAsCheck implements BaseChecker { desc = `${descPrefix} in file ${path.normalize(relatedFile.getName())}: ${relatedStmt.getOriginPositionInfo().getLineNo()} ` + desc; } } + let defects = new Defects( warnInfo.line, warnInfo.startCol, @@ -601,19 +642,4 @@ export class NoTSLikeAsCheck implements BaseChecker { ); 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 b582c90aaf..f0c756eeed 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ObjectLiteralCheck.ts @@ -101,7 +101,7 @@ export class ObjectLiteralCheck implements BaseChecker { 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); + this.addIssueReport(stmt, rightOp, checkAll.value); } } } @@ -202,20 +202,14 @@ export class ObjectLiteralCheck implements BaseChecker { DVFGHelper.buildSingleDVFG(declaringMtd, scene); this.visited.add(declaringMtd); } - declaringMtd - .getReturnStmt() - .forEach(r => this.checkFromStmt(r, scene, res, topLevelVarMap, checkAll, visited, depth + 1)); + 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() - ); + 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) - ); + 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)); } @@ -360,11 +354,14 @@ export class ObjectLiteralCheck implements BaseChecker { }); } - private addIssueReport(stmt: Stmt, operand: Value): void { + private addIssueReport(stmt: Stmt, operand: Value, checkAll: boolean = true): void { const severity = this.rule.alert ?? this.metaData.severity; const warnInfo = this.getLineAndColumn(stmt, operand); const problem = 'ObjectLiteral'; - const desc = `${this.metaData.description} (${this.rule.ruleId.replace('@migration/', '')})`; + let desc = `${this.metaData.description} (${this.rule.ruleId.replace('@migration/', '')})`; + if (!checkAll) { + desc = `Can not check when function call chain depth exceeds ${CALL_DEPTH_LIMIT}, please check it manually (${this.rule.ruleId.replace('@migration/', '')})`; + } let defects = new Defects( warnInfo.line, warnInfo.startCol, diff --git a/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts b/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts index 8f9c5cdb03..59c04a84d8 100644 --- a/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts +++ b/ets2panda/linter/homecheck/src/checker/migration/ObservedDecoratorCheck.ts @@ -78,6 +78,7 @@ export class ObservedDecoratorCheck implements BaseChecker { public check = (arkClass: ArkClass): void => { const scene = arkClass.getDeclaringArkFile().getScene(); + const projectName = arkClass.getDeclaringArkFile().getProjectName(); for (const field of arkClass.getFields()) { if (!field.getDecorators().some(d => DECORATOR_SET.has(d.getKind()))) { continue; @@ -88,6 +89,10 @@ export class ObservedDecoratorCheck implements BaseChecker { let issueClasses: Set = new Set(); // ArkAnalyzer此处有问题,若field的类型注解为unclear type,会用右边的替换左边的。 const fieldType = field.getType(); + // 此处仅对field为class类型进行检查,包含class和interface,非class类型不在本规则检查范围之内 + if (!(fieldType instanceof ClassType)) { + continue; + } const initializers = field.getInitializer(); let canFindAllTargets = true; @@ -121,10 +126,10 @@ export class ObservedDecoratorCheck implements BaseChecker { locals.add(rightOp); } else if (rightOp instanceof ArkNewExpr) { // 此处需要区分field = new cls()和field = {}两种场景,查找完毕需继续遍历stmts以解析条件表达式造成的多赋值场景 - canFindAllTargets = canFindAllTargets && this.handleNewExpr(scene, fieldType, rightOp, usedClasses); + canFindAllTargets = canFindAllTargets && this.handleNewExpr(scene, fieldType, rightOp, usedClasses, projectName); } else if (rightOp instanceof AbstractInvokeExpr) { canFindAllTargets = - canFindAllTargets && this.handleInvokeExpr(scene, fieldType, rightOp, usedClasses); + canFindAllTargets && this.handleInvokeExpr(scene, fieldType, rightOp, usedClasses, projectName); } else { // 对应场景为使用条件表达式cond ? 123 : 456赋值时 continue; @@ -160,11 +165,15 @@ export class ObservedDecoratorCheck implements BaseChecker { // 此处需要区分field = new cls()和field = {}两种场景 // 对于field = new cls()场景,需要查找此右边class的所有父class // 对于field = {}场景,需要查找左边field类型为class时的所有父class - private handleNewExpr(scene: Scene, fieldType: Type, rightOp: ArkNewExpr, targets: Set): boolean { + private handleNewExpr(scene: Scene, fieldType: Type, rightOp: ArkNewExpr, targets: Set, projectName: string): boolean { const target = scene.getClass(rightOp.getClassType().getClassSignature()); if (target === null) { return false; } + // class为非本项目的内容时,表示调用到三方库、SDK等内容,不再继续进行查找 + if (target.getDeclaringArkFile().getProjectName() !== projectName) { + return true; + } if (!target.isAnonymousClass()) { // 理论上来说ArkNewExpr中的class一定ClassCategory.CLASS,此处仍然显式的检查一次 @@ -186,6 +195,10 @@ export class ObservedDecoratorCheck implements BaseChecker { if (fieldClass === null) { return false; } + // fieldClass为非本项目的内容时,表示调用到三方库、SDK等内容,不再继续进行查找 + if (fieldClass.getDeclaringArkFile().getProjectName() !== projectName) { + return true; + } if (fieldClass.getCategory() !== ClassCategory.CLASS) { return true; } @@ -201,13 +214,18 @@ export class ObservedDecoratorCheck implements BaseChecker { scene: Scene, fieldType: Type, invokeExpr: AbstractInvokeExpr, - targets: Set + targets: Set, + projectName: string ): boolean { let canFindAllTargets = true; const callMethod = scene.getMethod(invokeExpr.getMethodSignature()); if (callMethod === null) { return false; } + // callMethod为非本项目的内容时,表示调用到三方库、SDK等内容,不再继续进行查找 + if (callMethod.getDeclaringArkFile().getProjectName() !== projectName) { + return true; + } const stmts = callMethod.getBody()?.getCfg().getStmts(); if (stmts === undefined) { return false; diff --git a/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts b/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts index e08dbb90f7..b8a14fa1bd 100644 --- a/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts +++ b/ets2panda/linter/homecheck/src/utils/common/CheckEntry.ts @@ -98,7 +98,7 @@ export class CheckEntry { /** * 按规则维度统计并输出告警信息,按文件维度汇总并返回告警信息。 - * + * * @returns FileReport[] 文件报告数组,每个元素包含文件名、缺陷列表和输出信息 */ public sortIssues(): FileIssues[] { @@ -235,7 +235,7 @@ export async function checkEntryBuilder(checkEntry: CheckEntry): Promise=10.0.0" + } + }, + "node_modules/@es-joy/jsdoccomment": { + "version": "0.46.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@es-joy/jsdoccomment/-/jsdoccomment-0.46.0.tgz", + "integrity": "sha512-C3Axuq1xd/9VqFZpW4YAzOx5O9q/LP46uIQy/iNDpHG3fmPa6TBtvfglMCs3RBiBxAIi0Go97r8+jvTt55XMyQ==", + "dev": true, + "dependencies": { + "comment-parser": "1.4.1", + "esquery": "^1.6.0", + "jsdoc-type-pratt-parser": "~4.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.7.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz", + "integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint-community/regexpp/-/regexpp-4.12.1.tgz", + "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", + "dev": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/compat": { + "version": "1.2.9", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint/compat/-/compat-1.2.9.tgz", + "integrity": "sha512-gCdSY54n7k+driCadyMNv8JSPzYLeDVM/ikZRtvtROBpRdFSkS8W9A82MqsaY7lZuwL0wiapgD0NT1xT0hyJsA==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "peerDependencies": { + "eslint": "^9.10.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/config-array": { + "version": "0.20.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint/config-array/-/config-array-0.20.0.tgz", + "integrity": "sha512-fxlS1kkIjx8+vy2SjuCB94q3htSNrufYTXubwiBFeaQHbH6Ipi43gFJq2zCMt6PHhImH3Xmr0NksKDvchWlpQQ==", + "dev": true, + "dependencies": { + "@eslint/object-schema": "^2.1.6", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-array/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://repo.huaweicloud.com/repository/npm/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint/config-helpers/-/config-helpers-0.2.2.tgz", + "integrity": "sha512-+GPzk8PlG0sPpzdU5ZvIRMPidzAnZDl/s9L+y13iodqvb8leL53bTannOrQ/Im7UkpsmFU5Ily5U60LWixnmLg==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.14.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint/core/-/core-0.14.0.tgz", + "integrity": "sha512-qIbV0/JZr7iSDjqAc60IqbLdsj9GDt16xQtWD+B78d/HAlvysGdZZ6rpJHGAc2T0FQx1X6thsSPdnoiGKdNtdg==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint/eslintrc/-/eslintrc-3.3.1.tgz", + "integrity": "sha512-gtF186CXhIl1p4pJNGZw8Yc6RlshoePRvE0X91oPGb3vZ8pM3qOS9W9NGPat9LziaBV7XrJWGylNQXkGcnM3IQ==", + "dev": true, + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://repo.huaweicloud.com/repository/npm/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "9.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint/js/-/js-9.28.0.tgz", + "integrity": "sha512-fnqSjGWd/CoIp4EXIxWVK/sHA6DOHN4+8Ix2cX5ycOY7LG0UY8nHCU5pIp2eaE1Mc7Qd8kHspYNzYXT2ojPLzg==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint/object-schema/-/object-schema-2.1.6.tgz", + "integrity": "sha512-RBMg5FRL0I0gs51M/guSAj5/e14VQ4tpZnQNWwuDT66P14I43ItmPfIZRhO9fUVIPOAQXU47atlywZ/czoqFPA==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@eslint/plugin-kit/-/plugin-kit-0.3.1.tgz", + "integrity": "sha512-0J+zgWxHN+xXONWIyPWKFMgVuJoZuGiIFu8yxk7RJjxkzpGmyja5wRFqZIVtjDVOQpV+Rw0iOAjYPE2eQyjr0w==", + "dev": true, + "dependencies": { + "@eslint/core": "^0.14.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/@humanfs/node/-/node-0.16.6.tgz", + "integrity": "sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==", + "dev": true, + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.3.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node/node_modules/@humanwhocodes/retry": { + "version": "0.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@humanwhocodes/retry/-/retry-0.3.1.tgz", + "integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==", + "dev": true, + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/@jridgewell/gen-mapping/-/gen-mapping-0.3.8.tgz", + "integrity": "sha512-imAbBGkb+ebQyxKgzv5Hu2nmROxoDOXHh80evxdoXNOrvAnVx7zimzc1Oo5h9RlfV4vPXaE2iM5pOFbvOCClWA==", + "dev": true, + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/@jridgewell/source-map/-/source-map-0.3.6.tgz", + "integrity": "sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://repo.huaweicloud.com/repository/npm/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@pkgr/core": { + "version": "0.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@pkgr/core/-/core-0.1.2.tgz", + "integrity": "sha512-fdDH1LSGfZdTH2sxdpVMw31BanV28K/Gry0cVFxaNP77neJSkd82mM8ErPNYs9e+0O7SdHBLTDzDgwUuy18RnQ==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + } + }, + "node_modules/@rtsao/scc": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rtsao/scc/-/scc-1.1.0.tgz", + "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", + "dev": true + }, + "node_modules/@stylistic/eslint-plugin": { + "version": "4.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@stylistic/eslint-plugin/-/eslint-plugin-4.4.1.tgz", + "integrity": "sha512-CEigAk7eOLyHvdgmpZsKFwtiqS2wFwI1fn4j09IU9GmD4euFM4jEBAViWeCqaNLlbX2k2+A/Fq9cje4HQBXuJQ==", + "dev": true, + "dependencies": { + "@typescript-eslint/utils": "^8.32.1", + "eslint-visitor-keys": "^4.2.0", + "espree": "^10.3.0", + "estraverse": "^5.3.0", + "picomatch": "^4.0.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "peerDependencies": { + "eslint": ">=9.0.0" + } + }, + "node_modules/@types/eslint": { + "version": "9.6.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/eslint/-/eslint-9.6.1.tgz", + "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==", + "dev": true, + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "node_modules/@types/eslint-scope": { + "version": "3.7.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/eslint-scope/-/eslint-scope-3.7.7.tgz", + "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==", + "dev": true, + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true + }, + "node_modules/@types/json5": { + "version": "0.0.29", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "dev": true + }, + "node_modules/@types/node": { + "version": "18.11.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/node/-/node-18.11.7.tgz", + "integrity": "sha512-LhFTglglr63mNXUSRYD8A+ZAIu5sFqNJ4Y2fPuY7UlrySJH87rRRlhtVmMHplmfk5WkoJGmDjE9oiTfyX94CpQ==", + "dev": true + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.33.1.tgz", + "integrity": "sha512-TDCXj+YxLgtvxvFlAvpoRv9MAncDLBV2oT9Bd7YBGC/b/sEURoOYuIwLI99rjWOfY3QtDzO+mk0n4AmdFExW8A==", + "dev": true, + "dependencies": { + "@eslint-community/regexpp": "^4.10.0", + "@typescript-eslint/scope-manager": "8.33.1", + "@typescript-eslint/type-utils": "8.33.1", + "@typescript-eslint/utils": "8.33.1", + "@typescript-eslint/visitor-keys": "8.33.1", + "graphemer": "^1.4.0", + "ignore": "^7.0.0", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.33.1", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/parser/-/parser-8.33.1.tgz", + "integrity": "sha512-qwxv6dq682yVvgKKp2qWwLgRbscDAYktPptK4JPojCwwi3R9cwrvIxS4lvBpzmcqzR4bdn54Z0IG1uHFskW4dA==", + "dev": true, + "dependencies": { + "@typescript-eslint/scope-manager": "8.33.1", + "@typescript-eslint/types": "8.33.1", + "@typescript-eslint/typescript-estree": "8.33.1", + "@typescript-eslint/visitor-keys": "8.33.1", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/project-service/-/project-service-8.33.1.tgz", + "integrity": "sha512-DZR0efeNklDIHHGRpMpR5gJITQpu6tLr9lDJnKdONTC7vvzOlLAG/wcfxcdxEWrbiZApcoBCzXqU/Z458Za5Iw==", + "dev": true, + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.33.1", + "@typescript-eslint/types": "^8.33.1", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/scope-manager/-/scope-manager-8.33.1.tgz", + "integrity": "sha512-dM4UBtgmzHR9bS0Rv09JST0RcHYearoEoo3pG5B6GoTR9XcyeqX87FEhPo+5kTvVfKCvfHaHrcgeJQc6mrDKrA==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "8.33.1", + "@typescript-eslint/visitor-keys": "8.33.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.33.1.tgz", + "integrity": "sha512-STAQsGYbHCF0/e+ShUQ4EatXQ7ceh3fBCXkNU7/MZVKulrlq1usH7t2FhxvCpuCi5O5oi1vmVaAjrGeL71OK1g==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/type-utils/-/type-utils-8.33.1.tgz", + "integrity": "sha512-1cG37d9xOkhlykom55WVwG2QRNC7YXlxMaMzqw2uPeJixBFfKWZgaP/hjAObqMN/u3fr5BrTwTnc31/L9jQ2ww==", + "dev": true, + "dependencies": { + "@typescript-eslint/typescript-estree": "8.33.1", + "@typescript-eslint/utils": "8.33.1", + "debug": "^4.3.4", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/types/-/types-8.33.1.tgz", + "integrity": "sha512-xid1WfizGhy/TKMTwhtVOgalHwPtV8T32MS9MaH50Cwvz6x6YqRIPdD2WvW0XaqOzTV9p5xdLY0h/ZusU5Lokg==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/typescript-estree/-/typescript-estree-8.33.1.tgz", + "integrity": "sha512-+s9LYcT8LWjdYWu7IWs7FvUxpQ/DGkdjZeE/GGulHvv8rvYwQvVaUZ6DE+j5x/prADUgSbbCWZ2nPI3usuVeOA==", + "dev": true, + "dependencies": { + "@typescript-eslint/project-service": "8.33.1", + "@typescript-eslint/tsconfig-utils": "8.33.1", + "@typescript-eslint/types": "8.33.1", + "@typescript-eslint/visitor-keys": "8.33.1", + "debug": "^4.3.4", + "fast-glob": "^3.3.2", + "is-glob": "^4.0.3", + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/utils/-/utils-8.33.1.tgz", + "integrity": "sha512-52HaBiEQUaRYqAXpfzWSR2U3gxk92Kw006+xZpElaPMg3C4PgM+A5LqwoQI1f9E5aZ/qlxAZxzm42WX+vn92SQ==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.7.0", + "@typescript-eslint/scope-manager": "8.33.1", + "@typescript-eslint/types": "8.33.1", + "@typescript-eslint/typescript-estree": "8.33.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@typescript-eslint/visitor-keys/-/visitor-keys-8.33.1.tgz", + "integrity": "sha512-3i8NrFcZeeDHJ+7ZUuDkGT+UHq+XoFGsymNK2jZCOHcfEzRQ0BdpRtdpSx/Iyf3MHLWIcLS0COuOPibKQboIiQ==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "8.33.1", + "eslint-visitor-keys": "^4.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.14.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/ast/-/ast-1.14.1.tgz", + "integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==", + "dev": true, + "dependencies": { + "@webassemblyjs/helper-numbers": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.13.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz", + "integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.13.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz", + "integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.14.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz", + "integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.13.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz", + "integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==", + "dev": true, + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.13.2", + "@webassemblyjs/helper-api-error": "1.13.2", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.13.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz", + "integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.14.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz", + "integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/wasm-gen": "1.14.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.13.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz", + "integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==", + "dev": true, + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.13.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/leb128/-/leb128-1.13.2.tgz", + "integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==", + "dev": true, + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.13.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/utf8/-/utf8-1.13.2.tgz", + "integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==", + "dev": true + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.14.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz", + "integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/helper-wasm-section": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-opt": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1", + "@webassemblyjs/wast-printer": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.14.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz", + "integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.14.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz", + "integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.14.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz", + "integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-api-error": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.14.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz", + "integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webpack-cli/configtest": { + "version": "2.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webpack-cli/configtest/-/configtest-2.1.1.tgz", + "integrity": "sha512-wy0mglZpDSiSS0XHrVR+BAdId2+yxPSoJW8fsna3ZpYSlufjvxnP4YbKTCBZnNIcGN4r6ZPXV55X4mYExOfLmw==", + "dev": true, + "engines": { + "node": ">=14.15.0" + }, + "peerDependencies": { + "webpack": "5.x.x", + "webpack-cli": "5.x.x" + } + }, + "node_modules/@webpack-cli/info": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webpack-cli/info/-/info-2.0.2.tgz", + "integrity": "sha512-zLHQdI/Qs1UyT5UBdWNqsARasIA+AaF8t+4u2aS2nEpBQh2mWIVb8qAklq0eUENnC5mOItrIB4LiS9xMtph18A==", + "dev": true, + "engines": { + "node": ">=14.15.0" + }, + "peerDependencies": { + "webpack": "5.x.x", + "webpack-cli": "5.x.x" + } + }, + "node_modules/@webpack-cli/serve": { + "version": "2.0.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/@webpack-cli/serve/-/serve-2.0.5.tgz", + "integrity": "sha512-lqaoKnRYBdo1UgDX8uF24AfGMifWK19TxPmM5FHc2vAGxrJ/qtyUyFBWoY1tISZdelsQ5fBcOusifo5o5wSJxQ==", + "dev": true, + "engines": { + "node": ">=14.15.0" + }, + "peerDependencies": { + "webpack": "5.x.x", + "webpack-cli": "5.x.x" + }, + "peerDependenciesMeta": { + "webpack-dev-server": { + "optional": true + } + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "2.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "dev": true, + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-formats/node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/are-docs-informative": { + "version": "0.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/are-docs-informative/-/are-docs-informative-0.0.2.tgz", + "integrity": "sha512-ixiS0nLNNG5jNQzgZJNoUpBKdo9yTYZMGJ+QgT2jmjR7G7+QHRCc4v6LQ3NgE7EBJq+o0ams3waJwkrlBom8Ig==", + "dev": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "node_modules/arkanalyzer": { + "resolved": "arkanalyzer", + "link": true + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-includes": { + "version": "3.1.9", + "resolved": "https://repo.huaweicloud.com/repository/npm/array-includes/-/array-includes-3.1.9.tgz", + "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.0", + "es-object-atoms": "^1.1.1", + "get-intrinsic": "^1.3.0", + "is-string": "^1.1.1", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlastindex": { + "version": "1.2.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", + "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-shim-unscopables": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flat": { + "version": "1.3.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz", + "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz", + "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "dev": true, + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.25.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/browserslist/-/browserslist-4.25.0.tgz", + "integrity": "sha512-PJ8gYKeS5e/whHBh8xrwYK+dAvEj7JXtz6uTucnMRB8OiGTsKccFekoRrjajPBHV8oOY+2tI4uxeceSimKwMFA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "caniuse-lite": "^1.0.30001718", + "electron-to-chromium": "^1.5.160", + "node-releases": "^2.0.19", + "update-browserslist-db": "^1.1.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/call-bind": { + "version": "1.0.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/call-bind/-/call-bind-1.0.8.tgz", + "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==", + "dev": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.0", + "es-define-property": "^1.0.0", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001721", + "resolved": "https://repo.huaweicloud.com/repository/npm/caniuse-lite/-/caniuse-lite-1.0.30001721.tgz", + "integrity": "sha512-cOuvmUVtKrtEaoKiO0rSc29jcjwMwX5tOHDy4MgVFEWiUXj4uBMJkwI8MDySkgXidpMiHUcviogAvFi4pA2hDQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ] + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", + "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", + "dev": true, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/clone-deep": { + "version": "4.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/clone-deep/-/clone-deep-4.0.1.tgz", + "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", + "dev": true, + "dependencies": { + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.2", + "shallow-clone": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://repo.huaweicloud.com/repository/npm/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "dev": true + }, + "node_modules/commander": { + "version": "9.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/commander/-/commander-9.5.0.tgz", + "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", + "inBundle": true, + "engines": { + "node": "^12.20.0 || >=14" + } + }, + "node_modules/comment-parser": { + "version": "1.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/comment-parser/-/comment-parser-1.4.1.tgz", + "integrity": "sha512-buhp5kePrmda3vhc5B9t7pUQXAb2Tnd0qgpkIhPhkHXxJpiPJ11H0ZEU0oBpJ2QztSbzG/ZxMj/CHsYJqRHmyg==", + "dev": true, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/date-format": { + "version": "4.0.14", + "resolved": "https://repo.huaweicloud.com/repository/npm/date-format/-/date-format-4.0.14.tgz", + "integrity": "sha512-39BOQLs9ZjKh0/patS9nrT8wc3ioX3/eA/zgbKNopnF2wCqJEoxywwwElATYvRsXdnOxA/OQeQoFZ3rFjVajhg==", + "inBundle": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/debug": { + "version": "4.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "inBundle": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true + }, + "node_modules/electron-to-chromium": { + "version": "1.5.165", + "resolved": "https://repo.huaweicloud.com/repository/npm/electron-to-chromium/-/electron-to-chromium-1.5.165.tgz", + "integrity": "sha512-naiMx1Z6Nb2TxPU6fiFrUrDTjyPMLdTtaOd2oLmG8zVSg2hCWGkhPyxwk+qRmZ1ytwVqUv0u7ZcDA5+ALhaUtw==", + "dev": true + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true + }, + "node_modules/enhanced-resolve": { + "version": "5.18.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/enhanced-resolve/-/enhanced-resolve-5.18.1.tgz", + "integrity": "sha512-ZSW3ma5GkcQBIpwZTSRAI8N71Uuwgs93IezB7mf7R60tC8ZbJideoDNKjHn2O9KIlx6rkGTTEk1xUCK2E1Y2Yg==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/envinfo": { + "version": "7.14.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/envinfo/-/envinfo-7.14.0.tgz", + "integrity": "sha512-CO40UI41xDQzhLB1hWyqUKgFhs250pNcGbyGKe1l/e4FSaI/+YE4IMG76GDt0In67WLPACIITC+sOi08x4wIvg==", + "dev": true, + "bin": { + "envinfo": "dist/cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/es-abstract": { + "version": "1.24.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/es-abstract/-/es-abstract-1.24.0.tgz", + "integrity": "sha512-WSzPgsdLtTcQwm4CROfS5ju2Wa1QQcVeT37jFjYzdFz1r9ahadC8B8/a4qxJxM+09F18iumCdRmlr96ZYkQvEg==", + "dev": true, + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-shim-unscopables": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz", + "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==", + "dev": true, + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/es-to-primitive/-/es-to-primitive-1.3.0.tgz", + "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==", + "dev": true, + "dependencies": { + "is-callable": "^1.2.7", + "is-date-object": "^1.0.5", + "is-symbol": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint/-/eslint-9.28.0.tgz", + "integrity": "sha512-ocgh41VhRlf9+fVpe7QKzwLj9c92fDiqOj8Y3Sd4/ZmVA4Btx4PlUYPq4pp9JDyupkf1upbEXecxL2mwNV7jPQ==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.20.0", + "@eslint/config-helpers": "^0.2.1", + "@eslint/core": "^0.14.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.28.0", + "@eslint/plugin-kit": "^0.3.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "@types/json-schema": "^7.0.15", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.3.0", + "eslint-visitor-keys": "^4.2.0", + "espree": "^10.3.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-compat-utils": { + "version": "0.5.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-compat-utils/-/eslint-compat-utils-0.5.1.tgz", + "integrity": "sha512-3z3vFexKIEnjHE3zCMRo6fn/e44U7T1khUjg+Hp0ZQMCigh28rALD0nPFBcGZuiLC5rLZa2ubQHDRln09JfU2Q==", + "dev": true, + "dependencies": { + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "eslint": ">=6.0.0" + } + }, + "node_modules/eslint-import-resolver-node": { + "version": "0.3.9", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", + "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "dev": true, + "dependencies": { + "debug": "^3.2.7", + "is-core-module": "^2.13.0", + "resolve": "^1.22.4" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-module-utils": { + "version": "2.12.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-module-utils/-/eslint-module-utils-2.12.0.tgz", + "integrity": "sha512-wALZ0HFoytlyh/1+4wuZ9FJCD/leWHQzzrxJ8+rebyReSLk7LApMyd3WJaLVoN+D5+WIdJyDK1c6JnE65V4Zyg==", + "dev": true, + "dependencies": { + "debug": "^3.2.7" + }, + "engines": { + "node": ">=4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-es-x": { + "version": "7.8.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-plugin-es-x/-/eslint-plugin-es-x-7.8.0.tgz", + "integrity": "sha512-7Ds8+wAAoV3T+LAKeu39Y5BzXCrGKrcISfgKEqTS4BDN8SFEDQd0S43jiQ8vIa3wUKD07qitZdfzlenSi8/0qQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/ota-meshi", + "https://opencollective.com/eslint" + ], + "dependencies": { + "@eslint-community/eslint-utils": "^4.1.2", + "@eslint-community/regexpp": "^4.11.0", + "eslint-compat-utils": "^0.5.1" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "eslint": ">=8" + } + }, + "node_modules/eslint-plugin-import": { + "version": "2.31.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-plugin-import/-/eslint-plugin-import-2.31.0.tgz", + "integrity": "sha512-ixmkI62Rbc2/w8Vfxyh1jQRTdRTF52VxwRVHl/ykPAmqG+Nb7/kNn+byLP0LxPgI7zWA16Jt82SybJInmMia3A==", + "dev": true, + "dependencies": { + "@rtsao/scc": "^1.1.0", + "array-includes": "^3.1.8", + "array.prototype.findlastindex": "^1.2.5", + "array.prototype.flat": "^1.3.2", + "array.prototype.flatmap": "^1.3.2", + "debug": "^3.2.7", + "doctrine": "^2.1.0", + "eslint-import-resolver-node": "^0.3.9", + "eslint-module-utils": "^2.12.0", + "hasown": "^2.0.2", + "is-core-module": "^2.15.1", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.8", + "object.groupby": "^1.0.3", + "object.values": "^1.2.0", + "semver": "^6.3.1", + "string.prototype.trimend": "^1.0.8", + "tsconfig-paths": "^3.15.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9" + } + }, + "node_modules/eslint-plugin-import/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://repo.huaweicloud.com/repository/npm/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/eslint-plugin-import/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-plugin-jsdoc": { + "version": "48.11.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-48.11.0.tgz", + "integrity": "sha512-d12JHJDPNo7IFwTOAItCeJY1hcqoIxE0lHA8infQByLilQ9xkqrRa6laWCnsuCrf+8rUnvxXY1XuTbibRBNylA==", + "dev": true, + "dependencies": { + "@es-joy/jsdoccomment": "~0.46.0", + "are-docs-informative": "^0.0.2", + "comment-parser": "1.4.1", + "debug": "^4.3.5", + "escape-string-regexp": "^4.0.0", + "espree": "^10.1.0", + "esquery": "^1.6.0", + "parse-imports": "^2.1.1", + "semver": "^7.6.3", + "spdx-expression-parse": "^4.0.0", + "synckit": "^0.9.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^7.0.0 || ^8.0.0 || ^9.0.0" + } + }, + "node_modules/eslint-plugin-n": { + "version": "17.19.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-plugin-n/-/eslint-plugin-n-17.19.0.tgz", + "integrity": "sha512-qxn1NaDHtizbhVAPpbMT8wWFaLtPnwhfN/e+chdu2i6Vgzmo/tGM62tcJ1Hf7J5Ie4dhse3DOPMmDxduzfifzw==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.5.0", + "@typescript-eslint/utils": "^8.26.1", + "enhanced-resolve": "^5.17.1", + "eslint-plugin-es-x": "^7.8.0", + "get-tsconfig": "^4.8.1", + "globals": "^15.11.0", + "ignore": "^5.3.2", + "minimatch": "^9.0.5", + "semver": "^7.6.3", + "ts-declaration-location": "^1.0.6" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": ">=8.23.0" + } + }, + "node_modules/eslint-plugin-n/node_modules/globals": { + "version": "15.15.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/globals/-/globals-15.15.0.tgz", + "integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint-plugin-no-null": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-plugin-no-null/-/eslint-plugin-no-null-1.0.2.tgz", + "integrity": "sha512-uRDiz88zCO/2rzGfgG15DBjNsgwWtWiSo4Ezy7zzajUgpnFIqd1TjepKeRmJZHEfBGu58o2a8S0D7vglvvhkVA==", + "dev": true, + "engines": { + "node": ">=5.0.0" + }, + "peerDependencies": { + "eslint": ">=3.0.0" + } + }, + "node_modules/eslint-scope": { + "version": "8.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-scope/-/eslint-scope-8.3.0.tgz", + "integrity": "sha512-pUNxi75F8MJ/GdeKtVLSbYg4ZI34J6C0C7sbL4YOp2exGwen7ZsuBqKzUhXd0qMQ362yET3z+uPwKeg/0C2XCQ==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", + "integrity": "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://repo.huaweicloud.com/repository/npm/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/espree": { + "version": "10.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/espree/-/espree-10.3.0.tgz", + "integrity": "sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg==", + "dev": true, + "dependencies": { + "acorn": "^8.14.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true + }, + "node_modules/fast-uri": { + "version": "3.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/fast-uri/-/fast-uri-3.0.6.tgz", + "integrity": "sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ] + }, + "node_modules/fastest-levenshtein": { + "version": "1.0.16", + "resolved": "https://repo.huaweicloud.com/repository/npm/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", + "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==", + "dev": true, + "engines": { + "node": ">= 4.9.1" + } + }, + "node_modules/fastq": { + "version": "1.19.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/fastq/-/fastq-1.19.1.tgz", + "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", + "dev": true, + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat": { + "version": "5.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/flat/-/flat-5.0.2.tgz", + "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", + "dev": true, + "bin": { + "flat": "cli.js" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "inBundle": true + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "dev": true, + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fs-extra": { + "version": "11.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/fs-extra/-/fs-extra-11.2.0.tgz", + "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/function.prototype.name/-/function.prototype.name-1.1.8.tgz", + "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "functions-have-names": "^1.2.3", + "hasown": "^2.0.2", + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-tsconfig": { + "version": "4.10.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/get-tsconfig/-/get-tsconfig-4.10.1.tgz", + "integrity": "sha512-auHyJ4AgMz7vgS8Hp3N6HXSmlMdUyhSUrfBF16w153rxtLIEOE+HGqaBppczZvnHLqQJfiHotCYpNhl0lUROFQ==", + "dev": true, + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/glob": { + "version": "11.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/glob/-/glob-11.0.2.tgz", + "integrity": "sha512-YT7U7Vye+t5fZ/QMkBFrTJ7ZQxInIUjwyAjVj84CYXqgBdv30MFUPGnBR6sQaVq6Is15wYJUsnzTuWaGRBhBAQ==", + "dev": true, + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^4.0.1", + "minimatch": "^10.0.0", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true + }, + "node_modules/glob/node_modules/minimatch": { + "version": "10.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-10.0.1.tgz", + "integrity": "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://repo.huaweicloud.com/repository/npm/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "inBundle": true + }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "dev": true, + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/homecheck": { + "resolved": "homecheck", + "link": true + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-local": { + "version": "3.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/import-local/-/import-local-3.2.0.tgz", + "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", + "dev": true, + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/interpret": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/interpret/-/interpret-1.4.0.tgz", + "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==", + "dev": true, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "dev": true, + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-generator-function/-/is-generator-function-1.1.0.tgz", + "integrity": "sha512-nPUB5km40q9e8UfN/Zc24eLlzdSf9OfKByBw9CIdw4H1giPMeA0OIJvbchsCu4npfI2QcMVBsGEBHKZ7wLTWmQ==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "get-proto": "^1.0.0", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-plain-object": { + "version": "2.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "dev": true, + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/isobject": { + "version": "3.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jackspeak": { + "version": "4.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/jackspeak/-/jackspeak-4.1.1.tgz", + "integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==", + "dev": true, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsdoc-type-pratt-parser": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-4.0.0.tgz", + "integrity": "sha512-YtOli5Cmzy3q4dP26GraSOeAhqecewG04hoO8DY56CH4KJ9Fvv5qKWUCCo3HZob7esJQHCv6/+bnTy72xZZaVQ==", + "dev": true, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/loader-runner": { + "version": "4.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/loader-runner/-/loader-runner-4.3.0.tgz", + "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", + "dev": true, + "engines": { + "node": ">=6.11.5" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true + }, + "node_modules/log4js": { + "version": "6.9.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/log4js/-/log4js-6.9.1.tgz", + "integrity": "sha512-1somDdy9sChrr9/f4UlzhdaGfDR2c/SaD2a4T7qEkG4jTS57/B3qmnjLYePwQ8cqWnUHZI0iAKxMBpCZICiZ2g==", + "inBundle": true, + "dependencies": { + "date-format": "^4.0.14", + "debug": "^4.3.4", + "flatted": "^3.2.7", + "rfdc": "^1.3.0", + "streamroller": "^3.1.5" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/lru-cache": { + "version": "11.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/lru-cache/-/lru-cache-11.1.0.tgz", + "integrity": "sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A==", + "dev": true, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://repo.huaweicloud.com/repository/npm/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "inBundle": true + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true + }, + "node_modules/node-releases": { + "version": "2.0.19", + "resolved": "https://repo.huaweicloud.com/repository/npm/node-releases/-/node-releases-2.0.19.tgz", + "integrity": "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==", + "dev": true + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.fromentries": { + "version": "2.0.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.fromentries/-/object.fromentries-2.0.8.tgz", + "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.groupby": { + "version": "1.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.groupby/-/object.groupby-1.0.3.tgz", + "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.values": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.values/-/object.values-1.2.1.tgz", + "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/own-keys": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/own-keys/-/own-keys-1.0.1.tgz", + "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.2.6", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-imports": { + "version": "2.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/parse-imports/-/parse-imports-2.2.1.tgz", + "integrity": "sha512-OL/zLggRp8mFhKL0rNORUTR4yBYujK/uU+xZL+/0Rgm2QE4nLO9v8PzEweSJEbMGKmDRjJE4R3IMJlL2di4JeQ==", + "dev": true, + "dependencies": { + "es-module-lexer": "^1.5.3", + "slashes": "^3.0.12" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/path-scurry": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "dev": true, + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/picomatch": { + "version": "4.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/picomatch/-/picomatch-4.0.2.tgz", + "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pkg-dir/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "3.5.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/prettier/-/prettier-3.5.3.tgz", + "integrity": "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/property-expr": { + "version": "2.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/property-expr/-/property-expr-2.0.6.tgz", + "integrity": "sha512-SVtmxhRE/CGkn3eZY1T6pC8Nln6Fr/lu1mKSgRud0eC73whjGfoAogbn78LkD8aFL0zz3bAFerKSnOl7NlErBA==" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/rechoir": { + "version": "0.6.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/rechoir/-/rechoir-0.6.2.tgz", + "integrity": "sha512-HFM8rkZ+i3zrV+4LQjwQ0W+ez98pApMGM3HUrN04j3CqzPOzl9nmP15Y8YXNm8QHGv/eacOVEjqhmWpkRV0NAw==", + "dev": true, + "dependencies": { + "resolve": "^1.1.6" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://repo.huaweicloud.com/repository/npm/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.10", + "resolved": "https://repo.huaweicloud.com/repository/npm/resolve/-/resolve-1.22.10.tgz", + "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "dev": true, + "dependencies": { + "is-core-module": "^2.16.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-cwd/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "inBundle": true + }, + "node_modules/rimraf": { + "version": "5.0.10", + "resolved": "https://repo.huaweicloud.com/repository/npm/rimraf/-/rimraf-5.0.10.tgz", + "integrity": "sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==", + "dev": true, + "dependencies": { + "glob": "^10.3.7" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/glob": { + "version": "10.4.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "dev": true, + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/rimraf/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true + }, + "node_modules/rimraf/node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/safe-array-concat/-/safe-array-concat-1.1.3.tgz", + "integrity": "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/schema-utils": { + "version": "4.3.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/schema-utils/-/schema-utils-4.3.2.tgz", + "integrity": "sha512-Gn/JaSk/Mt9gYubxTtSn/QCV4em9mpAPiR1rqy/Ocu19u/G9J5WWdNoUT4SiV6mFC3y6cxyFcFwdzPM3FgxGAQ==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.9.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/schema-utils/node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/schema-utils/node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/schema-utils/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", + "dev": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "dev": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/shallow-clone": { + "version": "3.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", + "dev": true, + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/shelljs": { + "version": "0.8.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/shelljs/-/shelljs-0.8.5.tgz", + "integrity": "sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow==", + "dev": true, + "dependencies": { + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" + }, + "bin": { + "shjs": "bin/shjs" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/shelljs/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://repo.huaweicloud.com/repository/npm/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/shelljs/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/shelljs/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slashes": { + "version": "3.0.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/slashes/-/slashes-3.0.12.tgz", + "integrity": "sha512-Q9VME8WyGkc7pJf6QEkj3wE+2CnvZMI+XJhwdTPR8Z/kWQRXi7boAWLDibRPyHRTUTPx5FaU7MsyrjI3yLB4HA==", + "dev": true + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://repo.huaweicloud.com/repository/npm/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", + "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", + "dev": true + }, + "node_modules/spdx-expression-parse": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/spdx-expression-parse/-/spdx-expression-parse-4.0.0.tgz", + "integrity": "sha512-Clya5JIij/7C6bRR22+tnGXbc4VKlibKSVj2iHvVeX5iMW7s1SIQlqu699JkODJJIhh/pUu8L0/VLh8xflD+LQ==", + "dev": true, + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.21", + "resolved": "https://repo.huaweicloud.com/repository/npm/spdx-license-ids/-/spdx-license-ids-3.0.21.tgz", + "integrity": "sha512-Bvg/8F5XephndSK3JffaRqdT+gyhfqIPwDHpX80tJrF8QQRYMo8sNMeaZ2Dp5+jhwKnUmIOyFFQfHRkjJm5nXg==", + "dev": true + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/streamroller": { + "version": "3.1.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/streamroller/-/streamroller-3.1.5.tgz", + "integrity": "sha512-KFxaM7XT+irxvdqSP1LGLgNWbYN7ay5owZ3r/8t77p+EtSUAfUgtl7be3xtqtOmGUl9K9YPO2ca8133RlTjvKw==", + "inBundle": true, + "dependencies": { + "date-format": "^4.0.14", + "debug": "^4.3.4", + "fs-extra": "^8.1.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/streamroller/node_modules/fs-extra": { + "version": "8.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "inBundle": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, + "node_modules/streamroller/node_modules/jsonfile": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", + "inBundle": true, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/streamroller/node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "inBundle": true, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.10", + "resolved": "https://repo.huaweicloud.com/repository/npm/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz", + "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-object-atoms": "^1.0.0", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.9", + "resolved": "https://repo.huaweicloud.com/repository/npm/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz", + "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/synckit": { + "version": "0.9.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/synckit/-/synckit-0.9.3.tgz", + "integrity": "sha512-JJoOEKTfL1urb1mDoEblhD9NhEbWmq9jHEMEnxoC4ujUaZ4itA8vKgwkFAyNClgxplLi9tsUKX+EduK0p/l7sg==", + "dev": true, + "dependencies": { + "@pkgr/core": "^0.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + } + }, + "node_modules/tapable": { + "version": "2.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/tapable/-/tapable-2.2.2.tgz", + "integrity": "sha512-Re10+NauLTMCudc7T5WLFLAwDhQ0JWdrMK+9B2M8zR5hRExKmsRDCBA7/aV/pNJFltmBFO5BAMlQFi/vq3nKOg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/terser": { + "version": "5.42.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/terser/-/terser-5.42.0.tgz", + "integrity": "sha512-UYCvU9YQW2f/Vwl+P0GfhxJxbUGLwd+5QrrGgLajzWAtC/23AX0vcise32kkP7Eu0Wu9VlzzHAXkLObgjQfFlQ==", + "dev": true, + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.14.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.3.14", + "resolved": "https://repo.huaweicloud.com/repository/npm/terser-webpack-plugin/-/terser-webpack-plugin-5.3.14.tgz", + "integrity": "sha512-vkZjpUjb6OMS7dhV+tILUW6BhpDR7P2L/aQSAv+Uwk+m8KATX9EccViHTJR2qDtACKPIYndLGCyl3FMo+r2LMw==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "jest-worker": "^27.4.5", + "schema-utils": "^4.3.0", + "serialize-javascript": "^6.0.2", + "terser": "^5.31.1" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/terser/node_modules/commander": { + "version": "2.20.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "node_modules/tiny-case": { + "version": "1.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/tiny-case/-/tiny-case-1.0.3.tgz", + "integrity": "sha512-Eet/eeMhkO6TX8mnUteS9zgPbUMQa4I6Kkp5ORiBD5476/m+PIRiumP5tmh5ioJpH7k51Kehawy2UDfsnxxY8Q==" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toposort": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/toposort/-/toposort-2.0.2.tgz", + "integrity": "sha512-0a5EOkAUp8D4moMi2W8ZF8jcga7BgZd91O/yabJCFY8az+XSzeGyTKs0Aoo897iV1Nj6guFq8orWDS96z91oGg==" + }, + "node_modules/ts-api-utils": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/ts-api-utils/-/ts-api-utils-2.1.0.tgz", + "integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==", + "dev": true, + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/ts-declaration-location": { + "version": "1.0.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/ts-declaration-location/-/ts-declaration-location-1.0.7.tgz", + "integrity": "sha512-EDyGAwH1gO0Ausm9gV6T2nUvBgXT5kGoCMJPllOaooZ+4VvJiKBdZE7wK18N1deEowhcUptS+5GXZK8U/fvpwA==", + "dev": true, + "funding": [ + { + "type": "ko-fi", + "url": "https://ko-fi.com/rebeccastevens" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/ts-declaration-location" + } + ], + "dependencies": { + "picomatch": "^4.0.2" + }, + "peerDependencies": { + "typescript": ">=4.0.0" + } + }, + "node_modules/tsconfig-paths": { + "version": "3.15.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", + "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", + "dev": true, + "dependencies": { + "@types/json5": "^0.0.29", + "json5": "^1.0.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + } + }, + "node_modules/tsconfig-paths/node_modules/json5": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "dev": true, + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "2.19.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/type-fest/-/type-fest-2.19.0.tgz", + "integrity": "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz", + "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==", + "dev": true, + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.9" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/typed-array-length/-/typed-array-length-1.0.7.tgz", + "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "is-typed-array": "^1.1.13", + "possible-typed-array-names": "^1.0.0", + "reflect.getprototypeof": "^1.0.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "5.8.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/typescript/-/typescript-5.8.3.tgz", + "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", + "dev": true, + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.33.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/typescript-eslint/-/typescript-eslint-8.33.1.tgz", + "integrity": "sha512-AgRnV4sKkWOiZ0Kjbnf5ytTJXMUZQ0qhSVdQtDNYLPLnjsATEYhaO94GlRQwi4t4gO8FfjM6NnikHeKjUm8D7A==", + "dev": true, + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.33.1", + "@typescript-eslint/parser": "8.33.1", + "@typescript-eslint/utils": "8.33.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <5.9.0" + } + }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.1.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz", + "integrity": "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/watchpack": { + "version": "2.4.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/watchpack/-/watchpack-2.4.4.tgz", + "integrity": "sha512-c5EGNOiyxxV5qmTtAB7rbiXxi1ooX1pQKMLX/MIabJjRA0SJBQOjKF+KSVfHkr9U1cADPon0mRiVe/riyaiDUA==", + "dev": true, + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack": { + "version": "5.99.9", + "resolved": "https://repo.huaweicloud.com/repository/npm/webpack/-/webpack-5.99.9.tgz", + "integrity": "sha512-brOPwM3JnmOa+7kd3NsmOUOwbDAj8FT9xDsG3IW0MgbN9yZV7Oi/s/+MNQ/EcSMqw7qfoRyXPoeEWT8zLVdVGg==", + "dev": true, + "dependencies": { + "@types/eslint-scope": "^3.7.7", + "@types/estree": "^1.0.6", + "@types/json-schema": "^7.0.15", + "@webassemblyjs/ast": "^1.14.1", + "@webassemblyjs/wasm-edit": "^1.14.1", + "@webassemblyjs/wasm-parser": "^1.14.1", + "acorn": "^8.14.0", + "browserslist": "^4.24.0", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.17.1", + "es-module-lexer": "^1.2.1", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.11", + "json-parse-even-better-errors": "^2.3.1", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^4.3.2", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.3.11", + "watchpack": "^2.4.1", + "webpack-sources": "^3.2.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-cli": { + "version": "5.1.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/webpack-cli/-/webpack-cli-5.1.4.tgz", + "integrity": "sha512-pIDJHIEI9LR0yxHXQ+Qh95k2EvXpWzZ5l+d+jIo+RdSm9MiHfzazIxwwni/p7+x4eJZuvG1AJwgC4TNQ7NRgsg==", + "dev": true, + "dependencies": { + "@discoveryjs/json-ext": "^0.5.0", + "@webpack-cli/configtest": "^2.1.1", + "@webpack-cli/info": "^2.0.2", + "@webpack-cli/serve": "^2.0.5", + "colorette": "^2.0.14", + "commander": "^10.0.1", + "cross-spawn": "^7.0.3", + "envinfo": "^7.7.3", + "fastest-levenshtein": "^1.0.12", + "import-local": "^3.0.2", + "interpret": "^3.1.1", + "rechoir": "^0.8.0", + "webpack-merge": "^5.7.3" + }, + "bin": { + "webpack-cli": "bin/cli.js" + }, + "engines": { + "node": ">=14.15.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "5.x.x" + }, + "peerDependenciesMeta": { + "@webpack-cli/generators": { + "optional": true + }, + "webpack-bundle-analyzer": { + "optional": true + }, + "webpack-dev-server": { + "optional": true + } + } + }, + "node_modules/webpack-cli/node_modules/commander": { + "version": "10.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "dev": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/webpack-cli/node_modules/interpret": { + "version": "3.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/interpret/-/interpret-3.1.1.tgz", + "integrity": "sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==", + "dev": true, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack-cli/node_modules/rechoir": { + "version": "0.8.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/rechoir/-/rechoir-0.8.0.tgz", + "integrity": "sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==", + "dev": true, + "dependencies": { + "resolve": "^1.20.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/webpack-merge": { + "version": "5.10.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/webpack-merge/-/webpack-merge-5.10.0.tgz", + "integrity": "sha512-+4zXKdx7UnO+1jaN4l2lHVD+mFvnlZQP/6ljaJVb4SZiwIKeUnrT5l0gkT8z+n4hKpC+jpOv6O9R+gLtag7pSA==", + "dev": true, + "dependencies": { + "clone-deep": "^4.0.1", + "flat": "^5.0.2", + "wildcard": "^2.0.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/webpack-sources": { + "version": "3.3.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/webpack-sources/-/webpack-sources-3.3.2.tgz", + "integrity": "sha512-ykKKus8lqlgXX/1WjudpIEjqsafjOTcOJqxnAbMLAu/KCsDCJ6GBtvscewvTkrn24HsnvFwrSCbenFrhtcCsAA==", + "dev": true, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack/node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/webpack/node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "dev": true, + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.19", + "resolved": "https://repo.huaweicloud.com/repository/npm/which-typed-array/-/which-typed-array-1.1.19.tgz", + "integrity": "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==", + "dev": true, + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/wildcard": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/wildcard/-/wildcard-2.0.1.tgz", + "integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==", + "dev": true + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yup": { + "version": "1.6.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/yup/-/yup-1.6.1.tgz", + "integrity": "sha512-JED8pB50qbA4FOkDol0bYF/p60qSEDQqBD0/qeIrUCG1KbPBIQ776fCUNb9ldbPcSTxA69g/47XTo4TqWiuXOA==", + "dependencies": { + "property-expr": "^2.0.5", + "tiny-case": "^1.0.3", + "toposort": "^2.0.2", + "type-fest": "^2.19.0" + } + } + } +} diff --git a/ets2panda/linter/package.json b/ets2panda/linter/package.json index 7b374c9944..9a8bd6eb74 100644 --- a/ets2panda/linter/package.json +++ b/ets2panda/linter/package.json @@ -40,15 +40,22 @@ "eslint-check": "npx eslint .", "eslint-fix": "npm run eslint-check -- --fix", "prettier-fix": "npx prettier --write .", - "fix": "npm run prettier-fix && npm run eslint-fix" + "fix": "npm run prettier-fix && npm run eslint-fix", + "coverage": "npm run coverage-prepare && npm run coverage-instrument && npm run coverage-test && npm run coverage-collect && npm run coverage-report", + "coverage-prepare": "npm run build && node scripts/testRunner/coverage_prepare.js", + "coverage-instrument": "nyc --compact false instrument build coverage/build_instrument", + "coverage-test": "node coverage/build_instrument/testRunner/TestRunner.js -d test/main,test/rules,test/regression,test/extended_features,test/migration,test/ohmurl,test/interop,test/sdkwhite,test/concurrent,test/builtin", + "coverage-collect": "node scripts/testRunner/coverage_collect.js", + "coverage-report": "node scripts/testRunner/coverage_report.js" }, "dependencies": { "commander": "^9.4.0", + "fs-extra": "11.2.0", "homecheck": "file:./homecheck", + "json5": "2.2.3", "log4js": "^6.4.0", - "yup": "^1.4.0", - "fs-extra": "11.2.0", - "json5": "2.2.3" + "readline-sync": "^1.4.10", + "yup": "^1.4.0" }, "devDependencies": { "@eslint/compat": "latest", @@ -61,10 +68,12 @@ "eslint-plugin-n": "^17.9.0", "eslint-plugin-no-null": "^1.0.2", "glob": "^11.0.0", + "nyc": "^15.1.0", "path-scurry": "^2.0.0", "prettier": "latest", "rimraf": "^5.0.10", "shelljs": "^0.8.5", + "source-map": "^0.7.4", "typescript-eslint": "latest", "webpack": "^5.75.0", "webpack-cli": "^5.0.1" diff --git a/ets2panda/linter/scripts/testRunner/coverage_collect.js b/ets2panda/linter/scripts/testRunner/coverage_collect.js new file mode 100644 index 0000000000..c5a918cb5c --- /dev/null +++ b/ets2panda/linter/scripts/testRunner/coverage_collect.js @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 fs = require('fs'); +const sourceMap = require('source-map'); +const path = require('path'); + +const PROJECT_ROOT = path.join(__dirname, '..', '..'); +const COVERAGE_DIR = path.join(PROJECT_ROOT, 'coverage'); +const COVERAGE_FILE = path.join(COVERAGE_DIR, 'coverage.json'); +const NEW_COVERAGE_FILE = path.join(COVERAGE_DIR, 'newCoverage.json'); + +/** + * Processes statement map data using source map consumer + * @param {Object} statementMap - Statement map data + * @param {Object} consumer - Source map consumer + */ +function processStatementMap(statementMap, consumer) { + for (const id in statementMap) { + const statement = statementMap[id]; + const startPos = consumer.originalPositionFor(statement.start); + const endPos = consumer.originalPositionFor(statement.end); + + statement.start = { line: startPos.line, column: startPos.column }; + statement.end = { line: endPos.line, column: endPos.column }; + } +} + +/** + * Processes function map data using source map consumer + * @param {Object} functionMap - Function map data + * @param {Object} consumer - Source map consumer + */ +function processFunctionMap(functionMap, consumer) { + for (const id in functionMap) { + const func = functionMap[id]; + + const declStart = consumer.originalPositionFor(func.decl.start); + const declEnd = consumer.originalPositionFor(func.decl.end); + const locStart = consumer.originalPositionFor(func.loc.start); + const locEnd = consumer.originalPositionFor(func.loc.end); + + func.decl = { + start: { line: declStart.line, column: declStart.column }, + end: { line: declEnd.line, column: declEnd.column } + }; + + func.loc = { + start: { line: locStart.line, column: locStart.column }, + end: { line: locEnd.line, column: locEnd.column } + }; + + func.line = declStart.line; + } +} + +/** + * Processes branch map data using source map consumer + * @param {Object} branchMap - Branch map data + * @param {Object} consumer - Source map consumer + */ +function processBranchMap(branchMap, consumer) { + for (const id in branchMap) { + const branch = branchMap[id]; + + // Process locations + branch.locations.forEach(location => { + const startPos = consumer.originalPositionFor(location.start); + const endPos = consumer.originalPositionFor(location.end); + + location.start = { line: startPos.line, column: startPos.column }; + location.end = { line: endPos.line, column: endPos.column }; + }); + + // Process loc + const locStart = consumer.originalPositionFor(branch.loc.start); + const locEnd = consumer.originalPositionFor(branch.loc.end); + + branch.loc = { + start: { line: locStart.line, column: locStart.column }, + end: { line: locEnd.line, column: locEnd.column } + }; + + branch.line = locStart.line; + } +} + +/** + * Collects and processes coverage data using source maps + */ +async function collectCoverage() { + if (!fs.existsSync(COVERAGE_FILE)) { + throw new Error(`Coverage file not found: ${COVERAGE_FILE}`); + } + + const coverageData = JSON.parse(fs.readFileSync(COVERAGE_FILE, 'utf8')); + const newCoverageData = {}; + + for (const file in coverageData) { + const mapFile = `${file}.map`; + + if (!fs.existsSync(mapFile)) { + console.warn(`Source map not found for: ${file}`); + continue; + } + + const sourceMapData = JSON.parse(fs.readFileSync(mapFile, 'utf8')); + const sources = sourceMapData.sources; + const newFile = path.join(path.dirname(mapFile), sources[0]); + + await sourceMap.SourceMapConsumer.with(sourceMapData, null, (consumer) => { + const fileCoverage = { ...coverageData[file] }; + fileCoverage.path = newFile; + + processStatementMap(fileCoverage.statementMap, consumer); + processFunctionMap(fileCoverage.functionMap, consumer); + processBranchMap(fileCoverage.branchMap, consumer); + + newCoverageData[newFile] = fileCoverage; + }); + } + + fs.writeFileSync( + NEW_COVERAGE_FILE, + JSON.stringify(newCoverageData, null, 4) + ); +} + +// Execute and handle errors +collectCoverage() + .then(() => console.log('Coverage collection completed successfully')) + .catch(error => { + console.error('Error collecting coverage:', error); + process.exit(1); + }); \ No newline at end of file diff --git a/ets2panda/linter/scripts/testRunner/coverage_prepare.js b/ets2panda/linter/scripts/testRunner/coverage_prepare.js new file mode 100644 index 0000000000..2a746b4b09 --- /dev/null +++ b/ets2panda/linter/scripts/testRunner/coverage_prepare.js @@ -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. + */ + +const fs = require('fs'); +const path = require('path'); + +const projectRoot = path.join(__dirname, '..', '..'); +const buildDir = path.join(projectRoot, 'build'); +const coverageDir = path.join(projectRoot, 'coverage'); +const buildInstrumentDir = path.join(coverageDir, 'build_instrument'); + +function copyDirectory(src, dest) { + fs.mkdirSync(dest, { recursive: true }); + + const entries = fs.readdirSync(src, { withFileTypes: true }); + + for (const entry of entries) { + const srcPath = path.join(src, entry.name); + const destPath = path.join(dest, entry.name); + + if (entry.isDirectory()) { + copyDirectory(srcPath, destPath); + } else { + fs.copyFileSync(srcPath, destPath); + } + } +} + +function prepareCoverage() { + try { + if (fs.existsSync(coverageDir)) { + fs.rmSync(coverageDir, { recursive: true, force: true }); + } + + fs.mkdirSync(coverageDir, { recursive: true }); + fs.mkdirSync(buildInstrumentDir, { recursive: true }); + + copyDirectory(buildDir, buildInstrumentDir); + + const dataDir = path.join(projectRoot, 'src', 'data'); + const instrumentDataDir = path.join(buildInstrumentDir, 'data'); + + if (fs.existsSync(dataDir)) { + copyDirectory(dataDir, instrumentDataDir); + } + } catch (error) { + console.error('Error during coverage preparation:', error); + process.exit(1); + } +} + +prepareCoverage(); \ No newline at end of file diff --git a/ets2panda/linter/scripts/testRunner/coverage_report.js b/ets2panda/linter/scripts/testRunner/coverage_report.js new file mode 100644 index 0000000000..84fa3219d0 --- /dev/null +++ b/ets2panda/linter/scripts/testRunner/coverage_report.js @@ -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. + */ + +const fs = require('fs'); +const path = require('path'); +const libCoverage = require('istanbul-lib-coverage'); +const libReport = require('istanbul-lib-report'); +const reports = require('istanbul-reports'); + +const projectRoot = path.join(__dirname, '..', '..'); +const coverageDir = path.join(projectRoot, 'coverage'); + +const coverageFile = fs.readFileSync(path.join(coverageDir, 'newCoverage.json'), 'utf8'); +const coverageData = JSON.parse(coverageFile); +const coverageMap = libCoverage.createCoverageMap(coverageData); + +// create summary report +const summary = libCoverage.createCoverageSummary(); +coverageMap.files().forEach(file => { + const fc = coverageMap.fileCoverageFor(file); + const s = fc.toSummary(); + summary.merge(s); +}); +console.log(summary); + +// Watermarks for the report +const configWatermarks = { + statements: [50, 80], + branches: [50, 80], + functions: [50, 80], + lines: [50, 80], +}; +const context = libReport.createContext({ + dir: path.join(coverageDir, 'report-html'), + defaultSummarizer: 'nested', + watermarks: configWatermarks, + coverageMap, +}); + +const report = reports.create('html', {}); +report.execute(context); + +const report_text = reports.create('text', {}); +report_text.execute(context); \ No newline at end of file diff --git a/ets2panda/linter/src/cli/CommandLineParser.ts b/ets2panda/linter/src/cli/CommandLineParser.ts index 9849eedf17..d3b948c5e7 100644 --- a/ets2panda/linter/src/cli/CommandLineParser.ts +++ b/ets2panda/linter/src/cli/CommandLineParser.ts @@ -13,15 +13,18 @@ * limitations under the License. */ -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'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import * as ts from 'typescript'; +import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import { cookBookTag } from '../lib/CookBookMsg'; +import { Logger } from '../lib/Logger'; +import { ARKTS_IGNORE_DIRS_OH_MODULES } from '../lib/utils/consts/ArktsIgnorePaths'; +import { getConfiguredRuleTags, getRulesFromConfig } from '../lib/utils/functions/ConfiguredRulesProcess'; +import { extractRuleTags } from '../lib/utils/functions/CookBookUtils'; +import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic'; const TS_EXT = '.ts'; const TSX_EXT = '.tsx'; @@ -132,7 +135,10 @@ function formIdeInteractive(cmdOptions: CommandLineOptions, commanderOpts: Optio cmdOptions.linterOptions.checkTsAndJs = true; } if (commanderOpts.onlyArkts2SyntaxRules) { - cmdOptions.onlySyntax = true; + cmdOptions.linterOptions.onlySyntax = true; + } + if (commanderOpts.autofixCheck) { + cmdOptions.linterOptions.autofixCheck = true; } } @@ -159,7 +165,9 @@ function formArkts2Options(cmdOptions: CommandLineOptions, commanderOpts: Option function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { const opts: CommandLineOptions = { - inputFiles: parsedCmd.args.inputFiles, + inputFiles: parsedCmd.args.inputFiles.map((file) => { + return path.normalize(file); + }), linterOptions: { useRtLogic: true, interopCheckMode: false @@ -177,6 +185,7 @@ function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { } if (options.projectFolder) { doProjectFolderArg(options.projectFolder, opts); + opts.linterOptions.projectFolderList = options.projectFolder; } if (options.project) { doProjectArg(options.project, opts); @@ -190,6 +199,7 @@ function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { if (options.useRtLogic !== undefined) { opts.linterOptions.useRtLogic = options.useRtLogic; } + processRuleConfig(opts, options); formIdeInteractive(opts, options); formSdkOptions(opts, options); formMigrateOptions(opts, options); @@ -197,6 +207,19 @@ function formCommandLineOptions(parsedCmd: ParsedCommand): CommandLineOptions { return opts; } +function processRuleConfig(commandLineOptions: CommandLineOptions, options: OptionValues): void { + if (options.ruleConfig !== undefined) { + const stats = fs.statSync(path.normalize(options.ruleConfig)); + if (!stats.isFile()) { + console.error(`The file at ${options.ruleConfigPath} path does not exist!`); + } else { + const configuredRulesMap = getRulesFromConfig(options.ruleConfig); + const arkTSRulesMap = extractRuleTags(cookBookTag); + commandLineOptions.linterOptions.ruleConfigTags = getConfiguredRuleTags(arkTSRulesMap, configuredRulesMap); + } + } +} + function createCommand(): Command { const program = new Command(); program. @@ -233,6 +256,8 @@ function createCommand(): Command { option('-o, --output-file-path ', 'path to store all log and result files'). option('--verbose', 'set log level to see debug messages'). option('--enable-interop', 'scan whole project to report 1.1 import 1.2'). + option('--rule-config ', 'Path to the rule configuration file'). + option('--autofix-check', 'confirm whether the user needs automatic repair'). 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 5af05d0e31..447a2358d1 100644 --- a/ets2panda/linter/src/cli/LinterCLI.ts +++ b/ets2panda/linter/src/cli/LinterCLI.ts @@ -13,20 +13,25 @@ * limitations under the License. */ +import { MigrationTool } from 'homecheck'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; +import * as readlineSync from 'readline-sync'; import * as readline from 'node:readline'; import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import { getHomeCheckConfigInfo, transferIssues2ProblemInfo } from '../lib/HomeCheck'; import { lint } from '../lib/LinterRunner'; import { Logger } from '../lib/Logger'; import type { ProblemInfo } from '../lib/ProblemInfo'; -import { parseCommandLine } from './CommandLineParser'; -import { compileLintOptions, getEtsLoaderPath } from '../lib/ts-compiler/Compiler'; +import * as statistic from '../lib/statistics/scan/ProblemStatisticsCommonFunction'; +import type { ScanTaskRelatedInfo } from '../lib/statistics/scan/ScanTaskRelatedInfo'; +import { StatisticsReportInPutInfo } from '../lib/statistics/scan/StatisticsReportInPutInfo'; +import { TimeRecorder } from '../lib/statistics/scan/TimeRecorder'; import { logStatistics } from '../lib/statistics/StatisticsLogger'; -import { arkts2Rules, onlyArkts2SyntaxRules } from '../lib/utils/consts/ArkTS2Rules'; -import { MigrationTool } from 'homecheck'; -import { getHomeCheckConfigInfo, transferIssues2ProblemInfo } from '../lib/HomeCheck'; +import { compileLintOptions, getEtsLoaderPath } from '../lib/ts-compiler/Compiler'; +import { processSyncErr, processSyncOut } from '../lib/utils/functions/ProcessWrite'; +import { parseCommandLine } from './CommandLineParser'; export function run(): void { const commandLineArgs = process.argv.slice(2); @@ -36,6 +41,13 @@ export function run(): void { } const cmdOptions = parseCommandLine(commandLineArgs); + if (cmdOptions.linterOptions.migratorMode && cmdOptions.linterOptions.autofixCheck) { + const shouldRun = readlineSync.question('Do you want to run the linter and apply migration? (y/n): ').toLowerCase(); + if (shouldRun !== 'y') { + console.log('Linting canceled by user.'); + process.exit(0); + } + } if (cmdOptions.devecoPluginModeDeprecated) { runIdeModeDeprecated(cmdOptions); @@ -43,7 +55,7 @@ export function run(): void { runIdeInteractiveMode(cmdOptions); } else { const compileOptions = compileLintOptions(cmdOptions); - const result = lint(compileOptions); + const result = lint(compileOptions, new TimeRecorder()); logStatistics(result.projectStats); process.exit(result.hasErrors ? 1 : 0); } @@ -52,36 +64,28 @@ export function run(): void { async function runIdeInteractiveMode(cmdOptions: CommandLineOptions): Promise { cmdOptions.followSdkSettings = true; cmdOptions.disableStrictDiagnostics = true; + const timeRecorder = new TimeRecorder(); + const scanTaskRelatedInfo = {} as ScanTaskRelatedInfo; const compileOptions = compileLintOptions(cmdOptions); - let homeCheckResult = new Map(); - const mergedProblems = new Map(); - - if (cmdOptions.linterOptions.arkts2 && cmdOptions.homecheck) { - const { ruleConfigInfo, projectConfigInfo } = getHomeCheckConfigInfo(cmdOptions); - let migrationTool: MigrationTool | null = new MigrationTool(ruleConfigInfo, projectConfigInfo); - await migrationTool.buildCheckEntry(); - const result = await migrationTool.start(); - migrationTool = null; - - homeCheckResult = transferIssues2ProblemInfo(result); - for (const [filePath, problems] of homeCheckResult) { - if (!mergedProblems.has(filePath)) { - mergedProblems.set(filePath, []); - } - mergedProblems.get(filePath)!.push(...problems); - } - } - - if (!cmdOptions.skipLinter) { - const result = lint(compileOptions, getEtsLoaderPath(compileOptions), homeCheckResult); - for (const [filePath, problems] of result.problemsInfos) { - mergeLintProblems(filePath, problems, mergedProblems, cmdOptions); - } + scanTaskRelatedInfo.cmdOptions = cmdOptions; + scanTaskRelatedInfo.timeRecorder = timeRecorder; + scanTaskRelatedInfo.compileOptions = compileOptions; + await executeScanTask(scanTaskRelatedInfo); + + const statisticsReportInPutInfo = scanTaskRelatedInfo.statisticsReportInPutInfo; + statisticsReportInPutInfo.statisticsReportName = 'scan-problems-statistics.json'; + statisticsReportInPutInfo.totalProblemNumbers = getTotalProblemNumbers(scanTaskRelatedInfo.mergedProblems); + statisticsReportInPutInfo.cmdOptions = cmdOptions; + statisticsReportInPutInfo.timeRecorder = timeRecorder; + + if (!cmdOptions.linterOptions.migratorMode && statisticsReportInPutInfo.cmdOptions.linterOptions.projectFolderList) { + await statistic.generateScanProbelemStatisticsReport(statisticsReportInPutInfo); } + const mergedProblems = scanTaskRelatedInfo.mergedProblems; const reportData = Object.fromEntries(mergedProblems); - await generateReportFile(reportData, cmdOptions.outputFilePath); - + const reportName: string = 'scan-report.json'; + await statistic.generateReportFile(reportName, reportData, cmdOptions.outputFilePath); for (const [filePath, problems] of mergedProblems) { const reportLine = JSON.stringify({ filePath, problems }) + '\n'; await processSyncOut(reportLine); @@ -90,6 +94,79 @@ async function runIdeInteractiveMode(cmdOptions: CommandLineOptions): Promise): number { + let totalProblemNumbers: number = 0; + for (const problems of mergedProblems.values()) { + totalProblemNumbers += problems.length; + } + return totalProblemNumbers; +} + +async function executeScanTask(scanTaskRelatedInfo: ScanTaskRelatedInfo): Promise { + const cmdOptions = scanTaskRelatedInfo.cmdOptions; + scanTaskRelatedInfo.statisticsReportInPutInfo = new StatisticsReportInPutInfo(); + scanTaskRelatedInfo.statisticsReportInPutInfo.ruleToNumbersMap = new Map(); + scanTaskRelatedInfo.statisticsReportInPutInfo.ruleToAutoFixedNumbersMap = new Map(); + scanTaskRelatedInfo.mergedProblems = new Map(); + if (cmdOptions.linterOptions.arkts2 && cmdOptions.homecheck) { + await executeHomeCheckTask(scanTaskRelatedInfo); + } + + if (!cmdOptions.skipLinter) { + executeLintTask(scanTaskRelatedInfo); + } +} + +async function executeHomeCheckTask(scanTaskRelatedInfo: ScanTaskRelatedInfo): Promise { + const cmdOptions = scanTaskRelatedInfo.cmdOptions; + const { ruleConfigInfo, projectConfigInfo } = getHomeCheckConfigInfo(cmdOptions); + let migrationTool: MigrationTool | null = new MigrationTool(ruleConfigInfo, projectConfigInfo); + await migrationTool.buildCheckEntry(); + scanTaskRelatedInfo.timeRecorder.startScan(); + scanTaskRelatedInfo.timeRecorder.setHomeCheckCountStatus(true); + const result = await migrationTool.start(); + migrationTool = null; + scanTaskRelatedInfo.homeCheckResult = transferIssues2ProblemInfo(result); + for (const [filePath, problems] of scanTaskRelatedInfo.homeCheckResult) { + if (!scanTaskRelatedInfo.mergedProblems.has(filePath)) { + scanTaskRelatedInfo.mergedProblems.set(filePath, []); + } + statistic.accumulateRuleNumbers( + problems, + scanTaskRelatedInfo.statisticsReportInPutInfo.ruleToNumbersMap, + scanTaskRelatedInfo.statisticsReportInPutInfo.ruleToAutoFixedNumbersMap + ); + scanTaskRelatedInfo.statisticsReportInPutInfo.arkOnePointOneProblemNumbers += + statistic.getArktsOnePointOneProlemNumbers(problems); + scanTaskRelatedInfo.mergedProblems.get(filePath)!.push(...problems); + } +} + +function executeLintTask(scanTaskRelatedInfo: ScanTaskRelatedInfo): void { + const cmdOptions = scanTaskRelatedInfo.cmdOptions; + const compileOptions = scanTaskRelatedInfo.compileOptions; + const homeCheckResult = scanTaskRelatedInfo.homeCheckResult; + if (!scanTaskRelatedInfo.timeRecorder.getHomeCheckCountStatus()) { + scanTaskRelatedInfo.timeRecorder.startScan(); + } + const result = lint( + compileOptions, + scanTaskRelatedInfo.timeRecorder, + getEtsLoaderPath(compileOptions), + homeCheckResult + ); + for (const [filePath, problems] of result.problemsInfos) { + statistic.accumulateRuleNumbers( + problems, + scanTaskRelatedInfo.statisticsReportInPutInfo.ruleToNumbersMap, + scanTaskRelatedInfo.statisticsReportInPutInfo.ruleToAutoFixedNumbersMap + ); + scanTaskRelatedInfo.statisticsReportInPutInfo.arkOnePointOneProblemNumbers += + statistic.getArktsOnePointOneProlemNumbers(problems); + mergeLintProblems(filePath, problems, scanTaskRelatedInfo.mergedProblems, cmdOptions); + } +} + function mergeLintProblems( filePath: string, problems: ProblemInfo[], @@ -100,16 +177,6 @@ function mergeLintProblems( mergedProblems.set(filePath, []); } let filteredProblems = problems; - if (cmdOptions.linterOptions.arkts2) { - filteredProblems = problems.filter((problem) => { - return arkts2Rules.includes(problem.ruleTag); - }); - } - if (cmdOptions.onlySyntax) { - filteredProblems = problems.filter((problem) => { - return onlyArkts2SyntaxRules.has(problem.ruleTag); - }); - } mergedProblems.get(filePath)!.push(...filteredProblems); if (cmdOptions.scanWholeProjectInHomecheck) { @@ -133,35 +200,6 @@ function mergeLintProblems( } } -async function generateReportFile(reportData, reportPath?: string): Promise { - let reportFilePath = path.join('scan-report.json'); - if (reportPath !== undefined) { - reportFilePath = path.join(path.normalize(reportPath), 'scan-report.json'); - } - try { - await fs.promises.mkdir(path.dirname(reportFilePath), { recursive: true }); - 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, () => { - resolve('success'); - }); - }); -} - -async function processSyncErr(message: string): Promise { - await new Promise((resolve) => { - process.stderr.write(message, () => { - resolve('success'); - }); - }); -} - function getTempFileName(): string { return path.join(os.tmpdir(), Math.floor(Math.random() * 10000000).toString() + '_linter_tmp_file.ts'); } @@ -204,7 +242,7 @@ function runIdeModeDeprecated(cmdOptions: CommandLineOptions): void { cmdOptions.parsedConfigFile.fileNames.push(tmpFileName); } const compileOptions = compileLintOptions(cmdOptions); - const result = lint(compileOptions); + const result = lint(compileOptions, new TimeRecorder()); const problems = Array.from(result.problemsInfos.values()); if (problems.length === 1) { showJSONMessage(problems); diff --git a/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts b/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts index e1e433013c..cb711335e4 100644 --- a/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/BaseTypeScriptLinter.ts @@ -26,6 +26,7 @@ import { faultsAttrs } from './FaultAttrs'; import { cookBookTag } from './CookBookMsg'; import { FaultID } from './Problems'; import { ProblemSeverity } from './ProblemSeverity'; +import { arkts2Rules, onlyArkts2SyntaxRules } from './utils/consts/ArkTS2Rules'; export abstract class BaseTypeScriptLinter { problemsInfos: ProblemInfo[] = []; @@ -75,18 +76,36 @@ export abstract class BaseTypeScriptLinter { autofix?: Autofix[], errorMsg?: string ): void { + const badNodeInfo = this.getbadNodeInfo(node, faultId, autofix, errorMsg); + + if (this.shouldSkipRule(badNodeInfo)) { + return; + } + + 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); + } + } + + private getbadNodeInfo( + node: ts.Node | ts.CommentRange, + faultId: number, + autofix?: Autofix[], + errorMsg?: string + ): ProblemInfo { 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 = errorMsg ? errorMsg : cookBookTag[cookBookMsgNum]; const severity = faultsAttrs[faultId]?.severity ?? ProblemSeverity.ERROR; const isMsgNumValid = cookBookMsgNum > 0; - autofix = autofix ? BaseTypeScriptLinter.addLineColumnInfoInAutofix(autofix, startPos, endPos) : autofix; + autofix = BaseTypeScriptLinter.processAutofix(autofix, startPos, endPos); const badNodeInfo: ProblemInfo = { line: startPos.line + 1, column: startPos.character + 1, @@ -106,12 +125,32 @@ export abstract class BaseTypeScriptLinter { autofix: autofix, autofixTitle: isMsgNumValid && autofix !== undefined ? cookBookRefToFixTitle.get(cookBookMsgNum) : undefined }; - this.problemsInfos.push(badNodeInfo); - this.updateFileStats(faultId, badNodeInfo.line); + return badNodeInfo; + } - // problems with autofixes might be collected separately - if (this.options.reportAutofixCb && badNodeInfo.autofix) { - this.options.reportAutofixCb(badNodeInfo); + private static processAutofix( + autofix: Autofix[] | undefined, + startPos: ts.LineAndCharacter, + endPos: ts.LineAndCharacter + ): Autofix[] | undefined { + return autofix ? BaseTypeScriptLinter.addLineColumnInfoInAutofix(autofix, startPos, endPos) : autofix; + } + + private shouldSkipRule(badNodeInfo: ProblemInfo): boolean { + const ruleConfigTags = this.options.ruleConfigTags; + if (ruleConfigTags && !ruleConfigTags.has(badNodeInfo.ruleTag)) { + return true; + } + if (this.options?.ideInteractive) { + if (this.options.onlySyntax) { + if (onlyArkts2SyntaxRules.has(badNodeInfo.ruleTag)) { + return false; + } + } else if (this.options.arkts2 && arkts2Rules.includes(badNodeInfo.ruleTag)) { + return false; + } + return true; } + return false; } } diff --git a/ets2panda/linter/src/lib/CommandLineOptions.ts b/ets2panda/linter/src/lib/CommandLineOptions.ts index 1bdde46fae..21ab3de973 100644 --- a/ets2panda/linter/src/lib/CommandLineOptions.ts +++ b/ets2panda/linter/src/lib/CommandLineOptions.ts @@ -27,11 +27,12 @@ export interface CommandLineOptions { arktsWholeProjectPath?: string; skipLinter?: boolean; homecheck?: boolean; - onlySyntax?: boolean; followSdkSettings?: boolean; devecoPluginModeDeprecated?: boolean; disableStrictDiagnostics?: boolean; outputFilePath?: string; verbose?: boolean; scanWholeProjectInHomecheck?: boolean; + ruleConfig?: string; + autofixCheck?: boolean; } diff --git a/ets2panda/linter/src/lib/CookBookMsg.ts b/ets2panda/linter/src/lib/CookBookMsg.ts index 17c0d8899b..512bc0b739 100644 --- a/ets2panda/linter/src/lib/CookBookMsg.ts +++ b/ets2panda/linter/src/lib/CookBookMsg.ts @@ -280,7 +280,7 @@ cookBookTag[270] = 'ArkTS1.2 cannot catch a non Error instance thrown from JS co 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 "@CustomLayout" decorator (arkui-custom-layout-need-add-decorator)'; + 'The Custom component with custom layout capability needs to add the "@CustomLayout" decorator (arkui-custom-layout-need-add-decorator)'; cookBookTag[281] = '"@Prop" decorator is not supported (arkui-no-prop-decorator)'; cookBookTag[282] = '"@StorageProp" decorator is not supported (arkui-no-storageprop-decorator)'; cookBookTag[283] = '"@LocalStorageProp" decorator is not supported (arkui-no-localstorageprop-decorator)'; @@ -315,7 +315,6 @@ cookBookTag[319] = cookBookTag[321] = 'Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)'; 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)'; @@ -352,6 +351,8 @@ 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[352] = + '1.2 Void cannot be combined. OnDestroy/onDisconnect (The return type of the method is now void | Promise) needs to be split into two interfaces. (sdk-ability-asynchronous-lifecycle)'; 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)'; @@ -368,6 +369,10 @@ cookBookTag[376] = 'Not supporting comparison between number type and bigint typ 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)'; +cookBookTag[381] = + 'The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)'; +cookBookTag[382] = + 'Promiseconstructor only supports using resolve (undefined) (arkts-promise-with-void-type-need-undefined-as-resolve-arg)'; 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 07f5587812..9a0e13b638 100644 --- a/ets2panda/linter/src/lib/FaultAttrs.ts +++ b/ets2panda/linter/src/lib/FaultAttrs.ts @@ -222,7 +222,6 @@ 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); @@ -250,6 +249,7 @@ 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.SdkAbilityAsynchronousLifecycle] = new FaultAttributes(352); faultsAttrs[FaultID.LimitedStdLibNoSendableDecorator] = new FaultAttributes(355); faultsAttrs[FaultID.LimitedStdLibNoDoncurrentDecorator] = new FaultAttributes(356); faultsAttrs[FaultID.NoNeedStdlibWorker] = new FaultAttributes(357); @@ -264,3 +264,5 @@ faultsAttrs[FaultID.TsLikeCatchType] = new FaultAttributes(375); faultsAttrs[FaultID.NumericBigintCompare] = new FaultAttributes(376); faultsAttrs[FaultID.NondecimalBigint] = new FaultAttributes(377); faultsAttrs[FaultID.UnsupportOperator] = new FaultAttributes(378); +faultsAttrs[FaultID.StateStylesBlockNeedArrowFunc] = new FaultAttributes(381); +faultsAttrs[FaultID.PromiseVoidNeedResolveArg] = new FaultAttributes(382); \ No newline at end of file diff --git a/ets2panda/linter/src/lib/FaultDesc.ts b/ets2panda/linter/src/lib/FaultDesc.ts index 49646a1965..f1c2603b4f 100644 --- a/ets2panda/linter/src/lib/FaultDesc.ts +++ b/ets2panda/linter/src/lib/FaultDesc.ts @@ -173,7 +173,6 @@ faultDesc[FaultID.ExtendsExpression] = 'Extends Expression'; faultDesc[FaultID.NumericSemantics] = 'Numeric semantics'; faultDesc[FaultID.AnimatableExtendDecoratorTransform] = '"@AnimatableExtend" decorator'; 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'; @@ -229,6 +228,7 @@ faultDesc[FaultID.BuiltinNoCtorFunc] = 'Api is not support ctor-signature and ca faultDesc[FaultID.SharedArrayBufferDeprecated] = 'SharedArrayBuffer is not supported'; faultDesc[FaultID.SetCloneListDeprecated] = 'setCloneList is not supported'; faultDesc[FaultID.SetTransferListDeprecated] = 'setTransferList is not supported'; +faultDesc[FaultID.SdkAbilityAsynchronousLifecycle] = '1.2 Void cannot be combined'; faultDesc[FaultID.LimitedStdLibNoSendableDecorator] = 'Limited stdlib no sendable decorator'; faultDesc[FaultID.LimitedStdLibNoDoncurrentDecorator] = 'Limited stdlib no concurrent decorator'; faultDesc[FaultID.NoNeedStdlibWorker] = 'No need stdlib worker'; @@ -252,3 +252,5 @@ faultDesc[FaultID.LocalStoragePropDecoratorNotSupported] = '"@LocalStorageProp" faultDesc[FaultID.PropFunctionNotSupported] = '"prop" function is not supported'; faultDesc[FaultID.SetAndPropFunctionNotSupported] = '"setAndProp" function is not supported'; faultDesc[FaultID.PropNeedCallMethodForDeepCopy] = 'Deep copy needs to call the specific method'; +faultDesc[FaultID.StateStylesBlockNeedArrowFunc] = 'StateStyles needs arrow function block'; +faultDesc[FaultID.PromiseVoidNeedResolveArg] = 'Promiseconstructor only supports using resolve (undefined)'; diff --git a/ets2panda/linter/src/lib/LintRunResult.ts b/ets2panda/linter/src/lib/LintRunResult.ts index 3397a3941a..9c1519d077 100644 --- a/ets2panda/linter/src/lib/LintRunResult.ts +++ b/ets2panda/linter/src/lib/LintRunResult.ts @@ -15,9 +15,11 @@ import type { ProblemInfo } from './ProblemInfo'; import type { ProjectStatistics } from './statistics/ProjectStatistics'; +import type { TimeRecorder } from './statistics/scan/TimeRecorder'; export interface LintRunResult { hasErrors: boolean; problemsInfos: Map; projectStats: ProjectStatistics; + timeRecorder?: TimeRecorder; } diff --git a/ets2panda/linter/src/lib/LinterOptions.ts b/ets2panda/linter/src/lib/LinterOptions.ts index 72613a4cd1..1d0743b5fb 100644 --- a/ets2panda/linter/src/lib/LinterOptions.ts +++ b/ets2panda/linter/src/lib/LinterOptions.ts @@ -44,6 +44,10 @@ export interface LinterOptions { noMigrationBackupFile?: boolean; migrationReport?: boolean; wholeProjectPath?: string; + projectFolderList?: string[]; checkTsAndJs?: boolean; inputFiles?: string[]; + onlySyntax?: boolean; + ruleConfigTags?: Set; + autofixCheck?: boolean; } diff --git a/ets2panda/linter/src/lib/LinterRunner.ts b/ets2panda/linter/src/lib/LinterRunner.ts index 453731f7bc..863687d554 100644 --- a/ets2panda/linter/src/lib/LinterRunner.ts +++ b/ets2panda/linter/src/lib/LinterRunner.ts @@ -16,6 +16,9 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import * as ts from 'typescript'; +import { processSyncErr } from '../lib/utils/functions/ProcessWrite'; +import * as qEd from './autofixes/QuasiEditor'; +import type { BaseTypeScriptLinter } from './BaseTypeScriptLinter'; import type { CommandLineOptions } from './CommandLineOptions'; import { InteropTypescriptLinter } from './InteropTypescriptLinter'; import type { LinterConfig } from './LinterConfig'; @@ -23,24 +26,24 @@ import type { LinterOptions } from './LinterOptions'; import type { LintRunResult } from './LintRunResult'; import { Logger } from './Logger'; import type { ProblemInfo } from './ProblemInfo'; -import { TypeScriptLinter } from './TypeScriptLinter'; +import { ProjectStatistics } from './statistics/ProjectStatistics'; +import { generateMigrationStatisicsReport } from './statistics/scan/ProblemStatisticsCommonFunction'; +import type { TimeRecorder } from './statistics/scan/TimeRecorder'; +import type { createProgramCallback } from './ts-compiler/Compiler'; +import { compileLintOptions } from './ts-compiler/Compiler'; import { getTscDiagnostics } from './ts-diagnostics/GetTscDiagnostics'; import { transformTscDiagnostics } from './ts-diagnostics/TransformTscDiagnostics'; +import { TypeScriptLinter } from './TypeScriptLinter'; import { ARKTS_IGNORE_DIRS_NO_OH_MODULES, ARKTS_IGNORE_DIRS_OH_MODULES, ARKTS_IGNORE_FILES } from './utils/consts/ArktsIgnorePaths'; +import { EXTNAME_JS, EXTNAME_TS } from './utils/consts/ExtensionName'; import { USE_STATIC } from './utils/consts/InteropAPI'; -import { EXTNAME_TS, EXTNAME_JS } from './utils/consts/ExtensionName'; +import { LibraryTypeCallDiagnosticChecker } from './utils/functions/LibraryTypeCallDiagnosticChecker'; import { mergeArrayMaps } from './utils/functions/MergeArrayMaps'; import { clearPathHelperCache, pathContainsDirectory } from './utils/functions/PathHelper'; -import { LibraryTypeCallDiagnosticChecker } from './utils/functions/LibraryTypeCallDiagnosticChecker'; -import type { createProgramCallback } from './ts-compiler/Compiler'; -import { compileLintOptions } from './ts-compiler/Compiler'; -import * as qEd from './autofixes/QuasiEditor'; -import { ProjectStatistics } from './statistics/ProjectStatistics'; -import type { BaseTypeScriptLinter } from './BaseTypeScriptLinter'; function prepareInputFilesList(cmdOptions: CommandLineOptions): string[] { let inputFiles = cmdOptions.inputFiles.map((x) => { @@ -76,6 +79,7 @@ function prepareInputFilesList(cmdOptions: CommandLineOptions): string[] { export function lint( config: LinterConfig, + timeRecorder: TimeRecorder, etsLoaderPath?: string, hcResults?: Map ): LintRunResult { @@ -83,7 +87,10 @@ export function lint( config.cmdOptions.linterOptions.etsLoaderPath = etsLoaderPath; } const lintResult = lintImpl(config); - return config.cmdOptions.linterOptions.migratorMode ? migrate(config, lintResult, hcResults) : lintResult; + timeRecorder.endScan(); + return config.cmdOptions.linterOptions.migratorMode ? + migrate(config, lintResult, timeRecorder, hcResults) : + lintResult; } function lintImpl(config: LinterConfig): LintRunResult { @@ -129,6 +136,7 @@ function lintFiles( TypeScriptLinter.initGlobals(); InteropTypescriptLinter.initGlobals(); + let fileCount: number = 0; for (const srcFile of srcFiles) { const linter: BaseTypeScriptLinter = !options.interopCheckMode ? @@ -138,6 +146,10 @@ function lintFiles( const problems = linter.problemsInfos; problemsInfos.set(path.normalize(srcFile.fileName), [...problems]); projectStats.fileStats.push(linter.fileStats); + fileCount = fileCount + 1; + if (options.ideInteractive) { + processSyncErr(`{"content":"${srcFile.fileName}","messageType":1,"indicator":${fileCount / srcFiles.length}}\n`); + } } return { @@ -150,8 +162,10 @@ function lintFiles( function migrate( initialConfig: LinterConfig, initialLintResult: LintRunResult, + timeRecorder: TimeRecorder, hcResults?: Map ): LintRunResult { + timeRecorder.startMigration(); let linterConfig = initialConfig; const { cmdOptions } = initialConfig; const updatedSourceTexts: Map = new Map(); @@ -182,6 +196,9 @@ function migrate( fs.writeFileSync(writeFileName, newText); }); + timeRecorder.endMigration(); + generateMigrationStatisicsReport(lintResult, timeRecorder, cmdOptions.outputFilePath); + if (cmdOptions.linterOptions.ideInteractive) { lintResult.problemsInfos = problemsInfosBeforeMigrate; } @@ -209,16 +226,9 @@ function fix( ): 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); - } - } - } + // Apply homecheck fixes first to avoid them being skipped due to conflict with linter autofixes + let mergedProblems: Map = hcResults ?? new Map(); + mergedProblems = mergeArrayMaps(mergedProblems, lintResult.problemsInfos); mergedProblems.forEach((problemInfos, fileName) => { const srcFile = program.getSourceFile(fileName); if (!srcFile) { @@ -231,7 +241,8 @@ function fix( linterConfig.cmdOptions.linterOptions.arkts2 && linterConfig.cmdOptions.inputFiles.includes(fileName) && !hasUseStaticDirective(srcFile) && - linterConfig.cmdOptions.linterOptions.ideInteractive; + linterConfig.cmdOptions.linterOptions.ideInteractive && + !qEd.QuasiEditor.hasAnyAutofixes(problemInfos); // If nothing to fix or don't need to add 'use static', then skip file if (!qEd.QuasiEditor.hasAnyAutofixes(problemInfos) && !needToAddUseStatic) { return; @@ -244,7 +255,9 @@ function fix( linterConfig.cmdOptions.outputFilePath ); updatedSourceTexts.set(fileName, qe.fix(problemInfos, needToAddUseStatic)); - appliedFix = true; + if (!needToAddUseStatic) { + appliedFix = true; + } }); return appliedFix; diff --git a/ets2panda/linter/src/lib/Problems.ts b/ets2panda/linter/src/lib/Problems.ts index e9dd80975f..e00674dce2 100644 --- a/ets2panda/linter/src/lib/Problems.ts +++ b/ets2panda/linter/src/lib/Problems.ts @@ -202,7 +202,6 @@ export enum FaultID { InteropJsObjectTraverseJsInstance, InteropJsObjectCallStaticFunc, InteropJsObjectExport, - InteropArkTs1ObjectExport, DefaultArgsBehindRequiredArgs, LimitedStdLibNoImportConcurrency, MissingSuperCall, @@ -230,6 +229,7 @@ export enum FaultID { SharedArrayBufferDeprecated, SetCloneListDeprecated, SetTransferListDeprecated, + SdkAbilityAsynchronousLifecycle, LimitedStdLibNoSendableDecorator, LimitedStdLibNoDoncurrentDecorator, NoNeedStdlibWorker, @@ -253,6 +253,8 @@ export enum FaultID { PropFunctionNotSupported, SetAndPropFunctionNotSupported, PropNeedCallMethodForDeepCopy, + StateStylesBlockNeedArrowFunc, + PromiseVoidNeedResolveArg, // 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 7a6dd23d96..2ba0b44631 100644 --- a/ets2panda/linter/src/lib/TypeScriptLinter.ts +++ b/ets2panda/linter/src/lib/TypeScriptLinter.ts @@ -19,7 +19,7 @@ import { FaultID } from './Problems'; import { TypeScriptLinterConfig } from './TypeScriptLinterConfig'; import type { Autofix } from './autofixes/Autofixer'; import { Autofixer } from './autofixes/Autofixer'; -import { SYMBOL, SYMBOL_CONSTRUCTOR, TsUtils } from './utils/TsUtils'; +import { PROMISE_METHODS, 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'; @@ -50,7 +50,8 @@ import { SENDABLE_DECORATOR, SENDABLE_DECORATOR_NODES, SENDABLE_FUNCTION_UNSUPPORTED_STAGES_IN_API12, - SENDBALE_FUNCTION_START_VERSION + SENDBALE_FUNCTION_START_VERSION, + TASKPOOL } from './utils/consts/SendableAPI'; import { DEFAULT_COMPATIBLE_SDK_VERSION, DEFAULT_COMPATIBLE_SDK_VERSION_STAGE } from './utils/consts/VersionInfo'; import { forEachNodeInSubtree } from './utils/functions/ForEachNodeInSubtree'; @@ -68,7 +69,9 @@ import { LIMITED_STD_OBJECT_API, LIMITED_STD_PROXYHANDLER_API, LIMITED_STD_REFLECT_API, - MODULE_IMPORTS + MODULE_IMPORTS, + ARKTSUTILS_MODULES, + ARKTSUTILS_LOCKS_MEMBER } from './utils/consts/LimitedStdAPI'; import { SupportedStdCallApiChecker } from './utils/functions/SupportedStdCallAPI'; import { identiferUseInValueContext } from './utils/functions/identiferUseInValueContext'; @@ -140,7 +143,19 @@ import type { ArrayAccess, UncheckedIdentifier } from './utils/consts/RuntimeChe import { NUMBER_LITERAL } from './utils/consts/RuntimeCheckAPI'; import { globalApiAssociatedInfo } from './utils/consts/AssociatedInfo'; import { ARRAY_API_LIST } from './utils/consts/ArraysAPI'; +import { + ABILITY_KIT, + ASYNC_LIFECYCLE_SDK_LIST, + ON_DESTROY, + ON_DISCONNECT, + PROMISE, + SERVICE_EXTENSION_ABILITY, + VOID +} from './utils/consts/AsyncLifecycleSDK'; import { ERROR_PROP_LIST } from './utils/consts/ErrorProp'; +import { D_ETS, D_TS } from './utils/consts/TsSuffix'; +import { arkTsBuiltInTypeName } from './utils/consts/ArkuiImportList'; +import { ERROR_TASKPOOL_PROP_LIST } from './utils/consts/ErrorProp'; interface InterfaceSymbolTypeResult { propNames: string[]; @@ -175,6 +190,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { static literalAsPropertyNameTypeSet: Set; private localApiListItem: ApiListItem | undefined = undefined; static constructorFuncsSet: Set; + static ConstructorIfaceSet: Set; static initGlobals(): void { TypeScriptLinter.sharedModulesCache = new Map(); @@ -268,11 +284,18 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + private static addSdkConstructorIfaceSetData(item: ApiListItem): void { + if (item.api_info.problem === SdkProblem.ConstructorIface) { + TypeScriptLinter.ConstructorIfaceSet.add(item); + } + } + private static initSdkWhitelist(): void { TypeScriptLinter.indexedTypeSet = new Set(); TypeScriptLinter.literalAsPropertyNameTypeSet = new Set(); TypeScriptLinter.constructorFuncsSet = new Set(); const list: ApiList = new ApiList(apiWhiteList); + TypeScriptLinter.ConstructorIfaceSet = new Set(); if (list?.api_list?.length > 0) { for (const item of list.api_list) { if (item.file_path !== '') { @@ -285,6 +308,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { TypeScriptLinter.addSdkliteralAsPropertyNameTypeSetData(item); TypeScriptLinter.addSdkConstructorFuncsSetData(item); TypeScriptLinter.addGlobalApiInfosCollocetionData(item); + TypeScriptLinter.addSdkConstructorIfaceSetData(item); } } } @@ -600,13 +624,24 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + static ifValidObjectLiteralProperty( + prop: ts.ObjectLiteralElementLike, + objLitExpr: ts.ObjectLiteralExpression + ): boolean { + return ( + ts.isPropertyAssignment(prop) || + ts.isShorthandPropertyAssignment(prop) && + (ts.isCallExpression(objLitExpr.parent) || ts.isNewExpression(objLitExpr.parent)) + ); + } + private handleObjectLiteralProperties( objectLiteralType: ts.Type | undefined, objectLiteralExpr: ts.ObjectLiteralExpression ): void { let objLiteralAutofix: Autofix[] | undefined; const invalidProps = objectLiteralExpr.properties.filter((prop) => { - return !ts.isPropertyAssignment(prop); + return !TypeScriptLinter.ifValidObjectLiteralProperty(prop, objectLiteralExpr); }); if ( @@ -635,22 +670,39 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } const arrayLitNode = node as ts.ArrayLiteralExpression; - let emptyContextTypeForArrayLiteral = false; - const arrayLitType = this.tsTypeChecker.getContextualType(arrayLitNode); if (arrayLitType && this.tsUtils.typeContainsSendableClassOrInterface(arrayLitType)) { this.incrementCounters(node, FaultID.SendableObjectInitialization); return; } + this.checkArrayElementsAndReportErrors(node, arrayLitNode, arrayLitType); + + this.handleObjectLiteralAssignmentToClass(arrayLitNode); + } + + private checkArrayElementsAndReportErrors( + node: ts.Node, + arrayLitNode: ts.ArrayLiteralExpression, + arrayLitType: undefined | ts.Type + ): void { + const parent = arrayLitNode.parent; + const arrayLitElements = arrayLitNode.elements; + const arrayElementIsEmpty = arrayLitElements.length === 0; + let emptyContextTypeForArrayLiteral = false; + /* * check that array literal consists of inferrable types * e.g. there is no element which is untyped object literals */ - const arrayLitElements = arrayLitNode.elements; - if (this.options.arkts2 && !arrayLitType && arrayLitElements.length === 0) { + const isPromiseEmptyArray = this.checkPromiseEmptyArray(parent, arrayElementIsEmpty); + const isEmptyArray = this.options.arkts2 && !arrayLitType && arrayElementIsEmpty; + if (isPromiseEmptyArray) { + this.incrementCounters(arrayLitNode, FaultID.NosparseArray); + } else if (isEmptyArray) { this.incrementCounters(node, FaultID.NosparseArray); } + for (const element of arrayLitElements) { const elementContextType = this.tsTypeChecker.getContextualType(element); if (ts.isObjectLiteralExpression(element)) { @@ -672,7 +724,25 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (emptyContextTypeForArrayLiteral) { this.incrementCounters(node, FaultID.ArrayLiteralNoContextType); } - this.handleObjectLiteralAssignmentToClass(arrayLitNode); + } + + private checkPromiseEmptyArray(parent: ts.Node, arrayElementIsEmpty: boolean): boolean { + if (this.options.arkts2 && ts.isCallExpression(parent) && arrayElementIsEmpty) { + const callExpr = parent; + const methodName = TypeScriptLinter.getPromiseMethodName(callExpr.expression); + if (methodName && PROMISE_METHODS.has(methodName)) { + return true; + } + return false; + } + return false; + } + + private static getPromiseMethodName(node: ts.Expression): string | undefined { + if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'Promise') { + return node.name.text; + } + return undefined; } private handleStructDeclaration(node: ts.StructDeclaration): void { @@ -1186,7 +1256,8 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const baseExprSym = this.tsUtils.trueSymbolAtLocation(propertyAccessNode.expression); const baseExprType = this.tsTypeChecker.getTypeAtLocation(propertyAccessNode.expression); this.handleTsInterop(propertyAccessNode, () => { - this.checkInteropForPropertyAccess(propertyAccessNode); + const type = this.tsTypeChecker.getTypeAtLocation(propertyAccessNode.expression); + this.checkUsageOfTsTypes(type, propertyAccessNode.expression); }); this.propertyAccessExpressionForInterop(propertyAccessNode); if (this.isPrototypePropertyAccess(propertyAccessNode, exprSym, baseExprSym, baseExprType)) { @@ -1203,7 +1274,6 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (this.options.advancedClassChecks && this.tsUtils.isClassObjectExpression(propertyAccessNode.expression)) { this.incrementCounters(propertyAccessNode.expression, FaultID.ClassAsObject); } - if (!!baseExprSym && TsUtils.symbolHasEsObjectType(baseExprSym)) { const faultId = this.options.arkts2 ? FaultID.EsValueTypeError : FaultID.EsValueType; this.incrementCounters(propertyAccessNode, faultId); @@ -1303,26 +1373,28 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (methodName !== ISCONCURRENT) { return; } - const moduleSpecifier = this.findModuleSpecifierforDepricatedIsConcurrent(node); - if (!moduleSpecifier || !ts.isStringLiteral(moduleSpecifier)) { + const symbol = this.tsUtils.trueSymbolAtLocation(node.expression); + if (!symbol) { return; } - if ( - TASKPOOL_MODULES.some((moduleName) => { - return TsUtils.removeOrReplaceQuotes(moduleSpecifier.getText(), false) === moduleName; - }) - ) { - this.incrementCounters(node.name, FaultID.IsConcurrentDeprecated); - } - } + if (symbol.name === TASKPOOL) { + const decl = TsUtils.getDeclaration(symbol); - findModuleSpecifierforDepricatedIsConcurrent(node: ts.PropertyAccessExpression): ts.Expression | undefined { - let symbol = this.tsUtils.trueSymbolAtLocation(node.expression); - if (symbol && 'unknown' === symbol.name) { - symbol = this.tsTypeChecker.getSymbolAtLocation(node.expression); + if (!decl) { + return; + } + + const sourceFile = decl.getSourceFile(); + const fileName = path.basename(sourceFile.fileName); + + if ( + TASKPOOL_MODULES.some((moduleName) => { + return fileName.startsWith(moduleName) && (fileName.endsWith(D_TS) || fileName.endsWith(D_ETS)); + }) + ) { + this.incrementCounters(node.name, FaultID.IsConcurrentDeprecated); + } } - const importDecl = ts.findAncestor(TsUtils.getDeclaration(symbol), ts.isImportDeclaration); - return importDecl?.moduleSpecifier; } checkFunctionProperty( @@ -1343,44 +1415,16 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } - private checkInteropForPropertyAccess(pan: ts.PropertyAccessExpression): void { - if (ts.isBinaryExpression(pan.parent)) { - this.checkAssignmentOfPan(pan.parent, pan); - } else { - const type = this.tsTypeChecker.getTypeAtLocation(pan.expression); - this.checkUsageOfTsTypes(type, pan.expression); - } - } - - private checkAssignmentOfPan(binaryExpr: ts.BinaryExpression, pan: ts.PropertyAccessExpression): void { - if (binaryExpr.left !== pan) { - return; - } - - if (binaryExpr.operatorToken.kind !== ts.SyntaxKind.EqualsToken) { - this.incrementCounters(pan, FaultID.InteropDirectAccessToTSTypes); - return; - } - - const rhs = binaryExpr.right; - const lhs = binaryExpr.left as ts.PropertyAccessExpression; - - const autofix = this.autofixer?.fixInteropTsType(binaryExpr, lhs, rhs); - this.incrementCounters(pan, FaultID.InteropDirectAccessToTSTypes, autofix); - } - private checkUsageOfTsTypes(baseType: ts.Type, node: ts.Node): void { - if (this.tsUtils.isStringType(baseType)) { - return; - } - if (this.tsUtils.isStdNumberType(baseType)) { - return; - } - if (this.tsUtils.isStdBooleanType(baseType)) { - return; + const typeString = this.tsTypeChecker.typeToString(baseType); + if ( + TsUtils.isAnyType(baseType) || + TsUtils.isUnknownType(baseType) || + this.tsUtils.isStdFunctionType(baseType) || + typeString === 'symbol' + ) { + this.incrementCounters(node, FaultID.InteropDirectAccessToTSTypes); } - - this.incrementCounters(node, FaultID.InteropDirectAccessToTSTypes); } checkUnionTypes(propertyAccessNode: ts.PropertyAccessExpression): void { @@ -1398,14 +1442,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const typeMap = new Map(); if (commonPropertyType.length === allType.length) { allType.forEach((type) => { - const propertySymbol = this.tsUtils.findProperty(type, propertyAccessNode.name.getText()); - if (propertySymbol?.declarations) { - const propertyType = this.tsTypeChecker.getTypeOfSymbolAtLocation( - propertySymbol, - propertySymbol.declarations[0] - ); - typeMap.set(propertyType, propertyAccessNode.name.getText()); - } + this.handleTypeMember(type, propertyAccessNode.name.getText(), typeMap); }); if (typeMap.size > 1) { this.incrementCounters(propertyAccessNode, FaultID.AvoidUnionTypes); @@ -1413,6 +1450,42 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + private handleTypeMember( + type: ts.Type, + memberName: string, + typeMap: Map + ): void { + const propertySymbol = this.tsUtils.findProperty(type, memberName); + if (!propertySymbol?.declarations) { + return; + } + const propertyType = this.tsTypeChecker.getTypeOfSymbolAtLocation(propertySymbol, propertySymbol.declarations[0]); + const symbol = propertySymbol.valueDeclaration; + if (!symbol) { + return; + } + if (ts.isMethodDeclaration(symbol)) { + const returnType = this.getMethodReturnType(propertySymbol); + typeMap.set(returnType, memberName); + } else { + typeMap.set(propertyType, memberName); + } + } + + private getMethodReturnType(symbol: ts.Symbol): string | undefined { + const declaration = symbol.valueDeclaration ?? (symbol.declarations?.[0] as ts.Node | undefined); + if (!declaration) { + return undefined; + } + const methodType = this.tsTypeChecker.getTypeOfSymbolAtLocation(symbol, declaration); + const signatures = methodType.getCallSignatures(); + if (signatures.length === 0) { + return 'void'; + } + const returnType = signatures[0].getReturnType(); + return this.tsTypeChecker.typeToString(returnType); + } + private handleLiteralAsPropertyName(node: ts.PropertyDeclaration | ts.PropertySignature): void { const propName = node.name; if (!!propName && (ts.isNumericLiteral(propName) || this.options.arkts2 && ts.isStringLiteral(propName))) { @@ -1997,6 +2070,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleNumericBigintCompare(tsBinaryExpr); this.handleArkTSPropertyAccess(tsBinaryExpr); this.handleObjectLiteralAssignmentToClass(tsBinaryExpr); + this.handleAssignmentNotsLikeSmartType(tsBinaryExpr); } private checkInterOpImportJsDataCompare(expr: ts.BinaryExpression): void { @@ -3326,6 +3400,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleMethodInherit(tsMethodDecl); this.handleSdkGlobalApi(tsMethodDecl); this.handleLimitedVoidFunction(tsMethodDecl); + this.checkVoidLifecycleReturn(tsMethodDecl); } private handleLimitedVoidFunction(node: ts.FunctionLikeDeclaration): void { @@ -3390,9 +3465,12 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { continue; } - const baseMethodDecl = baseMethod.declarations?.find((d) => { - return ts.isMethodDeclaration(d) || ts.isMethodSignature(d); - }) as ts.MethodDeclaration | ts.MethodSignature | undefined; + const baseMethodDecl = baseMethod.declarations?.find( + (d) => { + return (ts.isMethodDeclaration(d) || ts.isMethodSignature(d)) && + this.tsTypeChecker.getTypeAtLocation(d.parent) === baseType; + } + ) as ts.MethodDeclaration | ts.MethodSignature; if (!baseMethodDecl) { continue; @@ -3480,6 +3558,10 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const baseReturnType = this.tsTypeChecker.getTypeAtLocation(baseMethod.type); const derivedReturnType = this.tsTypeChecker.getTypeAtLocation(derivedMethod.type); + if (this.isDerivedTypeAssignable(derivedReturnType, baseReturnType)) { + return; + } + if (!this.isTypeAssignable(derivedReturnType, baseReturnType)) { this.incrementCounters(derivedMethod.type, FaultID.MethodInheritRule); } @@ -3518,6 +3600,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { // Checks structural assignability between two types. private isTypeAssignable(fromType: ts.Type, toType: ts.Type): boolean { + if (this.isDerivedTypeAssignable(fromType, toType)) { + return true; + } const fromTypes = this.flattenUnionTypes(fromType); const toTypes = new Set(this.flattenUnionTypes(toType)); @@ -3527,6 +3612,35 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { }); } + private isDerivedTypeAssignable(derivedType: ts.Type, baseType: ts.Type): boolean { + const baseSymbol = baseType.getSymbol(); + const derivedSymbol = derivedType.getSymbol(); + + if (!baseSymbol || !derivedSymbol) { + return false; + } + const baseDeclarations = baseSymbol.getDeclarations(); + const derivedDeclarations = derivedSymbol.getDeclarations(); + + if (!baseDeclarations || !derivedDeclarations) { + return false; + } + const baseTypeNode = baseDeclarations[0]; + const derivedTypeNode = derivedDeclarations[0]; + + if (ts.isClassDeclaration(baseTypeNode) && ts.isClassDeclaration(derivedTypeNode)) { + const baseTypes = this.tsTypeChecker.getTypeAtLocation(derivedTypeNode).getBaseTypes(); + const baseTypesExtends = baseTypes?.some((t) => { + return t === baseType; + }); + if (baseTypesExtends) { + return true; + } + } + + return false; + } + // Converts union types into an array of type strings for easy comparison. private flattenUnionTypes(type: ts.Type): string[] { if (type.isUnion()) { @@ -3670,6 +3784,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (isArkTs2) { this.checkWorkerSymbol(tsIdentSym, node); this.checkCollectionsSymbol(tsIdentSym, node); + this.checkConcurrencySymbol(tsIdentSym, node); } } @@ -3866,15 +3981,34 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { private handleIllegalSymbolUsage(tsIdentifier: ts.Identifier, tsIdentSym: ts.Symbol): void { if (tsIdentSym.flags & ts.SymbolFlags.ValueModule) { this.incrementCounters(tsIdentifier, FaultID.NamespaceAsObject); - } else { - const typeName = tsIdentifier.getText(); - const isWrapperObject = typeName === 'Number' || typeName === 'String' || typeName === 'Boolean'; + return; + } - if (!isWrapperObject) { - const faultId = this.options.arkts2 ? FaultID.ClassAsObjectError : FaultID.ClassAsObject; - this.incrementCounters(tsIdentifier, faultId); + const typeName = tsIdentifier.getText(); + const isWrapperObject = typeName === 'Number' || typeName === 'String' || typeName === 'Boolean'; + if (isWrapperObject) { + return; + } + + // Special-case element-access cast for autofix: (X as object)["prop"] + const asExpr = tsIdentifier.parent; + let elemAccess: ts.ElementAccessExpression | undefined; + + if ( + ts.isAsExpression(asExpr) && + ts.isParenthesizedExpression(asExpr.parent) && + ts.isElementAccessExpression(asExpr.parent.parent) && + ts.isStringLiteral(asExpr.parent.parent.argumentExpression) + ) { + // only care if it’s literally “as object” && static-class casts + if (asExpr.type.getText() === 'object' && tsIdentSym.flags & ts.SymbolFlags.Class) { + elemAccess = asExpr.parent.parent; } } + + const autofix = elemAccess ? this.autofixer?.fixPropertyAccessByIndex(elemAccess) : undefined; + const faultId = this.options.arkts2 ? FaultID.ClassAsObjectError : FaultID.ClassAsObject; + this.incrementCounters(tsIdentifier, faultId, autofix); } private isElementAcessAllowed(type: ts.Type, argType: ts.Type): boolean { @@ -3910,12 +4044,33 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { private handleElementAccessExpression(node: ts.Node): void { const tsElementAccessExpr = node as ts.ElementAccessExpression; - const tsElementAccessExprSymbol = this.tsUtils.trueSymbolAtLocation(tsElementAccessExpr.expression); const tsElemAccessBaseExprType = this.tsUtils.getNonNullableType( this.tsUtils.getTypeOrTypeConstraintAtLocation(tsElementAccessExpr.expression) ); const tsElemAccessArgType = this.tsTypeChecker.getTypeAtLocation(tsElementAccessExpr.argumentExpression); + if (this.tsUtils.hasEsObjectType(tsElementAccessExpr.expression)) { + const faultId = this.options.arkts2 ? FaultID.EsValueTypeError : FaultID.EsValueType; + this.incrementCounters(node, faultId); + } + if (this.tsUtils.isOrDerivedFrom(tsElemAccessBaseExprType, this.tsUtils.isIndexableArray)) { + this.handleIndexNegative(node); + } + this.checkPropertyAccessByIndex(tsElementAccessExpr, tsElemAccessBaseExprType, tsElemAccessArgType); + this.checkArrayUsageWithoutBound(tsElementAccessExpr); + this.checkArrayIndexType(tsElemAccessBaseExprType, tsElemAccessArgType, tsElementAccessExpr); + this.fixJsImportElementAccessExpression(tsElementAccessExpr); + this.checkInterOpImportJsIndex(tsElementAccessExpr); + this.checkEnumGetMemberValue(tsElementAccessExpr); + } + + private checkPropertyAccessByIndex( + tsElementAccessExpr: ts.ElementAccessExpression, + tsElemAccessBaseExprType: ts.Type, + tsElemAccessArgType: ts.Type + ): void { + const tsElementAccessExprSymbol = this.tsUtils.trueSymbolAtLocation(tsElementAccessExpr.expression); + const isSet = TsUtils.isSetExpression(tsElementAccessExpr); const isSetIndexable = isSet && @@ -3930,28 +4085,37 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if ( // unnamed types do not have symbol, so need to check that explicitly - !this.tsUtils.isLibrarySymbol(tsElementAccessExprSymbol) && - !ts.isArrayLiteralExpression(tsElementAccessExpr.expression) && - !this.isElementAcessAllowed(tsElemAccessBaseExprType, tsElemAccessArgType) && - !(this.options.arkts2 && isGetIndexable) && - !(this.options.arkts2 && isSetIndexable) + this.tsUtils.isLibrarySymbol(tsElementAccessExprSymbol) || + ts.isArrayLiteralExpression(tsElementAccessExpr.expression) || + this.isElementAcessAllowed(tsElemAccessBaseExprType, tsElemAccessArgType) || + this.options.arkts2 && isGetIndexable || + this.options.arkts2 && isSetIndexable ) { - const autofix = this.autofixer?.fixPropertyAccessByIndex(tsElementAccessExpr); - this.incrementCounters(node, FaultID.PropertyAccessByIndex, autofix); + return; } - if (this.tsUtils.hasEsObjectType(tsElementAccessExpr.expression)) { - const faultId = this.options.arkts2 ? FaultID.EsValueTypeError : FaultID.EsValueType; - this.incrementCounters(node, faultId); + if (this.isStaticClassAccess(tsElementAccessExpr)) { + return; } - if (this.tsUtils.isOrDerivedFrom(tsElemAccessBaseExprType, this.tsUtils.isIndexableArray)) { - this.handleIndexNegative(node); + + const autofix = this.autofixer?.fixPropertyAccessByIndex(tsElementAccessExpr); + this.incrementCounters(tsElementAccessExpr, FaultID.PropertyAccessByIndex, autofix); + } + + /** + * Returns true if this element-access is a static-class cast (e.g., (A as object)["foo"]). + */ + private isStaticClassAccess(expr: ts.ElementAccessExpression): boolean { + const inner = expr.expression; + if ( + ts.isParenthesizedExpression(inner) && + ts.isAsExpression(inner.expression) && + ts.isIdentifier(inner.expression.expression) + ) { + const sym = this.tsTypeChecker.getSymbolAtLocation(inner.expression.expression); + return !!(sym && sym.flags & ts.SymbolFlags.Class); } - this.checkArrayUsageWithoutBound(tsElementAccessExpr); - this.checkArrayIndexType(tsElemAccessBaseExprType, tsElemAccessArgType, tsElementAccessExpr); - this.fixJsImportElementAccessExpression(tsElementAccessExpr); - this.checkInterOpImportJsIndex(tsElementAccessExpr); - this.checkEnumGetMemberValue(tsElementAccessExpr); + return false; } private checkInterOpImportJsIndex(expr: ts.ElementAccessExpression): void { @@ -4337,7 +4501,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const tsCallExpr = node as ts.CallExpression; this.handleStateStyles(tsCallExpr); this.handleBuiltinCtorCallSignature(tsCallExpr); - + this.handleSdkConstructorIfaceForCallExpression(tsCallExpr); if (this.options.arkts2 && tsCallExpr.typeArguments !== undefined) { this.handleSdkPropertyAccessByIndex(tsCallExpr); } @@ -4355,6 +4519,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } else if (this.options.arkts2) { this.handleGenericCallWithNoTypeArgs(tsCallExpr, callSignature); } + this.handleNotsLikeSmartTypeOnCallExpression(tsCallExpr, callSignature); } this.handleInteropForCallExpression(tsCallExpr); this.handleLibraryTypeCall(tsCallExpr); @@ -4392,7 +4557,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { const type = this.tsTypeChecker.getTypeAtLocation(expression); const typeText = this.tsTypeChecker.typeToString(type); if (typeText === LIKE_FUNCTION) { - const autofix = this.autofixer?.fixNoTsLikeFunctionCall(expression); + const autofix = this.autofixer?.fixNoTsLikeFunctionCall(callExpr); this.incrementCounters(expression, FaultID.ExplicitFunctionType, autofix); } } @@ -4519,32 +4684,6 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return false; } - private isExportedEntityDeclaredInArkTs1(exportDecl: ts.ExportDeclaration): boolean | undefined { - if (!this.options.arkts2 || !this.useStatic) { - return false; - } - - // For named exports with braces { ... } - if (exportDecl.exportClause && ts.isNamedExports(exportDecl.exportClause)) { - for (const exportSpecifier of exportDecl.exportClause.elements) { - const identifier = exportSpecifier.name; - if (this.tsUtils.isExportImportedFromArkTs1(identifier, exportDecl)) { - return true; - } - } - } - - // For namespace exports (export * as namespace from ...) - if (exportDecl.exportClause && ts.isNamespaceExport(exportDecl.exportClause)) { - const namespaceIdentifier = exportDecl.exportClause.name; - if (this.tsUtils.isExportImportedFromArkTs1(namespaceIdentifier, exportDecl)) { - return true; - } - } - - return false; - } - private isDeclaredInArkTs2(callSignature: ts.Signature): boolean | undefined { const declarationSourceFile = callSignature?.declaration?.getSourceFile(); if (!declarationSourceFile) { @@ -4560,17 +4699,9 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return false; } - private checkRestrictedAPICall(node: ts.Node): void { - if (ts.isCallExpression(node)) { - if (TypeScriptLinter.isReflectAPICall(node)) { - this.incrementCounters(node.parent, FaultID.InteropCallReflect); - return; - } - - const signature = this.tsTypeChecker.getResolvedSignature(node); - if (signature) { - this.checkForForbiddenAPIs(signature, node); - } + private checkRestrictedAPICall(node: ts.CallExpression): void { + if (TypeScriptLinter.isReflectAPICall(node)) { + this.incrementCounters(node.parent, FaultID.InteropCallReflect); } } @@ -4591,11 +4722,31 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return false; } + private shouldCheckForForbiddenAPI(declaration: ts.SignatureDeclaration | ts.JSDocSignature): boolean { + for (const parameter of declaration.parameters) { + if (ts.isJSDocParameterTag(parameter)) { + continue; + } + const parameterType = this.tsTypeChecker.getTypeAtLocation(parameter); + const parameterTypeString = this.tsTypeChecker.typeToString(parameterType); + + if (parameterTypeString === OBJECT_LITERAL) { + return true; + } + } + + return false; + } + private checkForForbiddenAPIs(callSignature: ts.Signature, tsCallExpr: ts.CallExpression): void { if (!callSignature.declaration) { return; } + if (!this.shouldCheckForForbiddenAPI(callSignature.declaration)) { + return; + } + const functionSymbol = this.getFunctionSymbol(callSignature.declaration); const functionDeclaration = functionSymbol?.valueDeclaration; if (!functionDeclaration) { @@ -5013,30 +5164,32 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { 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.symbol) { - return; - } - const typeDeclarations = type.symbol.declarations; - if (!typeDeclarations || typeDeclarations.length === 0) { - return; - } - - if (!ts.isInterfaceDeclaration(typeDeclarations[0])) { - return; + const typeDeclaration = TsUtils.getDeclaration(type.symbol); + if (typeDeclaration && ts.isInterfaceDeclaration(typeDeclaration) && type.symbol) { + const filePath = typeDeclaration.getSourceFile().fileName; + this.checkIsConstructorIface(calleeExpr, type.symbol.name, path.basename(filePath)); } + } - this.incrementCounters(calleeExpr, FaultID.ConstructorIfaceFromSdk); + private checkIsConstructorIface(node: ts.Node, symbol: string, filePath: string): void { + const constructorIfaceSetInfos = Array.from(TypeScriptLinter.ConstructorIfaceSet); + constructorIfaceSetInfos.some((constructorFuncsInfo) => { + const api_name = constructorFuncsInfo.api_info.parent_api[0].api_name; + if ( + symbol === api_name && + (constructorFuncsInfo.file_path.includes(filePath) || constructorFuncsInfo.import_path.includes(filePath)) + ) { + this.incrementCounters(node, FaultID.ConstructorIfaceFromSdk); + return true; + } + return false; + }); } private handleNewExpression(node: ts.Node): void { @@ -5073,6 +5226,50 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } this.handleSendableGenericTypes(tsNewExpr); this.handleInstantiatedJsObject(tsNewExpr, sym); + this.handlePromiseNeedVoidResolve(tsNewExpr); + } + + handlePromiseNeedVoidResolve(newExpr: ts.NewExpression): void { + if (!this.options.arkts2) { + return; + } + + if (!ts.isIdentifier(newExpr.expression) || newExpr.expression.text !== 'Promise') { + return; + } + + const typeArg = newExpr.typeArguments?.[0]; + if (!typeArg) { + return; + } + + const type = this.tsTypeChecker.getTypeAtLocation(typeArg); + if (!(type.getFlags() & ts.TypeFlags.Void)) { + return; + } + + const executor = newExpr.arguments?.[0]; + if (!executor || !ts.isFunctionLike(executor)) { + return; + } + + const resolveParam = executor.parameters[0]; + if (resolveParam?.type) { + if (ts.isFunctionTypeNode(resolveParam.type) && + resolveParam.type.parameters.length === 0) { + this.incrementCounters(resolveParam.type,FaultID.PromiseVoidNeedResolveArg); + } + } + if (executor.body) { + ts.forEachChild(executor.body, node => { + if (ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === 'resolve' && + node.arguments.length === 0) { + this.incrementCounters(node,FaultID.PromiseVoidNeedResolveArg); + } + }); + } } private checkCreatingPrimitiveTypes(tsNewExpr: ts.NewExpression): void { @@ -5154,6 +5351,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.handleNoTuplesArrays(node, targetType, exprType); this.handleObjectLiteralAssignmentToClass(tsAsExpr); this.handleArrayTypeImmutable(tsAsExpr, exprType, targetType); + this.handleNotsLikeSmartTypeOnAsExpression(tsAsExpr); } private isExemptedAsExpression(node: ts.AsExpression): boolean { @@ -5266,6 +5464,52 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + private handleSdkConstructorIfaceForCallExpression(callExpr: ts.CallExpression): void { + if (!this.options.arkts2) { + return; + } + let type: ts.Type | undefined; + if (!callExpr.arguments || callExpr.arguments.length === 0) { + if (ts.isPropertyAccessExpression(callExpr.expression)) { + type = this.tsTypeChecker.getTypeAtLocation(callExpr.expression.expression); + } + } + callExpr.arguments.some((args) => { + if (ts.isIdentifier(args)) { + type = this.tsTypeChecker.getTypeAtLocation(args); + } + }); + if (!type) { + return; + } + const decl = TsUtils.getDeclaration(type?.symbol); + if (!decl) { + return; + } + const filePath = TypeScriptLinter.getFileName(decl); + this.checkIsConstructorIface(callExpr, type.symbol.name, filePath); + } + + private static getFileName(decl: ts.Declaration): string { + let filePath = ''; + if ( + ts.isImportSpecifier(decl) && + ts.isImportDeclaration(decl.parent.parent.parent) && + ts.isStringLiteral(decl.parent.parent.parent.moduleSpecifier) + ) { + filePath = decl.parent.parent.parent.moduleSpecifier.text; + } else if ( + ts.isImportClause(decl) && + ts.isImportDeclaration(decl.parent) && + ts.isStringLiteral(decl.parent.moduleSpecifier) + ) { + filePath = decl.parent.moduleSpecifier.text; + } else { + filePath = decl.getSourceFile().fileName; + } + return path.basename(filePath); + } + private handleSharedArrayBuffer( node: ts.TypeReferenceNode | ts.NewExpression | ts.ExpressionWithTypeArguments ): void { @@ -5934,11 +6178,6 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } - if (this.isExportedEntityDeclaredInArkTs1(exportDecl)) { - this.incrementCounters(node, FaultID.InteropArkTs1ObjectExport); - return; - } - if (!TypeScriptLinter.inSharedModule(node) || ts.isModuleBlock(node.parent)) { return; } @@ -6573,13 +6812,12 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (!this.options.arkts2) { return; } - if ( - !( - this.tsUtils.isOrDerivedFrom(lhsType, this.tsUtils.isArray) && - this.tsUtils.isOrDerivedFrom(rhsType, this.tsUtils.isArray) && - lhsType !== rhsType - ) - ) { + const isArray = + this.tsUtils.isOrDerivedFrom(lhsType, this.tsUtils.isArray) && + this.tsUtils.isOrDerivedFrom(rhsType, this.tsUtils.isArray); + const isTuple = + this.tsUtils.isOrDerivedFrom(lhsType, TsUtils.isTuple) && this.tsUtils.isOrDerivedFrom(rhsType, TsUtils.isTuple); + if (!((isArray || isTuple) && lhsType !== rhsType)) { return; } @@ -7025,6 +7263,20 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.checkSymbolAndExecute(symbol, WORKER_TEXT, WORKER_MODULES, cb); } + private checkConcurrencySymbol(symbol: ts.Symbol, node: ts.Node): void { + const cb = (): void => { + const parent = node.parent; + if (!ts.isPropertyAccessExpression(parent)) { + return; + } + if (parent.name.text === ARKTSUTILS_LOCKS_MEMBER) { + this.incrementCounters(node, FaultID.LimitedStdLibNoImportConcurrency); + } + }; + + this.checkSymbolAndExecute(symbol, ARKTSUTILS_LOCKS_MEMBER, ARKTSUTILS_MODULES, cb); + } + private checkSymbolAndExecute(symbol: ts.Symbol, symbolName: string, modules: string[], cb: () => void): void { void this; if (symbol.name === symbolName) { @@ -7244,7 +7496,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } const autofix = this.autofixer?.fixStateStyles(object, startNode, this.interfacesNeedToImport); - this.incrementCounters(object, FaultID.StylesDecoratorNotSupported, autofix); + this.incrementCounters(object, FaultID.StateStylesBlockNeedArrowFunc, autofix); } private static hasAnonBlock(properties: ts.NodeArray): boolean { @@ -7826,20 +8078,58 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { if (!hasSameApiName) { return; } - 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; }); + const checkSymbol = this.isIdentifierFromSDK(errorNode); + const type = this.tsTypeChecker.getTypeAtLocation(errorNode); + const typeName = this.tsTypeChecker.typeToString(type); - if (matchedApi) { - this.incrementCounters(errorNode, faultId); + if (checkSymbol) { + if (arkTsBuiltInTypeName.has(typeName)) { + return; + } + if (matchedApi) { + this.incrementCounters(errorNode, faultId); + } + } + } + + private isIdentifierFromSDK(node: ts.Node): boolean { + const symbol = this.tsTypeChecker.getSymbolAtLocation(node); + if (!symbol) { + return true; + } + + // Check if the symbol is from an SDK import + const declarations = symbol.getDeclarations(); + if (!declarations || declarations.length === 0) { + return true; + } + + let isLocal = false; + for (const declaration of declarations) { + if (ts.isVariableDeclaration(declaration) || + ts.isTypeAliasDeclaration(declaration) || + ts.isClassDeclaration(declaration) || + ts.isInterfaceDeclaration(declaration) || + ts.isFunctionDeclaration(declaration) || + ts.isEnumDeclaration(declaration)) { + isLocal = true; + break + } + } + + if(isLocal) { + return false; } + + return true; } private handleSdkGlobalApi( @@ -7918,6 +8208,7 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { private checkCallExpressionForSdkGlobalApi(node: ts.CallExpression): void { if (ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)) { const expression = node.expression.expression; + this.processApiNodeSdkGlobalApi(expression.text, expression); } } @@ -8083,6 +8374,152 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } } + /** + * Returns true if the method’s declared return type or body returns Promise. + */ + private hasPromiseVoidReturn(method: ts.MethodDeclaration): boolean { + return ( + this.hasAnnotatedPromiseVoidReturn(method) || this.isAsyncMethod(method) || this.hasBodyPromiseReturn(method) + ); + } + + /** + * Checks if the method’s declared return type annotation includes Promise. + */ + private hasAnnotatedPromiseVoidReturn(method: ts.MethodDeclaration): boolean { + void this; + if (!method.type) { + return false; + } + const t = method.type; + // Union type check + if (ts.isUnionTypeNode(t)) { + return t.types.some((u) => { + return this.isSinglePromiseVoid(u); + }); + } + // Single Promise check + return this.isSinglePromiseVoid(t); + } + + private isSinglePromiseVoid(n: ts.Node): boolean { + void this; + return ts.isTypeReferenceNode(n) && n.typeName.getText() === PROMISE && n.typeArguments?.[0]?.getText() === VOID; + } + + /** + * Checks if the method is declared async (implying Promise return). + */ + private isAsyncMethod(method: ts.MethodDeclaration): boolean { + void this; + return ( + method.modifiers?.some((m) => { + return m.kind === ts.SyntaxKind.AsyncKeyword; + }) ?? false + ); + } + + /** + * Scans the method body iteratively for any Promise-returning statements. + */ + private hasBodyPromiseReturn(method: ts.MethodDeclaration): boolean { + if (!method.body) { + return false; + } + + let found = false; + const visit = (node: ts.Node): void => { + if (ts.isReturnStatement(node) && node.expression) { + const retType = this.tsTypeChecker.getTypeAtLocation(node.expression); + if (retType.symbol?.getName() === PROMISE) { + found = true; + return; + } + } + ts.forEachChild(node, visit); + }; + ts.forEachChild(method.body, visit); + + return found; + } + + /** + * Returns true if this method name is onDestroy/onDisconnect and class extends one of the supported Ability subclasses. + */ + private isLifecycleMethodOnAbilitySubclass(method: ts.MethodDeclaration): boolean { + const name = method.name.getText(); + if (name !== ON_DESTROY && name !== ON_DISCONNECT) { + return false; + } + const cls = method.parent; + if (!ts.isClassDeclaration(cls) || !cls.heritageClauses) { + return false; + } + return cls.heritageClauses.some((h) => { + return ( + h.token === ts.SyntaxKind.ExtendsKeyword && + h.types.some((tn) => { + return this.isSupportedAbilityBase(method.name.getText(), tn.expression); + }) + ); + }); + } + + /** + * Checks that the base class name and its import source or declaration file are supported, + * and matches the lifecycle method (onDestroy vs onDisconnect). + */ + private isSupportedAbilityBase(methodName: string, baseExprNode: ts.Expression): boolean { + const sym = this.tsTypeChecker.getSymbolAtLocation(baseExprNode); + if (!sym) { + return false; + } + + const baseName = sym.getName(); + if (!ASYNC_LIFECYCLE_SDK_LIST.has(baseName)) { + return false; + } + + if (methodName === ON_DISCONNECT && baseName !== SERVICE_EXTENSION_ABILITY) { + return false; + } + if (methodName === ON_DESTROY && baseName === SERVICE_EXTENSION_ABILITY) { + return false; + } + + const decl = sym.getDeclarations()?.[0]; + if (!decl || !ts.isImportSpecifier(decl)) { + return false; + } + + const importDecl = decl.parent.parent.parent; + const moduleName = (importDecl.moduleSpecifier as ts.StringLiteral).text; + const srcFile = decl.getSourceFile().fileName; + + return moduleName === ABILITY_KIT || srcFile.endsWith(`${baseName}.${EXTNAME_D_TS}`); + } + + /** + * Rule sdk-void-lifecycle-return: + * Flags onDestroy/onDisconnect methods in Ability subclasses + * whose return type includes Promise. + */ + private checkVoidLifecycleReturn(method: ts.MethodDeclaration): void { + if (!this.options.arkts2) { + return; + } + + if (!this.isLifecycleMethodOnAbilitySubclass(method)) { + return; + } + + if (!this.hasPromiseVoidReturn(method)) { + return; + } + + this.incrementCounters(method.name, FaultID.SdkAbilityAsynchronousLifecycle); + } + private handleGetOwnPropertyNames(decl: ts.PropertyAccessExpression): void { if (this.checkPropertyAccessExpression(decl, GET_OWN_PROPERTY_NAMES_TEXT, TypeScriptLinter.missingAttributeSet)) { const autofix = this.autofixer?.fixMissingAttribute(decl); @@ -9325,6 +9762,102 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { this.incrementCounters(awaitExpr, FaultID.NoAwaitJsPromise, autofix); } + private handleNotsLikeSmartTypeOnCallExpression(tsCallExpr: ts.CallExpression, callSignature: ts.Signature): void { + if (!this.options.arkts2) { + return; + } + const isContinue = + ts.isCallExpression(tsCallExpr) && + ts.isIdentifier(tsCallExpr.expression) && + !ts.isReturnStatement(tsCallExpr.parent); + if (!isContinue || !tsCallExpr.arguments) { + return; + } + const declaration = callSignature.getDeclaration(); + if (!declaration || !ts.isFunctionDeclaration(declaration)) { + return; + } + const parameterTypes = declaration.parameters?.map((param) => { + const paramType = this.tsTypeChecker.getTypeAtLocation(param); + return this.tsTypeChecker.typeToString(paramType); + }); + tsCallExpr.arguments.forEach((arg, index) => { + if (index >= parameterTypes.length) { + return; + } + const expectedType = parameterTypes[index]; + const actualSym = this.tsTypeChecker.getSymbolAtLocation(arg); + const decl = TsUtils.getDeclaration(actualSym); + if (decl && ts.isParameter(decl) && decl.type) { + const actualType = this.tsTypeChecker.getTypeFromTypeNode(decl.type); + const actualTypeName = this.tsTypeChecker.typeToString(actualType); + if (actualTypeName !== expectedType) { + this.incrementCounters(arg, FaultID.NoTsLikeSmartType); + } + } + }); + } + + private handleNotsLikeSmartTypeOnAsExpression(tsAsExpr: ts.AsExpression): void { + if (!this.options.arkts2) { + return; + } + const asType = this.tsTypeChecker.getTypeAtLocation(tsAsExpr.type); + const originType = this.tsTypeChecker.getTypeAtLocation(tsAsExpr.expression); + const originTypeStr = this.tsTypeChecker.typeToString(originType); + if (originTypeStr === 'never' && this.tsTypeChecker.typeToString(asType) !== originTypeStr) { + this.incrementCounters(tsAsExpr, FaultID.NoTsLikeSmartType); + } + } + + private handleAssignmentNotsLikeSmartType(tsBinaryExpr: ts.BinaryExpression): void { + if (!this.options.arkts2) { + return; + } + + if (this.isPriorityInThreadInfo(tsBinaryExpr)) { + this.incrementCounters(tsBinaryExpr, FaultID.NoTsLikeSmartType); + } + } + + private isPriorityInThreadInfo(node: ts.BinaryExpression): boolean { + if (!ts.isBinaryExpression(node)) { + return false; + } + + // Handle both regular assignment and 'as' type assertion + let right: ts.Expression = ts.isAsExpression(node.right) ? node.right.expression : node.right; + if (!ts.isPropertyAccessExpression(right)) { + return false; + } + + const propertyName = right.name; + if (!ts.isIdentifier(propertyName)) { + return false; + } + + const object = right.expression; + if (!ts.isIdentifier(object)) { + return false; + } + + const symbol = this.tsTypeChecker.getSymbolAtLocation(object); + if (!symbol) { + return false; + } + + const type = this.tsTypeChecker.getTypeOfSymbolAtLocation(symbol, object); + const typeString = this.tsTypeChecker.typeToString(type); + + for (const [typeName, properties] of Object.entries(ERROR_TASKPOOL_PROP_LIST)) { + if (typeString === typeName && properties.has(propertyName.text)) { + return true; + } + } + + return false; + } + private handleNotsLikeSmartType(classDecl: ts.ClassDeclaration): void { if (!this.options.arkts2) { return; @@ -9501,7 +10034,11 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { } const autofix = this.autofixer?.fixCustomLayout(node); - this.incrementCounters(node.name, FaultID.CustomLayoutNeedAddDecorator, autofix); + const name = node.name.getText(); + const errorMsg = + `The Custom component "${name}" with custom layout capability needs to add the "@CustomLayout" decorator ` + + '(arkui-custom-layout-need-add-decorator)'; + this.incrementCounters(node.name, FaultID.CustomLayoutNeedAddDecorator, autofix, errorMsg); } private handleArkTSPropertyAccess(expr: ts.BinaryExpression): void { @@ -9586,6 +10123,11 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return; } + const arrayDecl = TypeScriptLinter.findArrayDeclaration(arraySym); + if (arrayDecl && TypeScriptLinter.isArrayCreatedWithOtherArrayLength(arrayDecl)) { + return; + } + const indexExpr = accessExpr.argumentExpression; const loopVarName = ts.isIdentifier(indexExpr) ? indexExpr.text : undefined; @@ -9951,4 +10493,31 @@ export class TypeScriptLinter extends BaseTypeScriptLinter { return false; } + + static isArrayCreatedWithOtherArrayLength(decl: ts.VariableDeclaration): boolean { + if (!decl.initializer || !ts.isNewExpression(decl.initializer)) { + return false; + } + + const newExpr = decl.initializer; + return ( + newExpr.arguments?.some((arg) => { + return ts.isPropertyAccessExpression(arg) && arg.name.text === 'length'; + }) ?? false + ); + } + + static findArrayDeclaration(sym: ts.Symbol): ts.VariableDeclaration | undefined { + const decls = sym.getDeclarations(); + if (!decls) { + return undefined; + } + + for (const decl of decls) { + if (ts.isVariableDeclaration(decl)) { + return decl; + } + } + return undefined; + } } diff --git a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts index 9a990259ea..743f8e7382 100644 --- a/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts +++ b/ets2panda/linter/src/lib/autofixes/AutofixTitles.ts @@ -64,5 +64,6 @@ export const cookBookRefToFixTitle: Map = new Map([ [339, 'Using \'ESValue\' interface call'], [341, 'Create JS objects using instantite'], [358, 'Replace missing attribute'], - [359, '"@LocalBuilder" transform to "@Builder"'] + [359, '"@LocalBuilder" transform to "@Builder"'], + [381, 'StateStyles needs arrow function block'] ]); diff --git a/ets2panda/linter/src/lib/autofixes/Autofixer.ts b/ets2panda/linter/src/lib/autofixes/Autofixer.ts index dc78eabc87..a29f4742e4 100644 --- a/ets2panda/linter/src/lib/autofixes/Autofixer.ts +++ b/ets2panda/linter/src/lib/autofixes/Autofixer.ts @@ -46,10 +46,8 @@ import { ES_VALUE } from '../utils/consts/ESObject'; import type { IncrementDecrementNodeInfo } from '../utils/consts/InteropAPI'; import { LOAD, - GET_PROPERTY_BY_NAME, - SET_PROPERTY_BY_NAME, - GET_PROPERTY_BY_INDEX, - SET_PROPERTY_BY_INDEX, + GET_PROPERTY, + SET_PROPERTY, ARE_EQUAL, ARE_STRICTLY_EQUAL, WRAP, @@ -3294,7 +3292,7 @@ export class Autofixer { ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(expression), - ts.factory.createIdentifier(GET_PROPERTY_BY_NAME) + ts.factory.createIdentifier(GET_PROPERTY) ), undefined, [ts.factory.createStringLiteral(name)] @@ -3329,7 +3327,7 @@ export class Autofixer { const node = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(expression), - ts.factory.createIdentifier(SET_PROPERTY_BY_NAME) + ts.factory.createIdentifier(SET_PROPERTY) ), undefined, [ts.factory.createIdentifier(field), value] @@ -3647,7 +3645,9 @@ export class Autofixer { annotationEndLine = sourceFile.getLineAndCharacterOfPosition(annotationEndPos).line; } - let text = this.printer.printNode(ts.EmitHint.Unspecified, importDeclaration, sourceFile); + let text = Autofixer.formatImportStatement( + this.printer.printNode(ts.EmitHint.Unspecified, importDeclaration, sourceFile) + ); if (annotationEndPos !== 0) { text = this.getNewLine() + this.getNewLine() + text; } @@ -3659,6 +3659,25 @@ export class Autofixer { return [{ start: annotationEndPos, end: annotationEndPos, replacementText: text }]; } + private static formatImportStatement(stmt: string): string { + return stmt.replace(/\{([^}]+)\}/, (match, importList) => { + const items = importList.split(',').map((item) => { + return item.trim(); + }); + + if (items.length > 1) { + const formattedList = items + .map((item) => { + return ` ${item.trim()},`; + }) + .join('\n'); + return `{\n${formattedList}\n}`; + } + return `{${importList}}`; + }); + } + + fixStylesDecoratorGlobal( funcDecl: ts.FunctionDeclaration, calls: ts.Identifier[], @@ -3696,6 +3715,10 @@ export class Autofixer { const parameters: ts.MemberName[] = []; const values: ts.Expression[][] = []; const statements = block?.statements; + const type = ts.factory.createTypeReferenceNode( + ts.factory.createIdentifier(CustomDecoratorName.CustomStyles), + undefined + ); Autofixer.getParamsAndValues(statements, parameters, values); const newBlock = Autofixer.createBlock(parameters, values, ts.factory.createIdentifier(INSTANCE_IDENTIFIER)); const parameDecl = ts.factory.createParameterDeclaration( @@ -3714,7 +3737,10 @@ export class Autofixer { ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), newBlock ); - const expr = ts.factory.createPropertyDeclaration(undefined, methodDecl.name, undefined, undefined, arrowFunc); + const newModifiers = ts.getModifiers(methodDecl)?.filter((modifier) => { + return !(ts.isDecorator(modifier) && TsUtils.getDecoratorName(modifier) === CustomDecoratorName.Styles); + }); + const expr = ts.factory.createPropertyDeclaration(newModifiers, methodDecl.name, undefined, type, arrowFunc); needImport.add(COMMON_METHOD_IDENTIFIER); let text = this.printer.printNode(ts.EmitHint.Unspecified, expr, methodDecl.getSourceFile()); const startPos = this.sourceFile.getLineAndCharacterOfPosition(methodDecl.getStart()).character; @@ -3868,7 +3894,7 @@ export class Autofixer { void this; const base = lhs.expression.getText(); const prop = lhs.name.text; - const replacementText = `${base}.setPropertyByName('${prop}',ESValue.wrap(${rhs.getText()}))`; + const replacementText = `${base}.setProperty('${prop}',ESValue.wrap(${rhs.getText()}))`; return [{ start: binaryExpr.getStart(), end: binaryExpr.getEnd(), replacementText }]; } @@ -3906,7 +3932,7 @@ export class Autofixer { let start = node.getStart(); let end = node.getEnd(); - let replacementText = `${objName}.${GET_PROPERTY_BY_NAME}('${propName}')`; + let replacementText = `${objName}.${GET_PROPERTY}('${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) { @@ -3926,7 +3952,7 @@ export class Autofixer { const end = node.getEnd(); const typeTag = this.utils.findTypeOfNodeForConversion(node); - const replacement = `${objName}.${GET_PROPERTY_BY_NAME}('${propName}')${typeTag}`; + const replacement = `${objName}.${GET_PROPERTY}('${propName}')${typeTag}`; return [{ replacementText: replacement, start, end }]; } @@ -3934,8 +3960,8 @@ export class Autofixer { /** * Converts a JS element access (e.g. `arr[index]`) into the corresponding * interop call: - * - On assignment (`arr[index] = value`), emits `arr.setPropertyByIndex(index, ESValue.wrap(value))` - * - On read, emits `arr.getPropertyByIndex(index)` plus any type conversion suffix + * - On assignment (`arr[index] = value`), emits `arr.setProperty(index, ESValue.wrap(value))` + * - On read, emits `arr.getProperty(index)` plus any type conversion suffix * * @param elementAccessExpr The original `ElementAccessExpression` node. * @returns An array with a single `Autofix` describing the replacement range and text. @@ -3951,7 +3977,7 @@ export class Autofixer { let replacementText: string; if (isAssignment) { - // arr.setPropertyByIndex(index, ESValue.wrap(value)) + // arr.setProperty(index, ESValue.wrap(value)) const wrapped = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(ES_VALUE), @@ -3962,16 +3988,16 @@ export class Autofixer { ); const callExpr = ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(identifierNode, ts.factory.createIdentifier(SET_PROPERTY_BY_INDEX)), + ts.factory.createPropertyAccessExpression(identifierNode, ts.factory.createIdentifier(SET_PROPERTY)), undefined, [elementAccessExpr.argumentExpression, wrapped] ); replacementText = this.printer.printNode(ts.EmitHint.Unspecified, callExpr, elementAccessExpr.getSourceFile()); } else { - // arr.getPropertyByIndex(index) plus conversion + // arr.getProperty(index) plus conversion const callExpr = ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(identifierNode, ts.factory.createIdentifier(GET_PROPERTY_BY_INDEX)), + ts.factory.createPropertyAccessExpression(identifierNode, ts.factory.createIdentifier(GET_PROPERTY)), undefined, [elementAccessExpr.argumentExpression] ); @@ -3989,17 +4015,17 @@ export class Autofixer { /** * Replace each loop‐variable reference (e.g. `element`) with - * `array.getPropertyByIndex(i)` plus appropriate conversion. + * `array.getProperty(i)` plus appropriate conversion. * * @param identifier The Identifier node of the loop variable usage. * @param arrayName The name of the array being iterated. */ fixInteropArrayElementUsage(identifier: ts.Identifier, arrayName: string): Autofix { - // arr.getPropertyByIndex(i) + // arr.getProperty(i) const callExpr = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(arrayName), - ts.factory.createIdentifier(GET_PROPERTY_BY_INDEX) + ts.factory.createIdentifier(GET_PROPERTY) ), undefined, [ts.factory.createIdentifier('i')] @@ -4040,7 +4066,7 @@ export class Autofixer { /** * Converts a `for...of` over an interop array into - * an index-based `for` loop using `getPropertyByName("length")`. + * an index-based `for` loop using `getProperty("length")`. * * @param node The `ForOfStatement` node to fix. * @returns A single Autofix for the loop header replacement. @@ -4063,7 +4089,7 @@ export class Autofixer { const lengthAccess = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(iterableName), - ts.factory.createIdentifier(GET_PROPERTY_BY_NAME) + ts.factory.createIdentifier(GET_PROPERTY) ), undefined, [ts.factory.createStringLiteral(LENGTH)] @@ -4216,7 +4242,7 @@ export class Autofixer { return undefined; } const propName = node.name.text; - return `${base}.${GET_PROPERTY_BY_NAME}('${propName}')`; + return `${base}.${GET_PROPERTY}('${propName}')`; } else if (ts.isNewExpression(node)) { const newArgs = this.createArgs(node.arguments); const newCallExpr = this.createJSInvokeCallExpression(node.expression, INSTANTIATE, [...newArgs || []]); @@ -4286,7 +4312,7 @@ export class Autofixer { const propertyName = originalName || symbolName; const constructDeclInfo: string[] = isLoad ? [this.modVarName, ES_VALUE, LOAD] : - [symbolName, this.modVarName, GET_PROPERTY_BY_NAME]; + [symbolName, this.modVarName, GET_PROPERTY]; const newVarDecl = Autofixer.createVariableForInteropImport( constructDeclInfo[0], constructDeclInfo[1], @@ -4311,7 +4337,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(GET_PROPERTY_BY_NAME)), + ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier(GET_PROPERTY)), undefined, [ts.factory.createStringLiteral(express.name.getText())] ); @@ -4333,7 +4359,7 @@ export class Autofixer { const statements = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(objectName), - ts.factory.createIdentifier(SET_PROPERTY_BY_NAME) + ts.factory.createIdentifier(SET_PROPERTY) ), undefined, [ @@ -4370,7 +4396,7 @@ export class Autofixer { } const propertyAccess = ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier(GET_PROPERTY_BY_NAME)), + ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier(GET_PROPERTY)), undefined, [ts.factory.createStringLiteral(express.name.getText())] ); @@ -4429,7 +4455,7 @@ export class Autofixer { private fixPropertyAccessToNumber(expr: ts.PropertyAccessExpression): Autofix[] { const getPropCall = ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(expr.expression, ts.factory.createIdentifier(GET_PROPERTY_BY_NAME)), + ts.factory.createPropertyAccessExpression(expr.expression, ts.factory.createIdentifier(GET_PROPERTY)), undefined, [ts.factory.createStringLiteral(expr.name.getText())] ); @@ -4453,7 +4479,7 @@ export class Autofixer { fixInteropArrayElementAccessExpression(express: ts.ElementAccessExpression): Autofix[] | undefined { const statements = ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier(GET_PROPERTY_BY_INDEX)), + ts.factory.createPropertyAccessExpression(express.expression, ts.factory.createIdentifier(GET_PROPERTY)), undefined, [express.argumentExpression] ); @@ -4467,7 +4493,7 @@ export class Autofixer { const statements = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(left.expression.getText()), - ts.factory.createIdentifier(SET_PROPERTY_BY_INDEX) + ts.factory.createIdentifier(SET_PROPERTY) ), undefined, [ @@ -4503,7 +4529,7 @@ export class Autofixer { const getPropertyCall = ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(propertyAccess.expression.getText()), - ts.factory.createIdentifier(GET_PROPERTY_BY_NAME) + ts.factory.createIdentifier(GET_PROPERTY) ), undefined, [ts.factory.createStringLiteral(propertyAccess.name.getText())] @@ -4627,17 +4653,22 @@ export class Autofixer { return [{ start: argExpr.getStart(), end: argExpr.getEnd(), replacementText: `${argExpr.getText()} as int` }]; } - fixNoTsLikeFunctionCall(identifier: ts.Node): Autofix[] { + fixNoTsLikeFunctionCall(callExpr: ts.CallExpression): Autofix[] { void this; - const funcName = identifier.getText(); - const replacementText = `${funcName}.unsafeCall`; - return [ - { - replacementText, - start: identifier.getStart(), - end: identifier.getEnd() - } - ]; + const expr = callExpr.expression; + const hasOptionalChain = !!callExpr.questionDotToken; + + const replacementText = hasOptionalChain + ? `${expr.getText()}${callExpr.questionDotToken.getText()}unsafeCall` + : `${expr.getText()}.unsafeCall`; + + return [{ + start: expr.getStart(), + end: hasOptionalChain + ? callExpr.questionDotToken.getEnd() + : expr.getEnd(), + replacementText + }]; } private static createBuiltInTypeInitializer(type: ts.TypeReferenceNode): ts.Expression | undefined { @@ -4871,6 +4902,12 @@ export class Autofixer { if (!typeNode) { return this.fixGenericCallNoTypeArgsWithContextualType(node); } + if (ts.isUnionTypeNode(typeNode)) { + return this.fixGenericCallNoTypeArgsForUnionType(node, typeNode); + } + if (ts.isArrayTypeNode(typeNode)) { + return this.fixGenericCallNoTypeArgsForArrayType(node, typeNode); + } if (!ts.isTypeReferenceNode(typeNode) || typeNode.typeName.getText() !== node.expression.getText()) { return undefined; } @@ -4887,6 +4924,36 @@ export class Autofixer { return [{ start: insertPos, end: insertPos, replacementText: typeArgsText }]; } + private fixGenericCallNoTypeArgsForArrayType(node: ts.NewExpression, arrayTypeNode: ts.ArrayTypeNode): Autofix[] | undefined { + const elementTypeNode = arrayTypeNode.elementType; + const srcFile = node.getSourceFile(); + const typeArgsText = `<${this.printer.printNode(ts.EmitHint.Unspecified, elementTypeNode, srcFile)}>`; + const insertPos = node.expression.getEnd(); + return [{ start: insertPos, end: insertPos, replacementText: typeArgsText }]; + } + + private fixGenericCallNoTypeArgsForUnionType(node: ts.NewExpression, unionType: ts.UnionTypeNode): Autofix[] | undefined { + const matchingTypes = unionType.types.filter((type) => { + return ts.isTypeReferenceNode(type) && type.typeName.getText() === node.expression.getText(); + }) as ts.TypeReferenceNode[]; + + if (matchingTypes.length === 1) { + const matchingType = matchingTypes[0]; + if (matchingType.typeArguments) { + const srcFile = node.getSourceFile(); + const typeArgsText = `<${matchingType.typeArguments. + map((arg) => { + return this.printer.printNode(ts.EmitHint.Unspecified, arg, srcFile); + }). + join(', ')}>`; + + const insertPos = node.expression.getEnd(); + return [{ start: insertPos, end: insertPos, replacementText: typeArgsText }]; + } + } + return undefined; + } + private generateGenericTypeArgumentsAutofix( node: ts.NewExpression, typeArgs: ts.TypeReferenceNode[] diff --git a/ets2panda/linter/src/lib/statistics/scan/CountFile.ts b/ets2panda/linter/src/lib/statistics/scan/CountFile.ts new file mode 100644 index 0000000000..04f0166f35 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/CountFile.ts @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 { promisify } from 'util'; + +// Define file type extensions +const FILE_TYPES: { [key: string]: string[] } = { + 'C/C++': ['.c', '.h', '.cpp', '.hpp'], + JavaScript: ['.js'], + TypeScript: ['.ts'], + JSON: ['.json', '.json5'], + XML: ['.xml'], + ArkTS: ['.ets'], + 'ArkTS Test': ['.test.ets'] +}; + +// Comment regex patterns by file type +const COMMENT_REGEX1: { [key: string]: RegExp } = { + 'C/C++': /\/\/.*/g, + JavaScript: /\/\/.*/g, + TypeScript: /\/\/.*/g, + ArkTS: /\/\/.*/g, + 'ArkTS Test': /\/\/.*/g, + XML: //g +}; + +const COMMENT_REGEX2: { [key: string]: RegExp } = { + 'C/C++': /\/\*.*?\*\//gs, + JavaScript: /\/\*.*?\*\//gs, + TypeScript: /\/\*.*?\*\//gs, + ArkTS: /\/\*.*?\*\//gs, + 'ArkTS Test': /\/\*.*?\*\//gs +}; + +/** + * Remove comments from file content + */ +function removeComments(content: string, fileType: string): string { + if (COMMENT_REGEX1[fileType]) { + content = content.replace(COMMENT_REGEX1[fileType], ''); + } + if (COMMENT_REGEX2[fileType]) { + content = content.replace(COMMENT_REGEX2[fileType], ''); + } + return content; +} + +/** + * Count valid lines of code (excluding comments and empty lines) + */ +async function countLines(filePath: string, fileType: string): Promise { + try { + const content = await promisify(fs.readFile)(filePath, 'utf-8'); + const cleanedContent = removeComments(content, fileType); + const lines = cleanedContent.split('\n'); + + // Filter out empty lines + const validLines = lines.filter((line) => { + return line.trim(); + }); + return validLines.length; + } catch (error) { + console.error(`Error reading ${filePath}: ${error}`); + return 0; + } +} + +/** + * Merge multiple result objects + */ +function mergeAllResults(results: { [key: string]: { fileCount: number; lineCount: number } }[]): { + [key: string]: { fileCount: number; lineCount: number }; +} { + const combined: { [key: string]: { fileCount: number; lineCount: number } } = {}; + + for (const result of results) { + for (const [type, counts] of Object.entries(result)) { + if (!combined[type]) { + combined[type] = { fileCount: 0, lineCount: 0 }; + } + combined[type].fileCount += counts.fileCount; + combined[type].lineCount += counts.lineCount; + } + } + + return combined; +} + +/** + * Process directory entries recursively + */ +async function walkDir(dir: string): Promise<{ [key: string]: { fileCount: number; lineCount: number } }> { + try { + const entries = await promisify(fs.readdir)(dir, { withFileTypes: true }); + const fileResults = await processFiles(dir, entries); + const dirResults = await processDirs(dir, entries); + return mergeAllResults([fileResults, dirResults]); + } catch (error) { + console.error(`Error reading ${dir}: ${error}`); + return {}; + } +} + +/** + * Process files in a directory + */ +async function processFiles( + dir: string, + entries: fs.Dirent[] +): Promise<{ [key: string]: { fileCount: number; lineCount: number } }> { + const fileResults = await Promise.all( + entries. + filter((entry) => { + return entry.isFile(); + }). + map(async(entry) => { + return processFileEntry(dir, entry); + }) + ); + return mergeAllResults(fileResults); +} + +/** + * Process a single file entry + */ +async function processFileEntry( + dir: string, + entry: fs.Dirent +): Promise<{ [key: string]: { fileCount: number; lineCount: number } }> { + const fullPath = path.join(dir, entry.name); + + for (const fileType in FILE_TYPES) { + const extensions = FILE_TYPES[fileType]; + const ext = path.extname(entry.name); + + if (extensions.includes(ext)) { + const lines = await countLines(fullPath, fileType); + return { + [fileType]: { + fileCount: 1, + lineCount: lines + } + }; + } + } + + return {}; +} + +/** + * Process subdirectories recursively + */ +async function processDirs( + dir: string, + entries: fs.Dirent[] +): Promise<{ [key: string]: { fileCount: number; lineCount: number } }> { + const dirEntries = entries.filter((entry) => { + return entry.isDirectory(); + }); + const dirResults = await Promise.all( + dirEntries.map((entry) => { + return walkDir(path.join(dir, entry.name)); + }) + ); + return mergeAllResults(dirResults); +} + +/** + * Analyze directory and count files/lines by type + */ +async function analyzeDirectory( + directory: string +): Promise<{ [key: string]: { fileCount: number; lineCount: number } }> { + // Initialize results + const results: { [key: string]: { fileCount: number; lineCount: number } } = {}; + for (const fileType in FILE_TYPES) { + results[fileType] = { fileCount: 0, lineCount: 0 }; + } + + const finalResults = await walkDir(directory); + Object.assign(results, finalResults); + return results; +} + +/** + * Main export function + */ +export async function countFiles( + directory: string +): Promise<{ [key: string]: { fileCount: number; lineCount: number } }> { + try { + const stats = await promisify(fs.stat)(directory); + if (stats.isDirectory()) { + return await analyzeDirectory(directory); + } + console.error('The directory is invalid!'); + return {}; + } catch (error) { + console.error('Read directory failed', error); + return {}; + } +} diff --git a/ets2panda/linter/src/lib/statistics/scan/CountNapiFile.ts b/ets2panda/linter/src/lib/statistics/scan/CountNapiFile.ts new file mode 100644 index 0000000000..93e31a0aa5 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/CountNapiFile.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 fs from 'fs'; +import * as path from 'path'; +import type { NapiFileStatisticInfo } from './NapiFileStatisticInfo'; + +const EXTENSIONS = ['.c', '.cpp', '.cc', '.cxx', '.h', '.hpp', '.hh', '.hxx']; + +const SINGLE_LINE_COMMENT_REGEX = /\/\/.*/g; +const MULTI_LINE_COMMENT_REGEX = /\/\*[\s\S]*?\*\//g; + +const DEFAULT_STATISTICS: NapiFileStatisticInfo = { + totalFiles: 0, + totalLines: 0, + napiFiles: 0, + napiLines: 0, + napiFileLines: 0 +}; + +function removeComments(content: string): string { + return content.replace(MULTI_LINE_COMMENT_REGEX, '').replace(SINGLE_LINE_COMMENT_REGEX, ''); +} + +async function countLines(filePath: string): Promise { + try { + const content = await fs.promises.readFile(filePath, 'utf-8'); + const contentWithoutComments = removeComments(content); + const validLines = contentWithoutComments.split('\n').filter((line) => { + return line.trim(); + }); + return validLines.length; + } catch (e) { + console.error(`Error reading ${filePath}: ${e}`); + return 0; + } +} + +async function countNapiLines(filePath: string): Promise { + try { + const content = await fs.promises.readFile(filePath, 'utf-8'); + const lines = content.split('\n'); + const napiLines = new Set(); + + for (const line of lines) { + if (line.toLowerCase().includes('napi')) { + napiLines.add(line); + } + } + + return napiLines.size; + } catch (e) { + console.error(`Error reading ${filePath}: ${e}`); + return 0; + } +} + +async function analyzeDirectoryAsync(directory: string): Promise { + const dirQueue: string[] = [directory]; + const allResults: NapiFileStatisticInfo[] = []; + + while (dirQueue.length > 0) { + const currentDir = dirQueue.shift()!; + const entries = await fs.promises.readdir(currentDir, { withFileTypes: true }); + const fileResults = await Promise.all( + entries. + map((entry) => { + const fullPath = path.join(currentDir, entry.name); + if (entry.isDirectory()) { + dirQueue.push(fullPath); + return null; + } else if (isTargetFile(entry.name)) { + return processFile(fullPath); + } + return null; + }). + filter(Boolean) as Promise[] + ); + allResults.push(...fileResults); + } + + return allResults.reduce( + (acc, cur) => { + acc.totalFiles += cur.totalFiles; + acc.totalLines += cur.totalLines; + if (cur.napiFiles > 0) { + acc.napiFiles += cur.napiFiles; + acc.napiLines += cur.napiLines; + acc.napiFileLines += cur.napiFileLines; + } + return acc; + }, + { ...DEFAULT_STATISTICS } + ); +} + +async function processFile(filePath: string): Promise { + const result: NapiFileStatisticInfo = { + totalFiles: 1, + totalLines: 0, + napiFiles: 0, + napiLines: 0, + napiFileLines: 0 + }; + + try { + const [lines, napiCount] = await Promise.all([countLines(filePath), countNapiLines(filePath)]); + + result.totalLines = lines; + if (napiCount > 0) { + result.napiFiles = 1; + result.napiLines = napiCount; + result.napiFileLines = lines; + } + } catch (e) { + console.error(`Error processing ${filePath}: ${e}`); + } + return result; +} + +function isTargetFile(filename: string): boolean { + return EXTENSIONS.some((ext) => { + return filename.endsWith(ext); + }); +} + +export async function countNapiFiles(directory: string): Promise { + try { + const stat = await fs.promises.stat(directory); + if (!stat.isDirectory()) { + console.log('The provided path is not a directory!'); + return DEFAULT_STATISTICS; + } + return await analyzeDirectoryAsync(directory); + } catch (e) { + console.error(`Error accessing directory ${directory}: ${e}`); + return DEFAULT_STATISTICS; + } +} diff --git a/ets2panda/linter/src/lib/statistics/scan/FloderScanResultInfo.ts b/ets2panda/linter/src/lib/statistics/scan/FloderScanResultInfo.ts new file mode 100644 index 0000000000..447813a2d2 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/FloderScanResultInfo.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 interface FloderScanResultInfo { + normalizedPath: string; + arkTSCodeLines: number; + cAndCPPCodeLines: number; + napiCodeLines: number; + jsCodeLines: number; + tsCodeLines: number; + jsonCodeLines: number; + xmlCodeLines: number; +} diff --git a/ets2panda/linter/src/lib/statistics/scan/NapiFileStatisticInfo.ts b/ets2panda/linter/src/lib/statistics/scan/NapiFileStatisticInfo.ts new file mode 100644 index 0000000000..20b3243802 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/NapiFileStatisticInfo.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. + */ + +export interface NapiFileStatisticInfo { + totalFiles: number; + totalLines: number; + napiFiles: number; + napiLines: number; + napiFileLines: number; +} diff --git a/ets2panda/linter/src/lib/statistics/scan/ProblemNumbersInfo.ts b/ets2panda/linter/src/lib/statistics/scan/ProblemNumbersInfo.ts new file mode 100644 index 0000000000..d969313546 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/ProblemNumbersInfo.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. + */ + +export interface ProblemNumbersInfo { + totalProblemNumbers: number; + arkOnePointOneProblemNumbers: number; + arkOnePointTWOProblemNumbers: number; + canBeAutoFixedproblemNumbers: number; + needToManualFixproblemNumbers: number; +} diff --git a/ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsCommonFunction.ts b/ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsCommonFunction.ts new file mode 100644 index 0000000000..cdf625ab5f --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsCommonFunction.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. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { LintRunResult } from '../../LintRunResult'; +import type { ProblemInfo } from '../../ProblemInfo'; +import * as mk from '../../utils/consts/MapKeyConst'; +import { countFiles } from './CountFile'; +import { countNapiFiles } from './CountNapiFile'; +import type { ProblemNumbersInfo } from './ProblemNumbersInfo'; +import type { ProblemStatisticsInfo } from './ProblemStatisticsInfo'; +import type { RuleDetailedErrorInfo } from './RuleDetailedErrorInfo'; +import type { StatisticsReportInPutInfo } from './StatisticsReportInPutInfo'; +import type { TimeRecorder } from './TimeRecorder'; +import { WorkLoadInfo } from './WorkLoadInfo'; + +export function getProblemStatisticsInfo( + problemNumbers: ProblemNumbersInfo, + ruleToNumbersMap: Map, + ruleToAutoFixedNumbersMap: Map, + timeRecorder: TimeRecorder, + WorkLoadInfo?: WorkLoadInfo +): ProblemStatisticsInfo { + const problemNumberMap: Map = new Map(); + problemNumberMap.set(mk.TOTAL_PROBLEMS, problemNumbers.totalProblemNumbers); + problemNumberMap.set(mk.ONE_POINT_ONE_PROBLEMS, problemNumbers.arkOnePointOneProblemNumbers); + problemNumberMap.set(mk.ONE_POINT_TWO_PROBLEMS, problemNumbers.arkOnePointTWOProblemNumbers); + problemNumberMap.set(mk.CAN_BE_AUTO_FIXED_PROBLEMS_NUMBERS, problemNumbers.canBeAutoFixedproblemNumbers); + problemNumberMap.set(mk.NEED_TO_NAMUAL_FIX_PROBLEM_NUMBERS, problemNumbers.needToManualFixproblemNumbers); + + const scanTime = timeRecorder.getScanTime(); + const migrationTime = timeRecorder.getMigrationTime(); + const usedTimeMap: Map = new Map(); + usedTimeMap.set(mk.SCAN_TIME, scanTime); + usedTimeMap.set(mk.MIGRATION_TIME, migrationTime); + + const detailRuleProblemsMap: Map = new Map(); + ruleToNumbersMap.forEach((value, key) => { + const ruleDetailedErrorInfo: RuleDetailedErrorInfo = { + rule: key, + problemNumbers: value, + canBeAutoFixedMumbers: ruleToAutoFixedNumbersMap.get(key) ?? 0 + }; + detailRuleProblemsMap.set(key, ruleDetailedErrorInfo); + }); + + const problemStatisticsInfo: ProblemStatisticsInfo = { + problems: Object.fromEntries(problemNumberMap), + usedTime: Object.fromEntries(usedTimeMap), + WorkLoadInfo: WorkLoadInfo, + eachRuleProblemsDetail: Array.from(detailRuleProblemsMap.values()) + }; + return problemStatisticsInfo; +} + +export function getArktsOnePointOneProlemNumbers(problems: ProblemInfo[]): number { + let problemNumbersForATSOnePointOne: number = 0; + const signForOne: string = 's2d'; + problems.forEach((problem) => { + if (problem.rule !== undefined) { + if (problem.rule.includes(signForOne)) { + problemNumbersForATSOnePointOne = problemNumbersForATSOnePointOne + 1; + } + } + }); + return problemNumbersForATSOnePointOne; +} + +export function accumulateRuleNumbers( + problems: ProblemInfo[], + ruleToNumbersMap: Map, + ruleToAutoFixedNumbersMap: Map +): void { + problems.forEach((problem) => { + if (problem.rule !== undefined) { + if (problem.autofix) { + const currentNumber = ruleToAutoFixedNumbersMap.get(problem.rule) || 0; + ruleToAutoFixedNumbersMap.set(problem.rule, currentNumber + 1); + } + const currentNumber = ruleToNumbersMap.get(problem.rule) || 0; + ruleToNumbersMap.set(problem.rule, currentNumber + 1); + } + }); +} + +export async function generateReportFile(reportName: string, reportData, reportPath?: string): Promise { + let reportFilePath = path.join(reportName); + if (reportPath !== undefined) { + reportFilePath = path.join(path.normalize(reportPath), reportName); + } + try { + await fs.promises.mkdir(path.dirname(reportFilePath), { recursive: true }); + await fs.promises.writeFile(reportFilePath, JSON.stringify(reportData, null, 2)); + } catch (error) { + console.error('Error generating report file:', error); + } +} + +export function generateReportFileSync(reportName: string, reportData: any, reportPath?: string): void { + let reportFilePath = reportName; + if (reportPath !== undefined) { + reportFilePath = path.join(path.normalize(reportPath), reportName); + } + try { + fs.mkdirSync(path.dirname(reportFilePath), { recursive: true }); + fs.writeFileSync(reportFilePath, JSON.stringify(reportData, null, 2)); + } catch (error) { + console.error('Error generating report file:', error); + } +} + +export function getMapValueSum(map: Map): number { + let result = 0; + for (const value of map.values()) { + result += value; + } + return result; +} + +export async function generateScanProbelemStatisticsReport( + statisticsReportInPutInfo: StatisticsReportInPutInfo +): Promise { + const canBeAutoFixedproblemNumbers = getMapValueSum(statisticsReportInPutInfo.ruleToAutoFixedNumbersMap); + const problemNumbers: ProblemNumbersInfo = { + totalProblemNumbers: statisticsReportInPutInfo.totalProblemNumbers, + arkOnePointOneProblemNumbers: statisticsReportInPutInfo.arkOnePointOneProblemNumbers, + arkOnePointTWOProblemNumbers: + statisticsReportInPutInfo.totalProblemNumbers - statisticsReportInPutInfo.arkOnePointOneProblemNumbers, + canBeAutoFixedproblemNumbers: canBeAutoFixedproblemNumbers, + needToManualFixproblemNumbers: statisticsReportInPutInfo.totalProblemNumbers - canBeAutoFixedproblemNumbers + }; + const projectFolderList = statisticsReportInPutInfo.cmdOptions.linterOptions.projectFolderList!; + const WorkLoadInfo = await getWorkLoadInfo(projectFolderList); + const statisticsReportData = getProblemStatisticsInfo( + problemNumbers, + statisticsReportInPutInfo.ruleToNumbersMap, + statisticsReportInPutInfo.ruleToAutoFixedNumbersMap, + statisticsReportInPutInfo.timeRecorder, + WorkLoadInfo + ); + await generateReportFile( + statisticsReportInPutInfo.statisticsReportName, + statisticsReportData, + statisticsReportInPutInfo.cmdOptions.outputFilePath + ); +} + +export function generateMigrationStatisicsReport( + lintResult: LintRunResult, + timeRecorder: TimeRecorder, + outputFilePath?: string +): void { + const ruleToNumbersMap: Map = new Map(); + const ruleToAutoFixedNumbersMap: Map = new Map(); + let arkOnePointOneProblemNumbers: number = 0; + + const problemsInfoAfterAutofixed = lintResult.problemsInfos; + for (const problems of problemsInfoAfterAutofixed.values()) { + accumulateRuleNumbers(problems, ruleToNumbersMap, ruleToAutoFixedNumbersMap); + arkOnePointOneProblemNumbers = arkOnePointOneProblemNumbers + getArktsOnePointOneProlemNumbers(problems); + } + + let totalProblemNumbers: number = 0; + for (const problems of problemsInfoAfterAutofixed.values()) { + totalProblemNumbers += problems.length; + } + + const canBeAutoFixedproblemNumbers = getMapValueSum(ruleToAutoFixedNumbersMap); + + const problemNumbers: ProblemNumbersInfo = { + totalProblemNumbers: totalProblemNumbers, + arkOnePointOneProblemNumbers: arkOnePointOneProblemNumbers, + arkOnePointTWOProblemNumbers: totalProblemNumbers - arkOnePointOneProblemNumbers, + canBeAutoFixedproblemNumbers: canBeAutoFixedproblemNumbers, + needToManualFixproblemNumbers: totalProblemNumbers - canBeAutoFixedproblemNumbers + }; + + const statisticsReportData = getProblemStatisticsInfo( + problemNumbers, + ruleToNumbersMap, + ruleToAutoFixedNumbersMap, + timeRecorder + ); + const statisticsReportName: string = 'migration-results-statistics.json'; + generateReportFileSync(statisticsReportName, statisticsReportData, outputFilePath); +} + +export async function getWorkLoadInfo(projectPathList: string[]): Promise { + const workloadInfo = new WorkLoadInfo(); + const projectResults = await Promise.all( + projectPathList.map(async(projectPath) => { + const normalizedPath = path.normalize(projectPath); + const [countFilesResults, countNapiFileResults] = await Promise.all([ + countFiles(normalizedPath), + countNapiFiles(normalizedPath) + ]); + + const getLines = (lang: keyof typeof countFilesResults): number => { + return countFilesResults[lang]?.lineCount || 0; + }; + + return { + normalizedPath, + arkTSCodeLines: getLines('ArkTS') + getLines('ArkTS Test'), + cAndCPPCodeLines: getLines('C/C++'), + napiCodeLines: countNapiFileResults.napiLines, + jsCodeLines: getLines('JavaScript'), + tsCodeLines: getLines('TypeScript'), + jsonCodeLines: getLines('JSON'), + xmlCodeLines: getLines('XML') + }; + }) + ); + + projectResults.forEach((result) => { + workloadInfo.addFloderResult(result); + }); + return workloadInfo; +} diff --git a/ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsInfo.ts b/ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsInfo.ts new file mode 100644 index 0000000000..8bbef29b16 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/ProblemStatisticsInfo.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 type { RuleDetailedErrorInfo } from './RuleDetailedErrorInfo'; +import type { WorkLoadInfo } from './WorkLoadInfo'; + +export interface ProblemStatisticsInfo { + problems: { [k: string]: number }; + usedTime: { [k: string]: string }; + eachRuleProblemsDetail: RuleDetailedErrorInfo[]; + WorkLoadInfo?: WorkLoadInfo; +} diff --git a/ets2panda/linter/src/lib/statistics/scan/RuleDetailedErrorInfo.ts b/ets2panda/linter/src/lib/statistics/scan/RuleDetailedErrorInfo.ts new file mode 100644 index 0000000000..b4c56ee615 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/RuleDetailedErrorInfo.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 interface RuleDetailedErrorInfo { + rule: string; + problemNumbers: number; + canBeAutoFixedMumbers: number; +} diff --git a/ets2panda/linter/src/lib/statistics/scan/ScanTaskRelatedInfo.ts b/ets2panda/linter/src/lib/statistics/scan/ScanTaskRelatedInfo.ts new file mode 100644 index 0000000000..6cc3f6dafd --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/ScanTaskRelatedInfo.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 type { CommandLineOptions } from '../../CommandLineOptions'; +import type { LinterConfig } from '../../LinterConfig'; +import type { ProblemInfo } from '../../ProblemInfo'; +import type { StatisticsReportInPutInfo } from './StatisticsReportInPutInfo'; +import type { TimeRecorder } from './TimeRecorder'; + +export interface ScanTaskRelatedInfo { + cmdOptions: CommandLineOptions; + timeRecorder: TimeRecorder; + statisticsReportInPutInfo: StatisticsReportInPutInfo; + mergedProblems: Map; + homeCheckResult: Map; + totalProblemNumbers: number; + statisticsReportName: number; + compileOptions: LinterConfig; +} diff --git a/ets2panda/linter/src/lib/statistics/scan/StatisticsReportInPutInfo.ts b/ets2panda/linter/src/lib/statistics/scan/StatisticsReportInPutInfo.ts new file mode 100644 index 0000000000..377f0843ff --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/StatisticsReportInPutInfo.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. + */ + +import type { CommandLineOptions } from '../../CommandLineOptions'; +import type { TimeRecorder } from './TimeRecorder'; + +export class StatisticsReportInPutInfo { + totalProblemNumbers: number = 0; + arkOnePointOneProblemNumbers: number = 0; + ruleToNumbersMap: Map = {} as Map; + ruleToAutoFixedNumbersMap: Map = {} as Map; + cmdOptions: CommandLineOptions = {} as CommandLineOptions; + timeRecorder: TimeRecorder = {} as TimeRecorder; + statisticsReportName: string = ''; +} diff --git a/ets2panda/linter/src/lib/statistics/scan/TimeRecorder.ts b/ets2panda/linter/src/lib/statistics/scan/TimeRecorder.ts new file mode 100644 index 0000000000..5f21944a81 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/TimeRecorder.ts @@ -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. + */ + +export class TimeRecorder { + private lintStart = BigInt(0); + private lintEnd = BigInt(0); + private migrationStart = BigInt(0); + private migrationEnd = BigInt(0); + private isHomeCheckCount: boolean = false; + + setHomeCheckCountStatus(isHomeCheckCount: boolean): void { + this.isHomeCheckCount = isHomeCheckCount; + } + + getHomeCheckCountStatus(): boolean { + return this.isHomeCheckCount; + } + + startScan(): void { + this.lintStart = process.hrtime.bigint(); + } + + endScan(): void { + this.lintEnd = process.hrtime.bigint(); + } + + startMigration(): void { + this.migrationStart = process.hrtime.bigint(); + } + + endMigration(): void { + this.migrationEnd = process.hrtime.bigint(); + } + + getScanTime(): string { + return `${(Number(this.lintEnd - this.lintStart) / 1000000000).toFixed(2)} s`; + } + + getMigrationTime(): string { + return `${(Number(this.migrationEnd - this.migrationStart) / 1000000000).toFixed(2)} s`; + } +} diff --git a/ets2panda/linter/src/lib/statistics/scan/WorkLoadInfo.ts b/ets2panda/linter/src/lib/statistics/scan/WorkLoadInfo.ts new file mode 100644 index 0000000000..59135b1db2 --- /dev/null +++ b/ets2panda/linter/src/lib/statistics/scan/WorkLoadInfo.ts @@ -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 { + AVERAGE_LINE_FOR_REPAIRE_RULE_COEFFICIENT, + NPAI_REPAIRE_WORKLOADA_COEFFICIEN, + TEST_DEBUG_WORKLOAD_COEFFICIENT +} from '../../utils/consts/WorkloadRelatedConst'; +import type { FloderScanResultInfo } from './FloderScanResultInfo'; +import type { ProblemNumbersInfo } from './ProblemNumbersInfo'; + +export class WorkLoadInfo { + scanFilePathList: string[] = []; + totalArkTSCodeLines = 0; + totalCAndCPPCodeLines = 0; + totalNapiCodeLines = 0; + totalJsCodeLines = 0; + totalTsCodeLines = 0; + totalJsonCodeLines = 0; + totalXmlCodeLines = 0; + + addFloderResult(result: FloderScanResultInfo): void { + this.scanFilePathList.push(result.normalizedPath); + this.totalArkTSCodeLines += result.arkTSCodeLines; + this.totalCAndCPPCodeLines += result.cAndCPPCodeLines; + this.totalNapiCodeLines += result.napiCodeLines; + this.totalJsCodeLines += result.jsCodeLines; + this.totalTsCodeLines += result.tsCodeLines; + this.totalJsonCodeLines += result.jsonCodeLines; + this.totalXmlCodeLines += result.xmlCodeLines; + } + + calculateFixRate(problemNumbers: ProblemNumbersInfo): string { + const totalLines = this.totalArkTSCodeLines + this.totalCAndCPPCodeLines; + if (totalLines <= 0) { + return '0.00%'; + } + + const problemCount = problemNumbers.needToManualFixproblemNumbers; + const ratio = + (problemCount * AVERAGE_LINE_FOR_REPAIRE_RULE_COEFFICIENT * TEST_DEBUG_WORKLOAD_COEFFICIENT + + this.totalNapiCodeLines * NPAI_REPAIRE_WORKLOADA_COEFFICIEN) / + totalLines; + + return `${(ratio * 100).toFixed(2)}%`; + } +} diff --git a/ets2panda/linter/src/lib/utils/TsUtils.ts b/ets2panda/linter/src/lib/utils/TsUtils.ts index 7aa8050e88..e164774602 100644 --- a/ets2panda/linter/src/lib/utils/TsUtils.ts +++ b/ets2panda/linter/src/lib/utils/TsUtils.ts @@ -48,6 +48,7 @@ import { ETS_MODULE, PATH_SEPARATOR, VALID_OHM_COMPONENTS_MODULE_PATH } from './ import { EXTNAME_ETS, EXTNAME_JS, EXTNAME_D_ETS } from './consts/ExtensionName'; import { STRING_ERROR_LITERAL } from './consts/Literals'; +export const PROMISE_METHODS = new Set(['all', 'race', 'any', 'resolve', 'allSettled']); export const SYMBOL = 'Symbol'; export const SYMBOL_CONSTRUCTOR = 'SymbolConstructor'; const ITERATOR = 'iterator'; @@ -824,18 +825,22 @@ export class TsUtils { isStrict: boolean = false ): boolean { if ( - TsUtils.reduceReference(lhsType) === TsUtils.reduceReference(rhsType) && - TsUtils.isTypeReference(lhsType) && - TsUtils.isTypeReference(rhsType) + TsUtils.reduceReference(lhsType) !== TsUtils.reduceReference(rhsType) || + !TsUtils.isTypeReference(lhsType) || + !TsUtils.isTypeReference(rhsType) ) { - const lhsArgs = lhsType.typeArguments; - const rhsArgs = rhsType.typeArguments; - if (lhsArgs && lhsArgs.length > 0) { - if (rhsArgs && rhsArgs.length > 0) { - return this.needToDeduceStructuralIdentity(lhsArgs[0], rhsArgs[0], rhsExpr, isStrict); + return false; + } + const lhsArgs = lhsType.typeArguments; + const rhsArgs = rhsType.typeArguments; + if (lhsArgs && lhsArgs.length > 0) { + if (rhsArgs && rhsArgs.length > 0) { + if (rhsArgs[0] === lhsArgs[0]) { + return false; } - return this.needToDeduceStructuralIdentity(lhsArgs[0], rhsType, rhsExpr, isStrict); + return this.needToDeduceStructuralIdentity(lhsArgs[0], rhsArgs[0], rhsExpr, isStrict); } + return this.needToDeduceStructuralIdentity(lhsArgs[0], rhsType, rhsExpr, isStrict); } return false; } @@ -3701,41 +3706,6 @@ 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) && - !this.isArkts12File(importSourceFile) && - this.isArkts12File(currentSourceFile) - ); - } - isArkts12File(sourceFile: ts.SourceFile): boolean { if (!sourceFile?.fileName) { return false; diff --git a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts index 1f26e36e86..a8b07dafce 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkTS2Rules.ts @@ -108,7 +108,6 @@ export const arkts2Rules: number[] = [ 321, 322, 323, - 324, 325, 326, 327, @@ -136,6 +135,7 @@ export const arkts2Rules: number[] = [ 349, 350, 351, + 352, 355, 356, 357, @@ -149,7 +149,9 @@ export const arkts2Rules: number[] = [ 375, 376, 377, - 378 + 378, + 381, + 382 ]; export const onlyArkts2SyntaxRules: Map = new Map([ @@ -193,5 +195,17 @@ export const onlyArkts2SyntaxRules: Map = new Map([ [255, 'arkts-no-extends-expression'], [300, 'arkts-no-ts-like-function-call'], [301, 'arkts-ohmurl-full-path'], - [304, 'arkts-no-duplicate-function-name'] + [304, 'arkts-no-duplicate-function-name'], + [319, 'arkts-method-inherit-rule'], + [325, 'arkts-default-args-behind-required-args'], + [329, 'arkts-unsupport-prop-name-from-value'], + [370, 'arkts-no-sparse-array'], + [371, 'arkts-no-enum-prop-as-type'], + [372, 'arkts-no-ts-like-smart-type'], + [373, 'arkts-array-type-immutable'], + [374, 'arkts-primitive-type-normalization'], + [375, 'arkts-no-ts-like-catch-type'], + [376, 'arkts-numeric-bigint-compare'], + [377, 'arkts-only-support-decimal-bigint-literal'], + [378, 'arkts-unsupport-operator'] ]); diff --git a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts index b12761975d..5405ffe91f 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkuiConstants.ts @@ -34,7 +34,8 @@ export enum CustomDecoratorName { AnimatableExtend = 'AnimatableExtend', Memo = 'Memo', Observed = 'Observed', - CustomLayout = 'CustomLayout' + CustomLayout = 'CustomLayout', + CustomStyles = 'CustomStyles' } export enum StorageTypeName { diff --git a/ets2panda/linter/src/lib/utils/consts/ArkuiImportList.ts b/ets2panda/linter/src/lib/utils/consts/ArkuiImportList.ts index 3adcc10ab5..3beae87577 100644 --- a/ets2panda/linter/src/lib/utils/consts/ArkuiImportList.ts +++ b/ets2panda/linter/src/lib/utils/consts/ArkuiImportList.ts @@ -57,6 +57,7 @@ export const arkuiImportList: Set = new Set([ 'Animator', 'AnimatorAttribute', 'AnimatorInterface', + 'applyStyles', 'AppRotation', 'AppStorage', 'AppearSymbolEffect', @@ -275,6 +276,7 @@ export const arkuiImportList: Set = new Set([ 'CustomSpanDrawInfo', 'CustomSpanMeasureInfo', 'CustomSpanMetrics', + 'CustomStyles', 'CustomTheme', 'CutEvent', 'DataAddOperation', @@ -1612,3 +1614,54 @@ export const arkuiImportList: Set = new Set([ 'sharedTransitionOptions', 'vp2px' ]); + +export const arkTsBuiltInTypeName: Set = new Set([ + 'Object', + 'Function', + 'Boolean', + 'Symbol', + 'Number', + 'BigInt', + 'Math', + 'Date', + 'String', + 'RegExp', + 'Array', + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'JSON', + 'Promise', + 'Generator', + 'GeneratorFunction', + 'AsyncFunction', + 'AsyncGenerator', + 'AsyncGeneratorFunction', + 'Reflect', + 'Proxy', + 'Error', + 'EvalError', + 'RangeError', + 'ReferenceError', + 'SyntaxError', + 'TypeError', + 'URIError', + 'AggregateError', + 'Intl', + 'WebAssembly' +]); \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/consts/AsyncLifecycleSDK.ts b/ets2panda/linter/src/lib/utils/consts/AsyncLifecycleSDK.ts new file mode 100644 index 0000000000..b589d85b4f --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/AsyncLifecycleSDK.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. + */ + +export const VOID = 'Void'; +export const PROMISE = 'Promise'; + +export const ON_DESTROY = 'onDestroy'; +export const ON_DISCONNECT = 'onDisconnect'; + +export const SERVICE_EXTENSION_ABILITY = 'ServiceExtensionAbility'; + +export const ABILITY_KIT = '@kit.AbilityKit'; + +export const ASYNC_LIFECYCLE_SDK_LIST = new Set([ + 'UIAbility', + 'UIExtensionAbility', + 'AutoFillExtensionAbility', + 'ServiceExtensionAbility' +]); diff --git a/ets2panda/linter/src/lib/utils/consts/ErrorProp.ts b/ets2panda/linter/src/lib/utils/consts/ErrorProp.ts index ce65497062..212bb02ae4 100644 --- a/ets2panda/linter/src/lib/utils/consts/ErrorProp.ts +++ b/ets2panda/linter/src/lib/utils/consts/ErrorProp.ts @@ -1,3 +1,4 @@ + /* * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,3 +15,9 @@ */ export const ERROR_PROP_LIST: Set = new Set(['name', 'message', 'stack', 'code']); + +export const ERROR_TASKPOOL_PROP_LIST: { [key: string]: Set } = { + 'taskpool.TaskInfo': new Set(['duration']), + 'taskpool.ThreadInfo': new Set(['taskIds', 'priority']), + 'StdProcess.ConditionType': new Set(['timeout', 'killSignal', 'maxBuffer']) +}; diff --git a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts index 285a75b407..afd7fcc087 100644 --- a/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/InteropAPI.ts @@ -39,6 +39,7 @@ export const REFLECT_PROPERTIES = [ 'isExtensible', 'preventExtensions' ]; + export const OBJECT_PROPERTIES = [ 'get', 'set', @@ -66,10 +67,8 @@ export const REFLECT_LITERAL = 'Reflect'; export const NONE = 'none'; export type ForbidenAPICheckResult = 'Object' | 'Reflect' | 'none'; 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 GET_PROPERTY = 'getProperty'; +export const SET_PROPERTY = 'setProperty'; export const TO_NUMBER = 'toNumber'; export enum InteropType { diff --git a/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts b/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts index ca9bdcd843..eeef04d78d 100644 --- a/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts +++ b/ets2panda/linter/src/lib/utils/consts/LimitedStdAPI.ts @@ -157,3 +157,6 @@ export const MODULE_IMPORTS: Record = { '@ohos.process': ['process'], '@ohos.taskpool': ['taskpool'] }; + +export const ARKTSUTILS_MODULES = ['@arkts.utils', '@kit.ArkTS']; +export const ARKTSUTILS_LOCKS_MEMBER = 'locks'; diff --git a/ets2panda/linter/src/lib/utils/consts/MapKeyConst.ts b/ets2panda/linter/src/lib/utils/consts/MapKeyConst.ts new file mode 100644 index 0000000000..e5689d3f2a --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/MapKeyConst.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. + */ + +export const TOTAL_PROBLEMS = 'totalProblems'; + +export const ONE_POINT_ONE_PROBLEMS = 'arts1.1_Problems'; + +export const ONE_POINT_TWO_PROBLEMS = 'arts1.2_Problems'; + +export const CAN_BE_AUTO_FIXED_PROBLEMS_NUMBERS = 'canBeAutoFixedproblemNumbers'; + +export const NEED_TO_NAMUAL_FIX_PROBLEM_NUMBERS = 'needToManualFixproblemNumbers'; + +export const SCAN_TIME = 'scanTime'; + +export const MIGRATION_TIME = 'migrationTime'; diff --git a/ets2panda/linter/src/lib/utils/consts/WorkloadRelatedConst.ts b/ets2panda/linter/src/lib/utils/consts/WorkloadRelatedConst.ts new file mode 100644 index 0000000000..c0c5efc0cc --- /dev/null +++ b/ets2panda/linter/src/lib/utils/consts/WorkloadRelatedConst.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 AVERAGE_LINE_FOR_REPAIRE_RULE_COEFFICIENT = 3; + +export const TEST_DEBUG_WORKLOAD_COEFFICIENT = 1.2; + +export const NPAI_REPAIRE_WORKLOADA_COEFFICIEN = 0.2; \ No newline at end of file diff --git a/ets2panda/linter/src/lib/utils/functions/ConfiguredRulesProcess.ts b/ets2panda/linter/src/lib/utils/functions/ConfiguredRulesProcess.ts new file mode 100644 index 0000000000..99e6c5da6f --- /dev/null +++ b/ets2panda/linter/src/lib/utils/functions/ConfiguredRulesProcess.ts @@ -0,0 +1,68 @@ +/* + * 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. + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +export function getConfiguredRuleTags( + arkTSRulesMap: Map, + configuredRulesMap: Map +): Set { + const mergedRulesMap: string[] = Array.from(configuredRulesMap.values()).flat(); + const configuredRuleTags = new Set(); + const mergedRulesSet = new Set(mergedRulesMap); + arkTSRulesMap.forEach((key, value) => { + if (mergedRulesSet.has(key)) { + configuredRuleTags.add(value); + } + }); + return configuredRuleTags; +} + +export function getRulesFromConfig(configRulePath: string): Map { + try { + const normalizedPath = path.normalize(configRulePath); + const data = fs.readFileSync(normalizedPath, 'utf-8'); + const jsonData = JSON.parse(data); + const dataMap = new Map(); + for (const [key, value] of Object.entries(jsonData)) { + dataMap.set(key, value); + } + return convertToStringArrayMap(dataMap); + } catch (error) { + if (error instanceof SyntaxError) { + throw new Error(`JSON parsing failed: ${error.message}`); + } + return new Map(); + } +} + +function convertToStringArrayMap(inputMap: Map): Map { + const resultMap: Map = new Map(); + for (const [key, value] of inputMap) { + if (isStringArray(value)) { + resultMap.set(key, value); + } + } + return resultMap; +} + +function isStringArray(value: any): value is string[] { + return ( + Array.isArray(value) && + value.every((item) => { + return typeof item === 'string'; + }) + ); +} diff --git a/ets2panda/linter/src/lib/utils/functions/CookBookUtils.ts b/ets2panda/linter/src/lib/utils/functions/CookBookUtils.ts new file mode 100644 index 0000000000..0f2bec5ade --- /dev/null +++ b/ets2panda/linter/src/lib/utils/functions/CookBookUtils.ts @@ -0,0 +1,35 @@ +/* + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 extractRuleTags(tags: string[]): Map { + const resultMap = new Map(); + + for (let i = 0; i < tags.length; i++) { + const tag = tags[i]; + + if (!tag?.trim()) { + continue; + } + + const regex = /\(([^)]+)\)/; + const match = tag.match(regex); + + if (match?.[1]?.trim()) { + resultMap.set(i, match[1]); + } + } + + return resultMap; +} diff --git a/ets2panda/linter/src/lib/utils/functions/ProcessWrite.ts b/ets2panda/linter/src/lib/utils/functions/ProcessWrite.ts new file mode 100644 index 0000000000..ef8e100ae8 --- /dev/null +++ b/ets2panda/linter/src/lib/utils/functions/ProcessWrite.ts @@ -0,0 +1,30 @@ +/* + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 async function processSyncOut(message: string): Promise { + await new Promise((resolve) => { + process.stdout.write(message, () => { + resolve('success'); + }); + }); +} + +export async function processSyncErr(message: string): Promise { + await new Promise((resolve) => { + process.stderr.write(message, () => { + resolve('success'); + }); + }); +} diff --git a/ets2panda/linter/src/testRunner/LintTest.ts b/ets2panda/linter/src/testRunner/LintTest.ts index 02db53dd49..8661ed7c74 100644 --- a/ets2panda/linter/src/testRunner/LintTest.ts +++ b/ets2panda/linter/src/testRunner/LintTest.ts @@ -15,20 +15,21 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; +import type { Autofix } from '../lib/autofixes/Autofixer'; import type { CommandLineOptions } from '../lib/CommandLineOptions'; import type { LinterConfig } from '../lib/LinterConfig'; import { lint } from '../lib/LinterRunner'; +import type { LintRunResult } from '../lib/LintRunResult'; import { Logger } from '../lib/Logger'; +import { TimeRecorder } from '../lib/statistics/scan/TimeRecorder'; import { compileLintOptions } from '../lib/ts-compiler/Compiler'; +import { DIFF_EXT, RESULTS_DIR, TAB } from './Consts'; +import type { CreateLintTestOptions } from './TestFactory'; 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'; +import { transformProblemInfos } from './TestUtil'; export class LintTest { readonly testDir: string; @@ -47,7 +48,8 @@ export class LintTest { Logger.info(`Running test ${this.testFile} (${TestMode[this.testModeProps.mode]} mode)`); const linterConfig = this.compile(); - const linterResult = lint(linterConfig); + const timeRecorder = new TimeRecorder(); + const linterResult = lint(linterConfig, timeRecorder); return this.validate(linterResult); } diff --git a/ets2panda/linter/src/testRunner/TestRunner.ts b/ets2panda/linter/src/testRunner/TestRunner.ts index 4d3639fb32..1f068e2f51 100755 --- a/ets2panda/linter/src/testRunner/TestRunner.ts +++ b/ets2panda/linter/src/testRunner/TestRunner.ts @@ -143,6 +143,21 @@ function runTests(): boolean { const { passed, failed } = testStats; Logger.info(`\nSUMMARY: ${passed + failed} total, ${passed} passed, ${failed} failed.`); Logger.info(failed > 0 ? '\nTEST FAILED' : '\nTEST SUCCESSFUL'); + + const saveCoverageData = (): void => { + const coverageData = globalThis.__coverage__; + if (coverageData) { + const projectRoot = path.resolve(__dirname, '../../..'); + const coverageDir = path.join(projectRoot, 'coverage'); + fs.mkdirSync(coverageDir, { recursive: true }); + + const coverageFile = path.join(coverageDir, 'coverage.json'); + fs.writeFileSync(coverageFile, JSON.stringify(coverageData, null, 4)); + } else { + console.log('no coverage data found'); + } + }; + saveCoverageData(); process.exit(failed > 0 ? -1 : 0); } diff --git a/ets2panda/linter/test/builtin/builtin_thisArgs.ets b/ets2panda/linter/test/builtin/builtin_thisArgs.ets index 2a73669055..b296e847c1 100755 --- a/ets2panda/linter/test/builtin/builtin_thisArgs.ets +++ b/ets2panda/linter/test/builtin/builtin_thisArgs.ets @@ -28,4 +28,12 @@ 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 +arr.filter(a.compare, b); + +type T = number | T[]; +let arr: ReadonlyArray = [[1.0, 2.0], 3.0, [4.0, 5.0]]; +arr.flatMap( + (value, index, array) => { + return value; + } +); \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets new file mode 100644 index 0000000000..3ad92e0865 --- /dev/null +++ b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.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 { ArkTSUtils } from '../main/oh_modules/@kit.ArkTS'; + +let lock1 = new ArkTSUtils.locks.AsyncLock(); + +let lock2 = new ArkTSUtils.locks.AsyncLock(); \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.arkts2.json b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.arkts2.json new file mode 100644 index 0000000000..31d218b8f0 --- /dev/null +++ b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.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": 28, + "endLine": 18, + "endColumn": 33, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 28, + "endLine": 20, + "endColumn": 33, + "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/concurrent/ no_support_arktsutils_locks_asynclock.ets.autofix.json b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.autofix.json new file mode 100644 index 0000000000..31d218b8f0 --- /dev/null +++ b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.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": 28, + "endLine": 18, + "endColumn": 33, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 28, + "endLine": 20, + "endColumn": 33, + "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/concurrent/ no_support_arktsutils_locks_asynclock.ets.json b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.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/ no_support_arktsutils_locks_asynclock.ets.migrate.ets b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.migrate.ets new file mode 100644 index 0000000000..c8cd4f5b48 --- /dev/null +++ b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.migrate.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 { ArkTSUtils } from '../main/oh_modules/@kit.ArkTS'; + +let lock1 = new ArkTSUtils.locks.AsyncLock(); + +let lock2 = new ArkTSUtils.locks.AsyncLock(); \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.migrate.json b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.ets.migrate.json new file mode 100644 index 0000000000..31d218b8f0 --- /dev/null +++ b/ets2panda/linter/test/concurrent/ no_support_arktsutils_locks_asynclock.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": 28, + "endLine": 18, + "endColumn": 33, + "problem": "LimitedStdLibNoImportConcurrency", + "suggest": "", + "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 28, + "endLine": 20, + "endColumn": 33, + "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/concurrent/no_support_isconcurrent.ets.arkts2.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json index 428032b2d8..9b627b9d72 100644 --- a/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent.ets.arkts2.json @@ -23,6 +23,26 @@ "suggest": "", "rule": "Usage of standard library is restricted(arkts-limited-stdlib-no-concurrent-decorator)", "severity": "ERROR" + }, + { + "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" } ] } \ No newline at end of file diff --git a/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.arkts2.json b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.arkts2.json index b418f42b21..bba9654328 100755 --- a/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.arkts2.json +++ b/ets2panda/linter/test/concurrent/no_support_isconcurrent2.ets.arkts2.json @@ -24,26 +24,6 @@ "rule": "Import Concurrency is not required (arkts-limited-stdlib-no-import-concurrency)", "severity": "ERROR" }, - { - "line": 23, - "column": 17, - "endLine": 23, - "endColumn": 29, - "problem": "IsConcurrentDeprecated", - "suggest": "", - "rule": "isConcurrent is not supported (arkts-limited-stdlib-no-support-isConcurrent)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 12, - "endLine": 25, - "endColumn": 24, - "problem": "IsConcurrentDeprecated", - "suggest": "", - "rule": "isConcurrent is not supported (arkts-limited-stdlib-no-support-isConcurrent)", - "severity": "ERROR" - }, { "line": 25, "column": 25, 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 8bf1b635a6..796dfbb772 100644 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 656, "end": 656, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./binary_operation_js_obj_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet m = GeneratedImportVar_1.getPropertyByName('m');\nlet n = GeneratedImportVar_1.getPropertyByName('n');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./binary_operation_js_obj_js');\nlet foo = GeneratedImportVar_1.getProperty('foo');\nlet m = GeneratedImportVar_1.getProperty('m');\nlet n = GeneratedImportVar_1.getProperty('n');\n", "line": 15, "column": 1, "endLine": 15, @@ -54,7 +54,7 @@ { "start": 665, "end": 670, - "replacementText": "foo.getPropertyByName(\"a\")", + "replacementText": "foo.getProperty(\"a\")", "line": 16, "column": 9, "endLine": 16, @@ -75,7 +75,7 @@ { "start": 679, "end": 684, - "replacementText": "foo.getPropertyByName(\"b\")", + "replacementText": "foo.getProperty(\"b\")", "line": 17, "column": 9, "endLine": 17, @@ -96,7 +96,7 @@ { "start": 665, "end": 670, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 18, "column": 1, "endLine": 18, @@ -117,7 +117,7 @@ { "start": 679, "end": 684, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 18, "column": 5, "endLine": 18, @@ -138,7 +138,7 @@ { "start": 665, "end": 670, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 19, "column": 1, "endLine": 19, @@ -159,7 +159,7 @@ { "start": 679, "end": 684, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 19, "column": 5, "endLine": 19, @@ -180,7 +180,7 @@ { "start": 665, "end": 670, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 20, "column": 1, "endLine": 20, @@ -201,7 +201,7 @@ { "start": 679, "end": 684, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 20, "column": 5, "endLine": 20, @@ -222,7 +222,7 @@ { "start": 665, "end": 670, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 21, "column": 1, "endLine": 21, @@ -243,7 +243,7 @@ { "start": 679, "end": 684, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 21, "column": 5, "endLine": 21, @@ -264,7 +264,7 @@ { "start": 665, "end": 670, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 22, "column": 1, "endLine": 22, @@ -285,7 +285,7 @@ { "start": 679, "end": 684, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 22, "column": 5, "endLine": 22, @@ -306,7 +306,7 @@ { "start": 665, "end": 670, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 23, "column": 1, "endLine": 23, @@ -327,7 +327,7 @@ { "start": 679, "end": 684, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 23, "column": 6, "endLine": 23, @@ -756,7 +756,7 @@ { "start": 884, "end": 889, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 43, "column": 1, "endLine": 43, @@ -777,7 +777,7 @@ { "start": 892, "end": 897, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 43, "column": 9, "endLine": 43, @@ -798,7 +798,7 @@ { "start": 884, "end": 889, - "replacementText": "foo.getPropertyByName(\"a\")", + "replacementText": "foo.getProperty(\"a\")", "line": 43, "column": 1, "endLine": 43, @@ -819,7 +819,7 @@ { "start": 892, "end": 897, - "replacementText": "foo.getPropertyByName(\"b\")", + "replacementText": "foo.getProperty(\"b\")", "line": 43, "column": 9, "endLine": 43, diff --git a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets index f29b91c275..f71f2540b4 100644 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.ets @@ -13,12 +13,12 @@ * limitations under the License. */ let GeneratedImportVar_1 = ESValue.load('./binary_operation_js_obj_js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); -let m = GeneratedImportVar_1.getPropertyByName('m'); -let n = GeneratedImportVar_1.getPropertyByName('n'); +let foo = GeneratedImportVar_1.getProperty('foo'); +let m = GeneratedImportVar_1.getProperty('m'); +let n = GeneratedImportVar_1.getProperty('n'); -let a = foo.getPropertyByName("a") -let b = foo.getPropertyByName("b") +let a = foo.getProperty("a") +let b = foo.getProperty("b") a + b a - b a * b @@ -48,4 +48,4 @@ x2 - y2; x2 % y2; Math.pow(x2, y2); -foo.getPropertyByName("a").toNumber() + foo.getPropertyByName("b").toNumber(); \ No newline at end of file +foo.getProperty("a").toNumber() + foo.getProperty("b").toNumber(); \ 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 index 817c2a9450..00ccbc39c6 100644 --- a/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.json +++ b/ets2panda/linter/test/interop/binary_operation_js_obj.ets.migrate.json @@ -28,7 +28,7 @@ "line": 16, "column": 5, "endLine": 16, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 17, "column": 5, "endLine": 17, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +48,7 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +58,7 @@ "line": 20, "column": 5, "endLine": 20, - "endColumn": 35, + "endColumn": 29, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 21, "column": 5, "endLine": 21, - "endColumn": 35, + "endColumn": 29, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", 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 5776d747e9..ca67f37978 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 650, "end": 650, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./call_object_methods_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./call_object_methods_js');\nlet foo = GeneratedImportVar_1.getProperty('foo');\n", "line": 15, "column": 1, "endLine": 15, diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets index 2d455bda8e..600a9cadac 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets +++ b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.ets @@ -13,7 +13,7 @@ * limitations under the License. */ let GeneratedImportVar_1 = ESValue.load('./call_object_methods_js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let foo = GeneratedImportVar_1.getProperty('foo'); foo.invokeMethod("bar", ESValue.wrap(123.0)) diff --git a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json index 4f96146af1..ccc6caf0a4 100644 --- a/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json +++ b/ets2panda/linter/test/interop/call_object_methods.ets.migrate.json @@ -28,7 +28,7 @@ "line": 16, "column": 5, "endLine": 16, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", diff --git a/ets2panda/linter/test/interop/ignore_files/unique_types.ts b/ets2panda/linter/test/interop/ignore_files/unique_types.ts index 1c19752b63..f56856f73a 100644 --- a/ets2panda/linter/test/interop/ignore_files/unique_types.ts +++ b/ets2panda/linter/test/interop/ignore_files/unique_types.ts @@ -13,24 +13,217 @@ * limitations under the License. */ -type SomeType = { - name: string, +// any 类型 +let any_var: any = 10; +any_var = "string"; +export {any_var} + +// unknown类型 +export let unknown_var:unknown = 10; + +// Symbol类型 +export let symbol_var: symbol = Symbol("description"); + +// Function类型 +export let function_var: Function = function() { + console.log("Hello, World!"); + return true; +}; + +export class A { + static instance = new A(); } -enum X { - a = 0, - b = '1', +export interface B { + name:string } -type UnionString = "A" | "B"; -type TemplateLiteralType = `${UnionString}_id`; +//用例一 +export function throw_number() { + throw 123; +} -export let objectLiteralType: SomeType; -export let mixedEnumType: X; -export let intersectionType: SomeType & X; -export let templateLiteralType: TemplateLiteralType; +export function throw_string() { + throw "error"; +} -export function tsFunction() { - throw 123; -}; -export let stringType: string; +export function throw_boolean() { + throw true; +} + +export function throw_bigint() { + throw 111n; +} + +export function throw_obj() { + throw { name:'error' }; +} + +export function throw_error() { + throw new Error("error"); +} + +export class SubError extends Error { + extraField: number = 123; + foo() { return 456; } +} + +export function throwErrorSubClass() { + throw new SubError(); +} +export function throwRangeError() { + throw new RangeError(); +} + +//用例二 +export class ObjectLiteralClass { + name:string = "" +} + +export interface ObjectLiteralInter { + name:string +} +//用例三 +//类装饰器 +export function MyClassDecorator(klass: Object) {} + +//属性装饰器 +export function propertyDecorator(target: Object, propertyKey: string) { + console.log(Property Decorator called on: ${target.constructor.name} with propertyKey: ${propertyKey}); +} + +//方法装饰器 +export function methodDecorator(target: Object, propertyKey: string , descriptor: PropertyDescriptor) { + console.log(Method Decorator called on: ${target.constructor.name} with propertyKey: ${propertyKey}); + descriptor.value = function (...args: any[]) { + console.log(Called: ${propertyKey} with, args); + return args[0] * 2; + }; + return descriptor; +} + +// 参数装饰器 +export function parameterDecorator(target: Object, propertyKey: string , parameterIndex: number) { + console.log(Parameter Decorator called on: ${target.constructor.name} with propertyKey: ${propertyKey} and parameterIndex: ${parameterIndex}); +} + +// 访问器装饰器 +export function accessorDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) { + const originalGet = descriptor.get; + const originalSet = descriptor.set; + + descriptor.get = function() { + console.log(Getter for ${propertyKey} called.); + return originalGet.apply(this); + }; + descriptor.set = function(value) { + console.log(Setter for ${propertyKey} called with value: ${value}); + originalSet.apply(this, [value]); + }; + return descriptor; +} + +// 装饰器工厂 +export function readonly1(isReadonly: boolean) { + return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { + if (isReadonly) { + descriptor.writable = false; + } + }; +} + +export let num_boxed = new Number(123) +export let bool_boxed = new Boolean(true) +export let str_boxed = new String('hello') +export let bigint_boxed = BigInt(123n) + +export function ts_object_method(prx: any) { + Object.getOwnPropertyDescriptor(prx, "a") // arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-limited-stdlib not undefined + Object.getOwnPropertyDescriptors(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 not {} + Object.getOwnPropertyNames(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 ["a"] + Object.hasOwn(prx, "a") // true + Object.isExtensible(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true + Object.isFrozen(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 false + Object.isSealed(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 false + Object.keys(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 ["a"] + Object.setPrototypeOf(prx, {}) // arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-limited-stdlib OK + Object.values(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-no-inferred-generic-params [1] + prx.hasOwnProperty("a") // true + prx.propertyIsEnumerable("a") // true +} + +export function ts_object_method_getOwnPropertyDescriptor(prx: any) { + return Object.getOwnPropertyDescriptor(prx, "a") // arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-limited-stdlib not undefined +} +export function ts_object_method_getOwnPropertyDescriptors(prx: any) { + return Object.getOwnPropertyDescriptors(prx)// arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-limited-stdlib not {} +} +export function ts_object_method_getOwnPropertyNames(prx: any) { + return Object.getOwnPropertyNames(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 ["a"] +} +export function ts_object_method_hasOwn(prx: any) { + return Object.hasOwn(prx, "a") // true +} +export function ts_object_method_isExtensible(prx: any) { + return Object.isExtensible(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-limited-stdlib true +} +export function ts_object_method_isFrozen(prx: any) { + return Object.isFrozen(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-limited-stdlib false +} + +export function ts_object_method_isSealed(prx: any) { + return Object.isSealed(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-limited-stdlib false +} + +export function ts_object_method_keys(prx: any) { + return Object.keys(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 3 ["a"] +} + +export function ts_object_method_setPrototypeOf(prx: any) { + return Object.setPrototypeOf(prx, {}) // arkts-limited-stdlib OK +} + +export function ts_object_method_values(prx: any) { + return Object.values(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 + arkts-no-inferred-generic-params [1] +} + +interface Iface { + a:number +} +export let interObj:Iface = {a:1} + +export function ts_reflect_method(prx: any) { + Reflect.apply(prx.getName, {a: 12}) // arkts-interop-ts2s-ts-object-on-static-instance * 2 12 + Reflect.defineProperty(prx, 'newField', {value: 7}) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true + Reflect.deleteProperty(prx, "a") // arkts-interop-ts2s-ts-object-on-static-instance * 2 true + Reflect.getOwnPropertyDescriptor(prx, "a") // arkts-interop-ts2s-ts-object-on-static-instance * 2 not undefined + Reflect.ownKeys(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 ['a'] + Reflect.isExtensible(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true + Reflect.set(prx, 'newField', 7) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true + Reflect.setPrototypeOf(prx, {}) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true +} + +export function ts_reflect_method_apply(prx: any) { + Reflect.apply(prx.getName, {a: 12}) // arkts-interop-ts2s-ts-object-on-static-instance * 2 12 +} +export function ts_reflect_method_defineProperty(prx: any) { + Reflect.defineProperty(prx, 'newField', {value: 7}) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true +} +export function ts_reflect_method_deleteProperty(prx: any) { + Reflect.deleteProperty(prx, "a") // arkts-interop-ts2s-ts-object-on-static-instance * 2 true +} +export function ts_reflect_method_getOwnPropertyDescriptor(prx: any) { + Reflect.getOwnPropertyDescriptor(prx, "a") // arkts-interop-ts2s-ts-object-on-static-instance * 2 not undefined +} +export function ts_reflect_method_ownKeys(prx: any) { + Reflect.ownKeys(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 ['a'] +} +export function ts_reflect_method_isExtensible(prx: any) { + Reflect.isExtensible(prx) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true +} +export function ts_reflect_method_set(prx: any) { + Reflect.set(prx, 'newField', 7) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true +} +export function ts_reflect_method_setPrototypeOf(prx: any) { + Reflect.setPrototypeOf(prx, {}) // arkts-interop-ts2s-ts-object-on-static-instance * 2 true +} \ 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 index e48a8565b9..a0e63a21c5 100644 --- 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,7 +14,7 @@ "limitations under the License." ], "result": [ - { + { "line": 15, "column": 1, "endLine": 15, @@ -33,7 +33,7 @@ { "start": 655, "end": 655, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./increases_decreases_js_obj_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./increases_decreases_js_obj_js');\nlet foo = GeneratedImportVar_1.getProperty('foo');\n", "line": 15, "column": 1, "endLine": 15, @@ -73,7 +73,7 @@ "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "a = foo.getPropertyByName(\"num\").toNumber()\nfoo.setPropertyByName(num, a + 1)\na = a + 1\n", + "replacementText": "a = foo.getProperty(\"num\").toNumber()\nfoo.setProperty(num, a + 1)\na = a + 1\n", "start": 673, "end": 686, "line": 17, @@ -96,7 +96,7 @@ { "start": 677, "end": 684, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 17, "column": 5, "endLine": 17, @@ -115,7 +115,7 @@ "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "a = foo.getPropertyByName(\"num\").toNumber()\na = a + 1\nfoo.setPropertyByName(num, a)\n", + "replacementText": "a = foo.getProperty(\"num\").toNumber()\na = a + 1\nfoo.setProperty(num, a)\n", "start": 687, "end": 700, "line": 18, @@ -138,7 +138,7 @@ { "start": 693, "end": 700, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 18, "column": 7, "endLine": 18, @@ -157,7 +157,7 @@ "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "a = foo.getPropertyByName(\"num\").toNumber()\nfoo.setPropertyByName(num, a - 1)\na = a - 1\n", + "replacementText": "a = foo.getProperty(\"num\").toNumber()\nfoo.setProperty(num, a - 1)\na = a - 1\n", "start": 701, "end": 714, "line": 19, @@ -180,7 +180,7 @@ { "start": 705, "end": 712, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 19, "column": 5, "endLine": 19, @@ -199,7 +199,7 @@ "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "a = foo.getPropertyByName(\"num\").toNumber()\na = a - 1\nfoo.setPropertyByName(num, a)\n", + "replacementText": "a = foo.getProperty(\"num\").toNumber()\na = a - 1\nfoo.setProperty(num, a)\n", "start": 715, "end": 728, "line": 20, @@ -222,7 +222,7 @@ { "start": 721, "end": 728, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 20, "column": 7, "endLine": 20, @@ -241,7 +241,7 @@ "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "let tmp_1 = foo.getPropertyByName(\"num\").toNumber()\nfoo.setPropertyByName(num, tmp_1 + 1)\ntmp_1 = tmp_1 + 1\n", + "replacementText": "let tmp_1 = foo.getProperty(\"num\").toNumber()\nfoo.setProperty(num, tmp_1 + 1)\ntmp_1 = tmp_1 + 1\n", "start": 730, "end": 739, "line": 22, @@ -264,7 +264,7 @@ { "start": 730, "end": 737, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 22, "column": 1, "endLine": 22, @@ -283,7 +283,7 @@ "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "let tmp_2 = foo.getPropertyByName(\"num\").toNumber()\ntmp_2 = tmp_2 + 1\nfoo.setPropertyByName(num, tmp_2)\n", + "replacementText": "let tmp_2 = foo.getProperty(\"num\").toNumber()\ntmp_2 = tmp_2 + 1\nfoo.setProperty(num, tmp_2)\n", "start": 740, "end": 749, "line": 23, @@ -306,7 +306,7 @@ { "start": 742, "end": 749, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 23, "column": 3, "endLine": 23, @@ -325,7 +325,7 @@ "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "let tmp_3 = foo.getPropertyByName(\"num\").toNumber()\nfoo.setPropertyByName(num, tmp_3 - 1)\ntmp_3 = tmp_3 - 1\n", + "replacementText": "let tmp_3 = foo.getProperty(\"num\").toNumber()\nfoo.setProperty(num, tmp_3 - 1)\ntmp_3 = tmp_3 - 1\n", "start": 750, "end": 759, "line": 24, @@ -348,7 +348,7 @@ { "start": 750, "end": 757, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 24, "column": 1, "endLine": 24, @@ -367,7 +367,7 @@ "problem": "InteropIncrementDecrement", "autofix": [ { - "replacementText": "let tmp_4 = foo.getPropertyByName(\"num\").toNumber()\ntmp_4 = tmp_4 - 1\nfoo.setPropertyByName(num, tmp_4)\n", + "replacementText": "let tmp_4 = foo.getProperty(\"num\").toNumber()\ntmp_4 = tmp_4 - 1\nfoo.setProperty(num, tmp_4)\n", "start": 760, "end": 769, "line": 25, @@ -390,7 +390,7 @@ { "start": 762, "end": 769, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 25, "column": 3, "endLine": 25, 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 index f022ce0834..276cf1196d 100644 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.ets +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.ets @@ -13,39 +13,39 @@ * limitations under the License. */ let GeneratedImportVar_1 = ESValue.load('./increases_decreases_js_obj_js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let foo = GeneratedImportVar_1.getProperty('foo'); let a: number =0.0 -a = foo.getPropertyByName("num").toNumber() -foo.setPropertyByName(num, a + 1.0) +a = foo.getProperty("num").toNumber() +foo.setProperty(num, a + 1.0) a = a + 1.0 -a = foo.getPropertyByName("num").toNumber() +a = foo.getProperty("num").toNumber() a = a + 1.0 -foo.setPropertyByName(num, a) +foo.setProperty(num, a) -a = foo.getPropertyByName("num").toNumber() -foo.setPropertyByName(num, a - 1.0) +a = foo.getProperty("num").toNumber() +foo.setProperty(num, a - 1.0) a = a - 1.0 -a = foo.getPropertyByName("num").toNumber() +a = foo.getProperty("num").toNumber() a = a - 1.0 -foo.setPropertyByName(num, a) +foo.setProperty(num, a) -let tmp_1 = foo.getPropertyByName("num").toNumber() -foo.setPropertyByName(num, tmp_1 + 1.0) +let tmp_1 = foo.getProperty("num").toNumber() +foo.setProperty(num, tmp_1 + 1.0) tmp_1 = tmp_1 + 1.0 -let tmp_2 = foo.getPropertyByName("num").toNumber() +let tmp_2 = foo.getProperty("num").toNumber() tmp_2 = tmp_2 + 1.0 -foo.setPropertyByName(num, tmp_2) +foo.setProperty(num, tmp_2) -let tmp_3 = foo.getPropertyByName("num").toNumber() -foo.setPropertyByName(num, tmp_3 - 1.0) +let tmp_3 = foo.getProperty("num").toNumber() +foo.setProperty(num, tmp_3 - 1.0) tmp_3 = tmp_3 - 1.0 -let tmp_4 = foo.getPropertyByName("num").toNumber() +let tmp_4 = foo.getProperty("num").toNumber() tmp_4 = tmp_4 - 1.0 -foo.setPropertyByName(num, tmp_4) +foo.setProperty(num, tmp_4) 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 index 0a10b6a69e..78b7199f4f 100644 --- a/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.json +++ b/ets2panda/linter/test/interop/increases_decreases_js_obj.ets.migrate.json @@ -28,7 +28,7 @@ "line": 16, "column": 5, "endLine": 16, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 36, "column": 5, "endLine": 36, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +48,7 @@ "line": 40, "column": 5, "endLine": 40, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +58,7 @@ "line": 44, "column": 5, "endLine": 44, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 48, "column": 5, "endLine": 48, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", 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 f9ae170771..c0509f85ea 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 655, "end": 655, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./instantiated_js_obj_js');\nlet Foo = GeneratedImportVar_1.getPropertyByName('Foo');\nlet Foo1 = GeneratedImportVar_1.getPropertyByName('Foo1');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./instantiated_js_obj_js');\nlet Foo = GeneratedImportVar_1.getProperty('Foo');\nlet Foo1 = GeneratedImportVar_1.getProperty('Foo1');\n", "line": 16, "column": 1, "endLine": 16, diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets index b033816ddb..754fa9a041 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.ets @@ -14,8 +14,8 @@ */ let GeneratedImportVar_1 = ESValue.load('./instantiated_js_obj_js'); -let Foo = GeneratedImportVar_1.getPropertyByName('Foo'); -let Foo1 = GeneratedImportVar_1.getPropertyByName('Foo1'); +let Foo = GeneratedImportVar_1.getProperty('Foo'); +let Foo1 = GeneratedImportVar_1.getProperty('Foo1'); class A { num: number = 1.0; diff --git a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json index 2084de8763..5c043e26be 100644 --- a/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json +++ b/ets2panda/linter/test/interop/instantiated_js_obj.ets.migrate.json @@ -28,7 +28,7 @@ "line": 17, "column": 5, "endLine": 17, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets b/ets2panda/linter/test/interop/interop_convert_import.ets index 02426a4318..ea40300e23 100644 --- a/ets2panda/linter/test/interop/interop_convert_import.ets +++ b/ets2panda/linter/test/interop/interop_convert_import.ets @@ -1,4 +1,3 @@ -<<<<<<< HEAD /* * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -39,27 +38,4 @@ return null_val as null === null;// 扫描出 arkts-interop-js2s-convert-js-type // convert type - undefined test_helper.test(() => { return undefined_val as undefined === undefined; // 扫描出 arkts-interop-js2s-convert-js-type - no pass -}, "undefined_val as undefined === undefined"); -======= -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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, foo2, foo3, foo4} from "./interop_convert_import_js.js" - - 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" ->>>>>>> efeb0a81e (modify use static spec) +}, "undefined_val as undefined === undefined"); 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 d6f91a557d..2891efe2d7 100644 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.arkts2.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 18, + "line": 17, "column": 2, - "endLine": 18, + "endLine": 17, "endColumn": 106, "problem": "ImportAfterStatement", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 2, - "endLine": 18, + "endLine": 17, "endColumn": 106, "problem": "InterOpImportJs", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 19, "column": 18, - "endLine": 20, + "endLine": 19, "endColumn": 35, "problem": "InterOpConvertImport", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 19, "column": 18, - "endLine": 20, + "endLine": 19, "endColumn": 25, "problem": "InteropObjectProperty", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 20, "column": 20, - "endLine": 21, + "endLine": 20, "endColumn": 41, "problem": "InterOpConvertImport", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 20, "column": 20, - "endLine": 21, + "endLine": 20, "endColumn": 29, "problem": "InteropObjectProperty", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 22, + "line": 21, "column": 19, - "endLine": 22, + "endLine": 21, "endColumn": 38, "problem": "InterOpConvertImport", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 22, + "line": 21, "column": 19, - "endLine": 22, + "endLine": 21, "endColumn": 27, "problem": "InteropObjectProperty", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 23, + "line": 22, "column": 19, - "endLine": 23, + "endLine": 22, "endColumn": 38, "problem": "InterOpConvertImport", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 23, + "line": 22, "column": 19, - "endLine": 23, + "endLine": 22, "endColumn": 27, "problem": "InteropObjectProperty", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 9, - "endLine": 26, + "endLine": 25, "endColumn": 27, "problem": "InterOpConvertImport", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 44, - "endLine": 26, + "endLine": 25, "endColumn": 62, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 54, - "endLine": 26, + "endLine": 25, "endColumn": 55, "problem": "NumericSemantics", "suggest": "", @@ -145,9 +145,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 57, - "endLine": 26, + "endLine": 25, "endColumn": 58, "problem": "NumericSemantics", "suggest": "", @@ -155,9 +155,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 60, - "endLine": 26, + "endLine": 25, "endColumn": 61, "problem": "NumericSemantics", "suggest": "", @@ -165,9 +165,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 9, - "endLine": 31, + "endLine": 30, "endColumn": 30, "problem": "InterOpConvertImport", "suggest": "", @@ -175,9 +175,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 48, - "endLine": 31, + "endLine": 30, "endColumn": 49, "problem": "NumericSemantics", "suggest": "", @@ -185,9 +185,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 50, - "endLine": 31, + "endLine": 30, "endColumn": 51, "problem": "NumericSemantics", "suggest": "", @@ -195,9 +195,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 52, - "endLine": 31, + "endLine": 30, "endColumn": 53, "problem": "NumericSemantics", "suggest": "", @@ -205,9 +205,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 35, "column": 8, - "endLine": 36, + "endLine": 35, "endColumn": 24, "problem": "InterOpConvertImport", "suggest": "", @@ -215,9 +215,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 40, "column": 8, - "endLine": 41, + "endLine": 40, "endColumn": 34, "problem": "InterOpConvertImport", "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.autofix.json b/ets2panda/linter/test/interop/interop_convert_import.ets.autofix.json index b49b275bb5..f2a8c5c3a4 100644 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.autofix.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 18, + "line": 17, "column": 2, - "endLine": 18, + "endLine": 17, "endColumn": 106, "problem": "ImportAfterStatement", "suggest": "", @@ -25,28 +25,28 @@ "severity": "ERROR" }, { - "line": 18, + "line": 17, "column": 2, - "endLine": 18, + "endLine": 17, "endColumn": 106, "problem": "InterOpImportJs", "autofix": [ { - "start": 649, - "end": 753, + "start": 636, + "end": 740, "replacementText": "", - "line": 18, + "line": 17, "column": 2, - "endLine": 18, + "endLine": 17, "endColumn": 106 }, { - "start": 753, - "end": 753, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_convert_import_js.js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet foo2 = GeneratedImportVar_1.getPropertyByName('foo2');\nlet foo3 = GeneratedImportVar_1.getPropertyByName('foo3');\nlet foo4 = GeneratedImportVar_1.getPropertyByName('foo4');\nlet array_val = GeneratedImportVar_1.getPropertyByName('array_val');\nlet null_val = GeneratedImportVar_1.getPropertyByName('null_val');\nlet undefined_val = GeneratedImportVar_1.getPropertyByName('undefined_val');\n", - "line": 18, + "start": 740, + "end": 740, + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_convert_import_js.js');\r\nlet foo = GeneratedImportVar_1.getProperty('foo');\r\nlet foo2 = GeneratedImportVar_1.getProperty('foo2');\r\nlet foo3 = GeneratedImportVar_1.getProperty('foo3');\r\nlet foo4 = GeneratedImportVar_1.getProperty('foo4');\r\nlet array_val = GeneratedImportVar_1.getProperty('array_val');\r\nlet null_val = GeneratedImportVar_1.getProperty('null_val');\r\nlet undefined_val = GeneratedImportVar_1.getProperty('undefined_val');\r\n", + "line": 17, "column": 2, - "endLine": 18, + "endLine": 17, "endColumn": 106 } ], @@ -55,19 +55,19 @@ "severity": "ERROR" }, { - "line": 20, + "line": 19, "column": 18, - "endLine": 20, + "endLine": 19, "endColumn": 35, "problem": "InterOpConvertImport", "autofix": [ { - "start": 774, - "end": 791, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", - "line": 20, + "start": 761, + "end": 778, + "replacementText": "foo.getProperty(\"num\").toNumber()", + "line": 19, "column": 18, - "endLine": 20, + "endLine": 19, "endColumn": 35 } ], @@ -76,19 +76,19 @@ "severity": "ERROR" }, { - "line": 20, + "line": 19, "column": 18, - "endLine": 20, + "endLine": 19, "endColumn": 25, "problem": "InteropObjectProperty", "autofix": [ { - "start": 774, - "end": 781, - "replacementText": "foo.getPropertyByName(\"num\")", - "line": 20, + "start": 761, + "end": 768, + "replacementText": "foo.getProperty(\"num\")", + "line": 19, "column": 18, - "endLine": 20, + "endLine": 19, "endColumn": 25 } ], @@ -97,19 +97,19 @@ "severity": "ERROR" }, { - "line": 21, + "line": 20, "column": 20, - "endLine": 21, + "endLine": 20, "endColumn": 41, "problem": "InterOpConvertImport", "autofix": [ { - "start": 812, - "end": 833, - "replacementText": "foo2.getPropertyByName(\"bool\").toBoolean()", - "line": 21, + "start": 799, + "end": 820, + "replacementText": "foo2.getProperty(\"bool\").toBoolean()", + "line": 20, "column": 20, - "endLine": 21, + "endLine": 20, "endColumn": 41 } ], @@ -118,19 +118,19 @@ "severity": "ERROR" }, { - "line": 21, + "line": 20, "column": 20, - "endLine": 21, + "endLine": 20, "endColumn": 29, "problem": "InteropObjectProperty", "autofix": [ { - "start": 812, - "end": 821, - "replacementText": "foo2.getPropertyByName(\"bool\")", - "line": 21, + "start": 799, + "end": 808, + "replacementText": "foo2.getProperty(\"bool\")", + "line": 20, "column": 20, - "endLine": 21, + "endLine": 20, "endColumn": 29 } ], @@ -139,19 +139,19 @@ "severity": "ERROR" }, { - "line": 22, + "line": 21, "column": 19, - "endLine": 22, + "endLine": 21, "endColumn": 38, "problem": "InterOpConvertImport", "autofix": [ { - "start": 853, - "end": 872, - "replacementText": "foo3.getPropertyByName(\"str\").toString()", - "line": 22, + "start": 840, + "end": 859, + "replacementText": "foo3.getProperty(\"str\").toString()", + "line": 21, "column": 19, - "endLine": 22, + "endLine": 21, "endColumn": 38 } ], @@ -160,19 +160,19 @@ "severity": "ERROR" }, { - "line": 22, + "line": 21, "column": 19, - "endLine": 22, + "endLine": 21, "endColumn": 27, "problem": "InteropObjectProperty", "autofix": [ { - "start": 853, - "end": 861, - "replacementText": "foo3.getPropertyByName(\"str\")", - "line": 22, + "start": 840, + "end": 848, + "replacementText": "foo3.getProperty(\"str\")", + "line": 21, "column": 19, - "endLine": 22, + "endLine": 21, "endColumn": 27 } ], @@ -181,19 +181,19 @@ "severity": "ERROR" }, { - "line": 23, + "line": 22, "column": 19, - "endLine": 23, + "endLine": 22, "endColumn": 38, "problem": "InterOpConvertImport", "autofix": [ { - "start": 892, - "end": 911, - "replacementText": "foo4.getPropertyByName(\"big\").toBigInt()", - "line": 23, + "start": 879, + "end": 898, + "replacementText": "foo4.getProperty(\"big\").toBigInt()", + "line": 22, "column": 19, - "endLine": 23, + "endLine": 22, "endColumn": 38 } ], @@ -202,19 +202,19 @@ "severity": "ERROR" }, { - "line": 23, + "line": 22, "column": 19, - "endLine": 23, + "endLine": 22, "endColumn": 27, "problem": "InteropObjectProperty", "autofix": [ { - "start": 892, - "end": 900, - "replacementText": "foo4.getPropertyByName(\"big\")", - "line": 23, + "start": 879, + "end": 887, + "replacementText": "foo4.getProperty(\"big\")", + "line": 22, "column": 19, - "endLine": 23, + "endLine": 22, "endColumn": 27 } ], @@ -223,9 +223,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 9, - "endLine": 26, + "endLine": 25, "endColumn": 27, "problem": "InterOpConvertImport", "suggest": "", @@ -233,9 +233,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 44, - "endLine": 26, + "endLine": 25, "endColumn": 62, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -243,19 +243,19 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 54, - "endLine": 26, + "endLine": 25, "endColumn": 55, "problem": "NumericSemantics", "autofix": [ { - "start": 994, - "end": 995, + "start": 981, + "end": 982, "replacementText": "1.0", - "line": 26, + "line": 25, "column": 54, - "endLine": 26, + "endLine": 25, "endColumn": 55 } ], @@ -264,19 +264,19 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 57, - "endLine": 26, + "endLine": 25, "endColumn": 58, "problem": "NumericSemantics", "autofix": [ { - "start": 997, - "end": 998, + "start": 984, + "end": 985, "replacementText": "2.0", - "line": 26, + "line": 25, "column": 57, - "endLine": 26, + "endLine": 25, "endColumn": 58 } ], @@ -285,19 +285,19 @@ "severity": "ERROR" }, { - "line": 26, + "line": 25, "column": 60, - "endLine": 26, + "endLine": 25, "endColumn": 61, "problem": "NumericSemantics", "autofix": [ { - "start": 1000, - "end": 1001, + "start": 987, + "end": 988, "replacementText": "3.0", - "line": 26, + "line": 25, "column": 60, - "endLine": 26, + "endLine": 25, "endColumn": 61 } ], @@ -306,9 +306,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 9, - "endLine": 31, + "endLine": 30, "endColumn": 30, "problem": "InterOpConvertImport", "suggest": "", @@ -316,19 +316,19 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 48, - "endLine": 31, + "endLine": 30, "endColumn": 49, "problem": "NumericSemantics", "autofix": [ { - "start": 1208, - "end": 1209, + "start": 1195, + "end": 1196, "replacementText": "1.0", - "line": 31, + "line": 30, "column": 48, - "endLine": 31, + "endLine": 30, "endColumn": 49 } ], @@ -337,19 +337,19 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 50, - "endLine": 31, + "endLine": 30, "endColumn": 51, "problem": "NumericSemantics", "autofix": [ { - "start": 1210, - "end": 1211, + "start": 1197, + "end": 1198, "replacementText": "2.0", - "line": 31, + "line": 30, "column": 50, - "endLine": 31, + "endLine": 30, "endColumn": 51 } ], @@ -358,19 +358,19 @@ "severity": "ERROR" }, { - "line": 31, + "line": 30, "column": 52, - "endLine": 31, + "endLine": 30, "endColumn": 53, "problem": "NumericSemantics", "autofix": [ { - "start": 1212, - "end": 1213, + "start": 1199, + "end": 1200, "replacementText": "3.0", - "line": 31, + "line": 30, "column": 52, - "endLine": 31, + "endLine": 30, "endColumn": 53 } ], @@ -379,9 +379,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 35, "column": 8, - "endLine": 36, + "endLine": 35, "endColumn": 24, "problem": "InterOpConvertImport", "suggest": "", @@ -389,9 +389,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 40, "column": 8, - "endLine": 41, + "endLine": 40, "endColumn": 34, "problem": "InterOpConvertImport", "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.json b/ets2panda/linter/test/interop/interop_convert_import.ets.json index 5a3f5938e4..98f171cc32 100755 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 18, + "line": 17, "column": 2, - "endLine": 18, + "endLine": 17, "endColumn": 106, "problem": "ImportAfterStatement", "suggest": "", diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.ets b/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.ets index 1e107cf338..2c49f3dc58 100644 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.ets @@ -1,4 +1,3 @@ -<<<<<<< HEAD /* * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,20 +14,20 @@ */ 'use static' - let GeneratedImportVar_1 = ESValue.load('./interop_convert_import_js.js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); -let foo2 = GeneratedImportVar_1.getPropertyByName('foo2'); -let foo3 = GeneratedImportVar_1.getPropertyByName('foo3'); -let foo4 = GeneratedImportVar_1.getPropertyByName('foo4'); -let array_val = GeneratedImportVar_1.getPropertyByName('array_val'); -let null_val = GeneratedImportVar_1.getPropertyByName('null_val'); -let undefined_val = GeneratedImportVar_1.getPropertyByName('undefined_val'); + let GeneratedImportVar_1 = ESValue.load('./interop_convert_import_js.js'); +let foo = GeneratedImportVar_1.getProperty('foo'); +let foo2 = GeneratedImportVar_1.getProperty('foo2'); +let foo3 = GeneratedImportVar_1.getProperty('foo3'); +let foo4 = GeneratedImportVar_1.getProperty('foo4'); +let array_val = GeneratedImportVar_1.getProperty('array_val'); +let null_val = GeneratedImportVar_1.getProperty('null_val'); +let undefined_val = GeneratedImportVar_1.getProperty('undefined_val'); - let a: number = foo.getPropertyByName("num").toNumber() - let a1: boolean = foo2.getPropertyByName("bool").toBoolean() - let a2: string = foo3.getPropertyByName("str").toString() - let a3: bigint = foo4.getPropertyByName("big").toBigInt() + let a: number = foo.getProperty("num").toNumber() + let a1: boolean = foo2.getProperty("bool").toBoolean() + let a2: string = foo3.getProperty("str").toString() + let a3: bigint = foo4.getProperty("big").toBigInt() test_helper.test(() => { return (array_val as Array).toString() === new Array(1.0, 2.0, 3.0).toString();// 扫描出 arkts-interop-js2s-convert-js-type - no pass @@ -47,27 +46,4 @@ return null_val as null === null;// 扫描出 arkts-interop-js2s-convert-js-type // convert type - undefined test_helper.test(() => { return undefined_val as undefined === undefined; // 扫描出 arkts-interop-js2s-convert-js-type - no pass -}, "undefined_val as undefined === undefined"); -======= -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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, foo2, foo3, foo4} from "./interop_convert_import_js.js" - - 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" ->>>>>>> efeb0a81e (modify use static spec) +}, "undefined_val as undefined === undefined"); diff --git a/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.json b/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.json index a49b70a952..52e07c8a2b 100644 --- a/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_convert_import.ets.migrate.json @@ -15,20 +15,30 @@ ], "result": [ { - "line": 18, + "line": 17, "column": 6, - "endLine": 18, + "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": 50, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, { "line": 19, "column": 5, "endLine": 19, - "endColumn": 56, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +48,7 @@ "line": 20, "column": 5, "endLine": 20, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +58,7 @@ "line": 21, "column": 5, "endLine": 21, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +68,7 @@ "line": 22, "column": 5, "endLine": 22, - "endColumn": 58, + "endColumn": 62, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +78,7 @@ "line": 23, "column": 5, "endLine": 23, - "endColumn": 68, + "endColumn": 60, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -78,26 +88,16 @@ "line": 24, "column": 5, "endLine": 24, - "endColumn": 66, - "problem": "AnyType", - "suggest": "", - "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", - "severity": "ERROR" - }, - { - "line": 25, - "column": 5, - "endLine": 25, - "endColumn": 76, + "endColumn": 70, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" }, { - "line": 34, + "line": 33, "column": 44, - "endLine": 34, + "endLine": 33, "endColumn": 68, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 43, "column": 8, - "endLine": 44, + "endLine": 43, "endColumn": 24, "problem": "InterOpConvertImport", "suggest": "", 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 7145a50507..3f22cfc7bf 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 656, "end": 656, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_equality_judgment_js');\nlet a = GeneratedImportVar_1.getPropertyByName('a');\nlet b = GeneratedImportVar_1.getPropertyByName('b');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_equality_judgment_js');\nlet a = GeneratedImportVar_1.getProperty('a');\nlet b = GeneratedImportVar_1.getProperty('b');\n", "line": 16, "column": 1, "endLine": 16, diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets index 796cf7f898..9a2c6e2cab 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.ets @@ -14,8 +14,8 @@ */ let GeneratedImportVar_1 = ESValue.load('./interop_equality_judgment_js'); -let a = GeneratedImportVar_1.getPropertyByName('a'); -let b = GeneratedImportVar_1.getPropertyByName('b'); +let a = GeneratedImportVar_1.getProperty('a'); +let b = GeneratedImportVar_1.getProperty('b'); a.areEqual(b) !a.areEqual(b) diff --git a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json index c3d33e531c..38e88ae0b6 100644 --- a/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_equality_judgment.ets.migrate.json @@ -28,7 +28,7 @@ "line": 17, "column": 5, "endLine": 17, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", diff --git a/ets2panda/linter/test/interop/interop_export_js_rules.ets b/ets2panda/linter/test/interop/interop_export_js_rules.ets index e729a7c2c3..3ab29fe81d 100644 --- a/ets2panda/linter/test/interop/interop_export_js_rules.ets +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets @@ -19,10 +19,6 @@ 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. -export * as namespace1 from "./oh_modules/ets_decorator" - export * as namespace2 from "./interop_import_js_rules_js" 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 index 1f92c538cd..827762e0bf 100644 --- a/ets2panda/linter/test/interop/interop_export_js_rules.ets.arkts2.json +++ b/ets2panda/linter/test/interop/interop_export_js_rules.ets.arkts2.json @@ -1,88 +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": 1, - "endLine": 16, - "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": 13, - "problem": "InteropJsObjectExport", - "suggest": "", - "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", - "severity": "ERROR" - }, - { - "line": 20, - "column": 1, - "endLine": 20, - "endColumn": 51, - "problem": "InteropJsObjectExport", - "suggest": "", - "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 1, - "endLine": 22, - "endColumn": 57, - "problem": "InteropArkTs1ObjectExport", - "suggest": "", - "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 57, - "problem": "InteropArkTs1ObjectExport", - "suggest": "", - "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 1, - "endLine": 26, - "endColumn": 57, - "problem": "InteropArkTs1ObjectExport", - "suggest": "", - "rule": "Direct export of interop ArkTS1.0 objects is not supported (arkts-interop-d2s-export-entity)", - "severity": "ERROR" - }, - { - "line": 28, - "column": 1, - "endLine": 28, - "endColumn": 59, - "problem": "InteropJsObjectExport", - "suggest": "", - "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", - "severity": "ERROR" - } - ] -} \ No newline at end of file + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 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": 13, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 1, + "endLine": 20, + "endColumn": 51, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-js)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 1, + "endLine": 24, + "endColumn": 59, + "problem": "InteropJsObjectExport", + "suggest": "", + "rule": "Direct export of interop JS objects is not supported (arkts-interop-js2s-export-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 bda0908dba..2a3dec941a 100755 --- a/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 958, "end": 958, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('../main/js_lib');\nlet Cjs = GeneratedImportVar_1.getPropertyByName('Cjs');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('../main/js_lib');\nlet Cjs = GeneratedImportVar_1.getProperty('Cjs');\n", "line": 16, "column": 1, "endLine": 16, @@ -63,7 +63,7 @@ { "start": 958, "end": 958, - "replacementText": "let GeneratedImportVar_2 = ESValue.load('../main/js_lib');\nlet fjs = GeneratedImportVar_2.getPropertyByName('fjs');\n", + "replacementText": "let GeneratedImportVar_2 = ESValue.load('../main/js_lib');\nlet fjs = GeneratedImportVar_2.getProperty('fjs');\n", "line": 17, "column": 1, "endLine": 17, @@ -93,7 +93,7 @@ { "start": 958, "end": 958, - "replacementText": "let GeneratedImportVar_3 = ESValue.load('./jsfiles/preview_import_js');\nlet CPreview = GeneratedImportVar_3.getPropertyByName('CPreview');\nlet bar = GeneratedImportVar_3.getPropertyByName('bar');\nlet foo = GeneratedImportVar_3.getPropertyByName('foo');\n", + "replacementText": "let GeneratedImportVar_3 = ESValue.load('./jsfiles/preview_import_js');\nlet CPreview = GeneratedImportVar_3.getProperty('CPreview');\nlet bar = GeneratedImportVar_3.getProperty('bar');\nlet foo = GeneratedImportVar_3.getProperty('foo');\n", "line": 18, "column": 1, "endLine": 18, @@ -123,7 +123,7 @@ { "start": 958, "end": 958, - "replacementText": "let GeneratedImportVar_4 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_4.getPropertyByName('aaa');\n", + "replacementText": "let GeneratedImportVar_4 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_4.getProperty('aaa');\n", "line": 19, "column": 1, "endLine": 19, @@ -153,7 +153,7 @@ { "start": 958, "end": 958, - "replacementText": "let GeneratedImportVar_5 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_5.getPropertyByName('aaa');\nlet ClassA = GeneratedImportVar_5.getPropertyByName('ClassA');\nlet Dog = GeneratedImportVar_5.getPropertyByName('Dog');\n", + "replacementText": "let GeneratedImportVar_5 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_5.getProperty('aaa');\nlet ClassA = GeneratedImportVar_5.getProperty('ClassA');\nlet Dog = GeneratedImportVar_5.getProperty('Dog');\n", "line": 20, "column": 1, "endLine": 20, @@ -213,7 +213,7 @@ { "start": 958, "end": 958, - "replacementText": "let GeneratedImportVar_7 = ESValue.load('./interop_import_js_js');\nlet Wiki = GeneratedImportVar_7.getPropertyByName('Wiki');\nlet Doge = GeneratedImportVar_7.getPropertyByName('Dog');\n", + "replacementText": "let GeneratedImportVar_7 = ESValue.load('./interop_import_js_js');\nlet Wiki = GeneratedImportVar_7.getProperty('Wiki');\nlet Doge = GeneratedImportVar_7.getProperty('Dog');\n", "line": 22, "column": 1, "endLine": 22, diff --git a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets index 80f88726e3..851b32fdc0 100644 --- a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.ets @@ -20,20 +20,20 @@ let GeneratedImportVar_7 = ESValue.load('./interop_import_js_js'); -let Wiki = GeneratedImportVar_7.getPropertyByName('Wiki'); -let Doge = GeneratedImportVar_7.getPropertyByName('Dog'); +let Wiki = GeneratedImportVar_7.getProperty('Wiki'); +let Doge = GeneratedImportVar_7.getProperty('Dog'); let GeneratedImportVar_6 = ESValue.load('./interop_import_js_js'); let GeneratedImportVar_5 = ESValue.load('./interop_import_js_js'); -let myAaa = GeneratedImportVar_5.getPropertyByName('aaa'); -let ClassA = GeneratedImportVar_5.getPropertyByName('ClassA'); -let Dog = GeneratedImportVar_5.getPropertyByName('Dog'); +let myAaa = GeneratedImportVar_5.getProperty('aaa'); +let ClassA = GeneratedImportVar_5.getProperty('ClassA'); +let Dog = GeneratedImportVar_5.getProperty('Dog'); let GeneratedImportVar_4 = ESValue.load('./interop_import_js_js'); -let myAaa = GeneratedImportVar_4.getPropertyByName('aaa'); +let myAaa = GeneratedImportVar_4.getProperty('aaa'); let GeneratedImportVar_3 = ESValue.load('./jsfiles/preview_import_js'); -let CPreview = GeneratedImportVar_3.getPropertyByName('CPreview'); -let bar = GeneratedImportVar_3.getPropertyByName('bar'); -let foo = GeneratedImportVar_3.getPropertyByName('foo'); +let CPreview = GeneratedImportVar_3.getProperty('CPreview'); +let bar = GeneratedImportVar_3.getProperty('bar'); +let foo = GeneratedImportVar_3.getProperty('foo'); let GeneratedImportVar_2 = ESValue.load('../main/js_lib'); -let fjs = GeneratedImportVar_2.getPropertyByName('fjs'); +let fjs = GeneratedImportVar_2.getProperty('fjs'); let GeneratedImportVar_1 = ESValue.load('../main/js_lib'); -let Cjs = GeneratedImportVar_1.getPropertyByName('Cjs'); +let Cjs = GeneratedImportVar_1.getProperty('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 index c422eb1668..d46fff44ee 100644 --- a/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_import_js.ets.migrate.json @@ -28,7 +28,7 @@ "line": 23, "column": 5, "endLine": 23, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 24, "column": 5, "endLine": 24, - "endColumn": 57, + "endColumn": 51, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 27, "column": 5, "endLine": 27, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -78,7 +78,7 @@ "line": 28, "column": 5, "endLine": 28, - "endColumn": 62, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -88,7 +88,7 @@ "line": 29, "column": 5, "endLine": 29, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -108,7 +108,7 @@ "line": 31, "column": 5, "endLine": 31, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -128,7 +128,7 @@ "line": 33, "column": 5, "endLine": 33, - "endColumn": 66, + "endColumn": 60, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -138,7 +138,7 @@ "line": 34, "column": 5, "endLine": 34, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -148,7 +148,7 @@ "line": 35, "column": 5, "endLine": 35, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -168,7 +168,7 @@ "line": 37, "column": 5, "endLine": 37, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -188,7 +188,7 @@ "line": 39, "column": 5, "endLine": 39, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.autofix.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.autofix.json index 2b90e5d9f0..baf465561b 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 663, "end": 663, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_compare_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet m = GeneratedImportVar_1.getPropertyByName('m');\nlet n = GeneratedImportVar_1.getPropertyByName('n');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_compare_js');\nlet foo = GeneratedImportVar_1.getProperty('foo');\nlet m = GeneratedImportVar_1.getProperty('m');\nlet n = GeneratedImportVar_1.getProperty('n');\n", "line": 17, "column": 1, "endLine": 17, @@ -54,7 +54,7 @@ { "start": 672, "end": 677, - "replacementText": "foo.getPropertyByName(\"a\")", + "replacementText": "foo.getProperty(\"a\")", "line": 18, "column": 9, "endLine": 18, @@ -75,7 +75,7 @@ { "start": 686, "end": 691, - "replacementText": "foo.getPropertyByName(\"b\")", + "replacementText": "foo.getProperty(\"b\")", "line": 19, "column": 9, "endLine": 19, @@ -96,7 +96,7 @@ { "start": 672, "end": 677, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 20, "column": 1, "endLine": 20, @@ -117,7 +117,7 @@ { "start": 686, "end": 691, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 20, "column": 5, "endLine": 20, @@ -138,7 +138,7 @@ { "start": 672, "end": 677, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 21, "column": 1, "endLine": 21, @@ -159,7 +159,7 @@ { "start": 686, "end": 691, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 21, "column": 5, "endLine": 21, @@ -180,7 +180,7 @@ { "start": 672, "end": 677, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 22, "column": 1, "endLine": 22, @@ -201,7 +201,7 @@ { "start": 686, "end": 691, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 22, "column": 6, "endLine": 22, @@ -222,7 +222,7 @@ { "start": 672, "end": 677, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 23, "column": 1, "endLine": 23, @@ -243,7 +243,7 @@ { "start": 686, "end": 691, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 23, "column": 6, "endLine": 23, @@ -546,7 +546,7 @@ { "start": 881, "end": 886, - "replacementText": "foo.getPropertyByName(\"a\").toNumber()", + "replacementText": "foo.getProperty(\"a\").toNumber()", "line": 43, "column": 1, "endLine": 43, @@ -567,7 +567,7 @@ { "start": 889, "end": 894, - "replacementText": "foo.getPropertyByName(\"b\").toNumber()", + "replacementText": "foo.getProperty(\"b\").toNumber()", "line": 43, "column": 9, "endLine": 43, @@ -588,7 +588,7 @@ { "start": 881, "end": 886, - "replacementText": "foo.getPropertyByName(\"a\")", + "replacementText": "foo.getProperty(\"a\")", "line": 43, "column": 1, "endLine": 43, @@ -609,7 +609,7 @@ { "start": 889, "end": 894, - "replacementText": "foo.getPropertyByName(\"b\")", + "replacementText": "foo.getProperty(\"b\")", "line": 43, "column": 9, "endLine": 43, diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.ets b/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.ets index 76633c942c..3e99265ba8 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.ets @@ -15,12 +15,12 @@ let GeneratedImportVar_1 = ESValue.load('./interop_import_js_compare_js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); -let m = GeneratedImportVar_1.getPropertyByName('m'); -let n = GeneratedImportVar_1.getPropertyByName('n'); +let foo = GeneratedImportVar_1.getProperty('foo'); +let m = GeneratedImportVar_1.getProperty('m'); +let n = GeneratedImportVar_1.getProperty('n'); -let a = foo.getPropertyByName("a") -let b = foo.getPropertyByName("b") +let a = foo.getProperty("a") +let b = foo.getProperty("b") a > b a < b a >= b @@ -48,4 +48,4 @@ x2 < y2; x2 >= y2; x2 <= y2; -foo.getPropertyByName("a").toNumber() > foo.getPropertyByName("b").toNumber(); \ No newline at end of file +foo.getProperty("a").toNumber() > foo.getProperty("b").toNumber(); \ No newline at end of file diff --git a/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.json b/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.json index 0ccdec1005..680e681f88 100644 --- a/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_import_js_compare.ets.migrate.json @@ -28,7 +28,7 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 19, "column": 5, "endLine": 19, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +48,7 @@ "line": 20, "column": 5, "endLine": 20, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +58,7 @@ "line": 22, "column": 5, "endLine": 22, - "endColumn": 35, + "endColumn": 29, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 23, "column": 5, "endLine": 23, - "endColumn": 35, + "endColumn": 29, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", 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 c9d2b8aee7..7e7407ab2d 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 @@ -33,7 +33,7 @@ { "start": 703, "end": 703, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_rules_js');\nlet ff3 = GeneratedImportVar_1.getPropertyByName('ff3');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_rules_js');\nlet ff3 = GeneratedImportVar_1.getProperty('ff3');\n", "line": 15, "column": 1, "endLine": 15, @@ -63,7 +63,7 @@ { "start": 703, "end": 703, - "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_index_js');\nlet foo = GeneratedImportVar_2.getPropertyByName('foo');\n", + "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_index_js');\nlet foo = GeneratedImportVar_2.getProperty('foo');\n", "line": 16, "column": 1, "endLine": 16, @@ -84,7 +84,7 @@ { "start": 714, "end": 721, - "replacementText": "foo.getPropertyByName(\"arr\")", + "replacementText": "foo.getProperty(\"arr\")", "line": 17, "column": 11, "endLine": 17, @@ -115,7 +115,7 @@ { "start": 722, "end": 728, - "replacementText": "arr.getPropertyByIndex(1)", + "replacementText": "arr.getProperty(1)", "line": 18, "column": 1, "endLine": 18, @@ -146,7 +146,7 @@ { "start": 729, "end": 739, - "replacementText": "arr.setPropertyByIndex(3, ESValue.wrap(4))", + "replacementText": "arr.setProperty(3, ESValue.wrap(4))", "line": 19, "column": 1, "endLine": 19, @@ -188,7 +188,7 @@ { "start": 752, "end": 759, - "replacementText": "ff3.getPropertyByName(\"arr\")", + "replacementText": "ff3.getProperty(\"arr\")", "line": 21, "column": 12, "endLine": 21, @@ -209,7 +209,7 @@ { "start": 770, "end": 781, - "replacementText": "arr1.getPropertyByName(\"length\")", + "replacementText": "arr1.getProperty(\"length\")", "line": 22, "column": 11, "endLine": 22, @@ -272,7 +272,7 @@ { "start": 812, "end": 823, - "replacementText": "arr1.getPropertyByName(\"length\")", + "replacementText": "arr1.getProperty(\"length\")", "line": 23, "column": 21, "endLine": 23, @@ -291,7 +291,7 @@ "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { - "replacementText": "arr1.getPropertyByIndex(i).toNumber()", + "replacementText": "arr1.getProperty(i).toNumber()", "start": 848, "end": 855, "line": 24, @@ -314,7 +314,7 @@ { "start": 848, "end": 855, - "replacementText": "arr1.getPropertyByIndex(i)", + "replacementText": "arr1.getProperty(i)", "line": 24, "column": 17, "endLine": 24, @@ -333,7 +333,7 @@ "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { - "replacementText": "arr1.getPropertyByIndex(i).toNumber()", + "replacementText": "arr1.getProperty(i).toNumber()", "start": 882, "end": 889, "line": 25, @@ -356,7 +356,7 @@ { "start": 882, "end": 889, - "replacementText": "arr1.getPropertyByIndex(i)", + "replacementText": "arr1.getProperty(i)", "line": 25, "column": 13, "endLine": 25, @@ -375,7 +375,7 @@ "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { - "replacementText": "arr1.setPropertyByIndex(i, ESValue.wrap(0 //error\n))", + "replacementText": "arr1.setProperty(i, ESValue.wrap(0 //error\n))", "start": 903, "end": 914, "line": 26, @@ -398,7 +398,7 @@ { "start": 903, "end": 914, - "replacementText": "arr1.setPropertyByIndex(i, ESValue.wrap(0))", + "replacementText": "arr1.setProperty(i, ESValue.wrap(0))", "line": 26, "column": 5, "endLine": 26, @@ -438,7 +438,7 @@ "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { - "replacementText": "arr1.getPropertyByIndex(i).toNumber()", + "replacementText": "arr1.getProperty(i).toNumber()", "start": 940, "end": 947, "line": 27, @@ -461,7 +461,7 @@ { "start": 940, "end": 947, - "replacementText": "arr1.getPropertyByIndex(i)", + "replacementText": "arr1.getProperty(i)", "line": 27, "column": 17, "endLine": 27, 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 index 8e707c2f67..d26adb726f 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.ets @@ -14,22 +14,22 @@ */ let GeneratedImportVar_2 = ESValue.load('./interop_import_js_index_js'); -let foo = GeneratedImportVar_2.getPropertyByName('foo'); +let foo = GeneratedImportVar_2.getProperty('foo'); let GeneratedImportVar_1 = ESValue.load('./interop_import_js_rules_js'); -let ff3 = GeneratedImportVar_1.getPropertyByName('ff3'); +let ff3 = GeneratedImportVar_1.getProperty('ff3'); -let arr = foo.getPropertyByName("arr") -arr.getPropertyByIndex(1.0) -arr.setPropertyByIndex(3.0, ESValue.wrap(4.0)) +let arr = foo.getProperty("arr") +arr.getProperty(1.0) +arr.setProperty(3.0, ESValue.wrap(4.0)) -let arr1 = ff3.getPropertyByName("arr") -let len: number = arr1.getPropertyByName("length") as number -for (let i: number = 0.0; i < arr1.getPropertyByName("length"); ++i) { - console.log(arr1.getPropertyByIndex(i).toNumber()+''); //error - let x = arr1.getPropertyByIndex(i).toNumber() //error - arr1.setPropertyByIndex(i, ESValue.wrap(0.0 //error +let arr1 = ff3.getProperty("arr") +let len: number = arr1.getProperty("length") as number +for (let i: number = 0.0; i < arr1.getProperty("length"); ++i) { + console.log(arr1.getProperty(i).toNumber()+''); //error + let x = arr1.getProperty(i).toNumber() //error + arr1.setProperty(i, ESValue.wrap(0.0 //error )) //error - console.log(arr1.getPropertyByIndex(i).toNumber()+''); //error + console.log(arr1.getProperty(i).toNumber()+''); //error } for (let element of arr1) { //error 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 index 526bcedf9d..f816c83809 100644 --- a/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_import_js_index.ets.migrate.json @@ -28,7 +28,7 @@ "line": 17, "column": 5, "endLine": 17, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +48,7 @@ "line": 19, "column": 5, "endLine": 19, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +58,7 @@ "line": 21, "column": 5, "endLine": 21, - "endColumn": 39, + "endColumn": 33, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 25, "column": 5, "endLine": 25, - "endColumn": 40, + "endColumn": 34, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -78,7 +78,7 @@ "line": 29, "column": 9, "endLine": 29, - "endColumn": 50, + "endColumn": 43, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", 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 b44bc6c370..58320d2ba5 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 @@ -43,7 +43,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_rules_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_rules_js');\nlet foo = GeneratedImportVar_1.getProperty('foo');\n", "line": 17, "column": 1, "endLine": 17, @@ -83,7 +83,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_rules_js');\nlet ff1 = GeneratedImportVar_2.getPropertyByName('ff1');\nlet ff2 = GeneratedImportVar_2.getPropertyByName('ff2');\n", + "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_rules_js');\nlet ff1 = GeneratedImportVar_2.getProperty('ff1');\nlet ff2 = GeneratedImportVar_2.getProperty('ff2');\n", "line": 18, "column": 1, "endLine": 18, @@ -123,7 +123,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_3 = ESValue.load('./interop_import_js_rules_js');\nlet A = GeneratedImportVar_3.getPropertyByName('A');\n", + "replacementText": "let GeneratedImportVar_3 = ESValue.load('./interop_import_js_rules_js');\nlet A = GeneratedImportVar_3.getProperty('A');\n", "line": 20, "column": 1, "endLine": 20, @@ -163,7 +163,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_4 = ESValue.load('./interop_import_js_rules_js');\nlet C = GeneratedImportVar_4.getPropertyByName('C');\n", + "replacementText": "let GeneratedImportVar_4 = ESValue.load('./interop_import_js_rules_js');\nlet C = GeneratedImportVar_4.getProperty('C');\n", "line": 21, "column": 1, "endLine": 21, @@ -203,7 +203,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_5 = ESValue.load('./interop_import_js_rules_js');\nlet ff3 = GeneratedImportVar_5.getPropertyByName('ff3');\n", + "replacementText": "let GeneratedImportVar_5 = ESValue.load('./interop_import_js_rules_js');\nlet ff3 = GeneratedImportVar_5.getProperty('ff3');\n", "line": 23, "column": 1, "endLine": 23, @@ -243,7 +243,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_6 = ESValue.load('./interop_import_js_rules_js');\nlet ff4 = GeneratedImportVar_6.getPropertyByName('ff4');\n", + "replacementText": "let GeneratedImportVar_6 = ESValue.load('./interop_import_js_rules_js');\nlet ff4 = GeneratedImportVar_6.getProperty('ff4');\n", "line": 25, "column": 1, "endLine": 25, @@ -283,7 +283,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_7 = ESValue.load('./interop_import_js_rules_js');\nlet handle = GeneratedImportVar_7.getPropertyByName('handle');\n", + "replacementText": "let GeneratedImportVar_7 = ESValue.load('./interop_import_js_rules_js');\nlet handle = GeneratedImportVar_7.getProperty('handle');\n", "line": 27, "column": 1, "endLine": 27, @@ -323,7 +323,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_8 = ESValue.load('./interop_import_js_rules_js');\nlet expand = GeneratedImportVar_8.getPropertyByName('expand');\n", + "replacementText": "let GeneratedImportVar_8 = ESValue.load('./interop_import_js_rules_js');\nlet expand = GeneratedImportVar_8.getProperty('expand');\n", "line": 29, "column": 1, "endLine": 29, @@ -363,7 +363,7 @@ { "start": 1092, "end": 1092, - "replacementText": "let GeneratedImportVar_9 = ESValue.load('./interop_import_js_rules_js');\nlet orange = GeneratedImportVar_9.getPropertyByName('orange');\n", + "replacementText": "let GeneratedImportVar_9 = ESValue.load('./interop_import_js_rules_js');\nlet orange = GeneratedImportVar_9.getProperty('orange');\n", "line": 30, "column": 1, "endLine": 30, @@ -384,7 +384,7 @@ { "start": 1098, "end": 1108, - "replacementText": "foo.getPropertyByName(\"isGood\")", + "replacementText": "foo.getProperty(\"isGood\")", "line": 32, "column": 5, "endLine": 32, @@ -403,7 +403,7 @@ "problem": "InteropJsObjectConditionJudgment", "autofix": [ { - "replacementText": "foo.getPropertyByName('isGood').toBoolean()", + "replacementText": "foo.getProperty('isGood').toBoolean()", "start": 1098, "end": 1108, "line": 32, @@ -426,7 +426,7 @@ { "start": 1118, "end": 1124, - "replacementText": "ff1.getPropertyByName(\"f1\").toNumber()", + "replacementText": "ff1.getProperty(\"f1\").toNumber()", "line": 34, "column": 5, "endLine": 34, @@ -447,7 +447,7 @@ { "start": 1118, "end": 1124, - "replacementText": "ff1.getPropertyByName(\"f1\")", + "replacementText": "ff1.getProperty(\"f1\")", "line": 34, "column": 5, "endLine": 34, @@ -466,7 +466,7 @@ "problem": "InteropJsObjectConditionJudgment", "autofix": [ { - "replacementText": "ff1.getPropertyByName('f1').toNumber()", + "replacementText": "ff1.getProperty('f1').toNumber()", "start": 1118, "end": 1124, "line": 34, @@ -561,7 +561,7 @@ { "start": 1344, "end": 1351, - "replacementText": "ff3.getPropertyByName(\"arr\")", + "replacementText": "ff3.getProperty(\"arr\")", "line": 50, "column": 11, "endLine": 50, @@ -582,7 +582,7 @@ { "start": 1362, "end": 1372, - "replacementText": "arr.getPropertyByName(\"length\")", + "replacementText": "arr.getProperty(\"length\")", "line": 51, "column": 11, "endLine": 51, @@ -653,7 +653,7 @@ "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { - "replacementText": "arr.getPropertyByIndex(i).toNumber()", + "replacementText": "arr.getProperty(i).toNumber()", "start": 1425, "end": 1431, "line": 53, @@ -676,7 +676,7 @@ { "start": 1425, "end": 1431, - "replacementText": "arr.getPropertyByIndex(i)", + "replacementText": "arr.getProperty(i)", "line": 53, "column": 11, "endLine": 53, @@ -705,7 +705,7 @@ "problem": "InteropJsObjectTraverseJsInstance", "autofix": [ { - "replacementText": "arr.setPropertyByIndex(i, ESValue.wrap(0))", + "replacementText": "arr.setProperty(i, ESValue.wrap(0))", "start": 1434, "end": 1444, "line": 54, @@ -728,7 +728,7 @@ { "start": 1434, "end": 1444, - "replacementText": "arr.setPropertyByIndex(i, ESValue.wrap(0))", + "replacementText": "arr.setProperty(i, ESValue.wrap(0))", "line": 54, "column": 3, "endLine": 54, @@ -1072,7 +1072,7 @@ { "start": 1831, "end": 1850, - "replacementText": "orange.getPropertyByName(\"isVegetable1\")", + "replacementText": "orange.getProperty(\"isVegetable1\")", "line": 84, "column": 5, "endLine": 84, 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 a080a8877d..9481ffc18a 100644 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 783, "end": 783, - "replacementText": "let GeneratedImportVar_1 = ESValue.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", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_import_js_js');\nlet myAaa = GeneratedImportVar_1.getProperty('aaa');\nlet ClassA = GeneratedImportVar_1.getProperty('ClassA');\nlet Dog = GeneratedImportVar_1.getProperty('Dog');\nlet Person = GeneratedImportVar_1.getProperty('Person');\nlet Wiki = GeneratedImportVar_1.getProperty('Wiki');\n", "line": 16, "column": 1, "endLine": 16, @@ -63,7 +63,7 @@ { "start": 783, "end": 783, - "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_js');\nlet Doge = GeneratedImportVar_2.getPropertyByName('Dog');\n", + "replacementText": "let GeneratedImportVar_2 = ESValue.load('./interop_import_js_js');\nlet Doge = GeneratedImportVar_2.getProperty('Dog');\n", "line": 17, "column": 1, "endLine": 17, @@ -93,7 +93,7 @@ { "start": 783, "end": 783, - "replacementText": "let GeneratedImportVar_3 = ESValue.load('./interop_import_js_js');\nlet wiki = GeneratedImportVar_3.getPropertyByName('Wiki');\n", + "replacementText": "let GeneratedImportVar_3 = ESValue.load('./interop_import_js_js');\nlet wiki = GeneratedImportVar_3.getProperty('Wiki');\n", "line": 18, "column": 1, "endLine": 18, @@ -260,7 +260,7 @@ { "start": 937, "end": 953, - "replacementText": "Wiki.getPropertyByName('name').typeOf()", + "replacementText": "Wiki.getProperty('name').typeOf()", "line": 27, "column": 1, "endLine": 27, @@ -281,7 +281,7 @@ { "start": 944, "end": 953, - "replacementText": "Wiki.getPropertyByName(\"name\")", + "replacementText": "Wiki.getProperty(\"name\")", "line": 27, "column": 8, "endLine": 27, @@ -323,7 +323,7 @@ { "start": 992, "end": 1001, - "replacementText": "wiki.getPropertyByName(\"name\")", + "replacementText": "wiki.getProperty(\"name\")", "line": 29, "column": 11, "endLine": 29, @@ -428,7 +428,7 @@ { "start": 1136, "end": 1147, - "replacementText": "person.getPropertyByName(\"name\")", + "replacementText": "person.getProperty(\"name\")", "line": 35, "column": 11, "endLine": 35, @@ -584,7 +584,7 @@ { "start": 1701, "end": 1717, - "replacementText": "wiki.getPropertyByName('name').typeOf()", + "replacementText": "wiki.getProperty('name').typeOf()", "line": 61, "column": 5, "endLine": 61, @@ -605,7 +605,7 @@ { "start": 1708, "end": 1717, - "replacementText": "wiki.getPropertyByName(\"name\")", + "replacementText": "wiki.getProperty(\"name\")", "line": 61, "column": 12, "endLine": 61, @@ -689,7 +689,7 @@ { "start": 1868, "end": 1892, - "replacementText": "Person.instantiate().getPropertyByName('name').typeOf()", + "replacementText": "Person.instantiate().getProperty('name').typeOf()", "line": 70, "column": 1, "endLine": 70, @@ -710,7 +710,7 @@ { "start": 1875, "end": 1892, - "replacementText": "new Person().getPropertyByName(\"name\")", + "replacementText": "new Person().getProperty(\"name\")", "line": 70, "column": 8, "endLine": 70, 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 index 197a8577ce..ec79bd0e7e 100644 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.ets +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.ets @@ -16,15 +16,15 @@ let GeneratedImportVar_3 = ESValue.load('./interop_import_js_js'); -let wiki = GeneratedImportVar_3.getPropertyByName('Wiki'); +let wiki = GeneratedImportVar_3.getProperty('Wiki'); let GeneratedImportVar_2 = ESValue.load('./interop_import_js_js'); -let Doge = GeneratedImportVar_2.getPropertyByName('Dog'); +let Doge = GeneratedImportVar_2.getProperty('Dog'); let GeneratedImportVar_1 = ESValue.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'); +let myAaa = GeneratedImportVar_1.getProperty('aaa'); +let ClassA = GeneratedImportVar_1.getProperty('ClassA'); +let Dog = GeneratedImportVar_1.getProperty('Dog'); +let Person = GeneratedImportVar_1.getProperty('Person'); +let Wiki = GeneratedImportVar_1.getProperty('Wiki'); myAaa.invoke().typeOf(); //error @@ -34,15 +34,15 @@ Dog.typeOf(); //error Dog.invoke(ESValue.wrap('doge')).typeOf(); //error Doge.invoke(ESValue.wrap('doge')).typeOf(); //error Wiki.typeOf() //error -Wiki.getPropertyByName('name').typeOf() //error +Wiki.getProperty('name').typeOf() //error wiki.typeOf() //error -let val = wiki.getPropertyByName("name") +let val = wiki.getProperty("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 name =person.getProperty("name") let name2 =person.invokeMethod("getName") function getPersonInfo(){ typeof person; @@ -68,7 +68,7 @@ class Object { typeof location; } tips(){ - wiki.getPropertyByName('name').typeOf(); //error + wiki.getProperty('name').typeOf(); //error typeof age; typeof person2; typeof fun; @@ -77,6 +77,6 @@ class Object { } myAaa.typeOf(); //error -Person.instantiate().getPropertyByName('name').typeOf() //error +Person.instantiate().getProperty('name').typeOf() //error Person.instantiate().invokeMethod("getName").typeOf() //error Person.instantiate().invokeMethod("setAge", ESValue.wrap(22.0)).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 index f709470eef..af67e13229 100644 --- a/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.json +++ b/ets2panda/linter/test/interop/interop_import_typeof_js.ets.migrate.json @@ -28,7 +28,7 @@ "line": 19, "column": 5, "endLine": 19, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +48,7 @@ "line": 21, "column": 5, "endLine": 21, - "endColumn": 57, + "endColumn": 51, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 23, "column": 5, "endLine": 23, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -78,7 +78,7 @@ "line": 24, "column": 5, "endLine": 24, - "endColumn": 62, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -88,7 +88,7 @@ "line": 25, "column": 5, "endLine": 25, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -98,7 +98,7 @@ "line": 26, "column": 5, "endLine": 26, - "endColumn": 62, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -108,7 +108,7 @@ "line": 27, "column": 5, "endLine": 27, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -128,7 +128,7 @@ "line": 39, "column": 5, "endLine": 39, - "endColumn": 41, + "endColumn": 35, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -138,7 +138,7 @@ "line": 45, "column": 5, "endLine": 45, - "endColumn": 43, + "endColumn": 37, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", 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 d66995a3c6..f2e4507626 100644 --- 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 @@ -43,7 +43,7 @@ { "start": 723, "end": 723, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_not_have_property_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet person = GeneratedImportVar_1.getPropertyByName('person');\nlet TestHelper = GeneratedImportVar_1.getPropertyByName('TestHelper');\nlet Machine = GeneratedImportVar_1.getPropertyByName('Machine');\nlet User = GeneratedImportVar_1.getPropertyByName('User');\nlet Person = GeneratedImportVar_1.getPropertyByName('Person');\nlet Employee = GeneratedImportVar_1.getPropertyByName('Employee');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_not_have_property_js');\nlet foo = GeneratedImportVar_1.getProperty('foo');\nlet person = GeneratedImportVar_1.getProperty('person');\nlet TestHelper = GeneratedImportVar_1.getProperty('TestHelper');\nlet Machine = GeneratedImportVar_1.getProperty('Machine');\nlet User = GeneratedImportVar_1.getProperty('User');\nlet Person = GeneratedImportVar_1.getProperty('Person');\nlet Employee = GeneratedImportVar_1.getProperty('Employee');\n", "line": 17, "column": 1, "endLine": 17, @@ -64,7 +64,7 @@ { "start": 725, "end": 733, - "replacementText": "foo.getPropertyByName(\"name\")", + "replacementText": "foo.getProperty(\"name\")", "line": 19, "column": 1, "endLine": 19, @@ -85,7 +85,7 @@ { "start": 734, "end": 750, - "replacementText": "foo.setPropertyByName(\"name\", ESValue.wrap(\"456\"))", + "replacementText": "foo.setProperty(\"name\", ESValue.wrap(\"456\"))", "line": 20, "column": 1, "endLine": 20, @@ -106,7 +106,7 @@ { "start": 751, "end": 766, - "replacementText": "person.setPropertyByName(\"age\", ESValue.wrap(23))", + "replacementText": "person.setProperty(\"age\", ESValue.wrap(23))", "line": 21, "column": 1, "endLine": 21, @@ -148,7 +148,7 @@ { "start": 767, "end": 787, - "replacementText": "person.setPropertyByName(\"male\", ESValue.wrap([2, 3]))", + "replacementText": "person.setProperty(\"male\", ESValue.wrap([2, 3]))", "line": 22, "column": 1, "endLine": 22, @@ -211,7 +211,7 @@ { "start": 788, "end": 800, - "replacementText": "foo.setPropertyByName(\"age\", ESValue.wrap(12))", + "replacementText": "foo.setProperty(\"age\", ESValue.wrap(12))", "line": 23, "column": 1, "endLine": 23, @@ -253,7 +253,7 @@ { "start": 805, "end": 821, - "replacementText": "foo.setPropertyByName(\"name\", ESValue.wrap(\"456\"))", + "replacementText": "foo.setProperty(\"name\", ESValue.wrap(\"456\"))", "line": 24, "column": 5, "endLine": 24, @@ -272,7 +272,7 @@ "problem": "InteropJsObjectConditionJudgment", "autofix": [ { - "replacementText": "foo.getPropertyByName('name').toString()", + "replacementText": "foo.getProperty('name').toString()", "start": 805, "end": 813, "line": 24, @@ -326,7 +326,7 @@ { "start": 860, "end": 870, - "replacementText": "a.setPropertyByName(\"age\", ESValue.wrap(12))", + "replacementText": "a.setProperty(\"age\", ESValue.wrap(12))", "line": 27, "column": 1, "endLine": 27, @@ -452,7 +452,7 @@ { "start": 1005, "end": 1017, - "replacementText": "machine.getPropertyByName(\"name\")", + "replacementText": "machine.getProperty(\"name\")", "line": 32, "column": 12, "endLine": 32, @@ -536,7 +536,7 @@ { "start": 1173, "end": 1180, - "replacementText": "user.getPropertyByName(\"id\")", + "replacementText": "user.getProperty(\"id\")", "line": 37, "column": 12, "endLine": 37, @@ -641,7 +641,7 @@ { "start": 1312, "end": 1319, - "replacementText": "user.getPropertyByName(\"id\")", + "replacementText": "user.getProperty(\"id\")", "line": 42, "column": 8, "endLine": 42, @@ -746,7 +746,7 @@ { "start": 1454, "end": 1461, - "replacementText": "user.getPropertyByName(\"id\")", + "replacementText": "user.getProperty(\"id\")", "line": 47, "column": 12, "endLine": 47, @@ -830,7 +830,7 @@ { "start": 1601, "end": 1608, - "replacementText": "user.getPropertyByName(\"id\")", + "replacementText": "user.getProperty(\"id\")", "line": 52, "column": 12, "endLine": 52, @@ -935,7 +935,7 @@ { "start": 1758, "end": 1770, - "replacementText": "machine.getPropertyByName(\"name\")", + "replacementText": "machine.getProperty(\"name\")", "line": 57, "column": 12, "endLine": 57, @@ -1019,7 +1019,7 @@ { "start": 1929, "end": 1942, - "replacementText": "employee.getPropertyByName(\"name\")", + "replacementText": "employee.getProperty(\"name\")", "line": 62, "column": 12, "endLine": 62, 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 index b5185b29e4..ff4cf81936 100644 --- 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 @@ -15,24 +15,24 @@ 'use static' let GeneratedImportVar_1 = ESValue.load('./interop_not_have_property_js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); -let person = GeneratedImportVar_1.getPropertyByName('person'); -let TestHelper = GeneratedImportVar_1.getPropertyByName('TestHelper'); -let Machine = GeneratedImportVar_1.getPropertyByName('Machine'); -let User = GeneratedImportVar_1.getPropertyByName('User'); -let Person = GeneratedImportVar_1.getPropertyByName('Person'); -let Employee = GeneratedImportVar_1.getPropertyByName('Employee'); +let foo = GeneratedImportVar_1.getProperty('foo'); +let person = GeneratedImportVar_1.getProperty('person'); +let TestHelper = GeneratedImportVar_1.getProperty('TestHelper'); +let Machine = GeneratedImportVar_1.getProperty('Machine'); +let User = GeneratedImportVar_1.getProperty('User'); +let Person = GeneratedImportVar_1.getProperty('Person'); +let Employee = GeneratedImportVar_1.getProperty('Employee'); -foo.getPropertyByName("name") -foo.setPropertyByName("name", ESValue.wrap("456")) -person.setPropertyByName("age", ESValue.wrap(23.0)) -person.setPropertyByName("male", ESValue.wrap([2.0, 3.0])) -foo.setPropertyByName("age", ESValue.wrap(12.0)) -if (foo.setPropertyByName("name", ESValue.wrap("456"))) { print("true") } +foo.getProperty("name") +foo.setProperty("name", ESValue.wrap("456")) +person.setProperty("age", ESValue.wrap(23.0)) +person.setProperty("male", ESValue.wrap([2.0, 3.0])) +foo.setProperty("age", ESValue.wrap(12.0)) +if (foo.setProperty("name", ESValue.wrap("456"))) { print("true") } let a = foo.instantiate() -a.setPropertyByName("age", ESValue.wrap(12.0)) +a.setProperty("age", ESValue.wrap(12.0)) let test_helper = TestHelper.instantiate(ESValue.wrap("TEST_INSTANTIATE_JS_OBJECT")); test_helper.invokeMethod("test", ESValue.wrap(() => { 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 index 540b5557d4..258a8601a0 100644 --- 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 @@ -28,7 +28,7 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 19, "column": 5, "endLine": 19, - "endColumn": 62, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +48,7 @@ "line": 20, "column": 5, "endLine": 20, - "endColumn": 70, + "endColumn": 64, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +58,7 @@ "line": 21, "column": 5, "endLine": 21, - "endColumn": 64, + "endColumn": 58, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 22, "column": 5, "endLine": 22, - "endColumn": 58, + "endColumn": 52, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -78,7 +78,7 @@ "line": 23, "column": 5, "endLine": 23, - "endColumn": 62, + "endColumn": 56, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -88,7 +88,7 @@ "line": 24, "column": 5, "endLine": 24, - "endColumn": 66, + "endColumn": 60, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", 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 c638dec23e..402aa07005 100644 --- 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 @@ -33,7 +33,7 @@ { "start": 650, "end": 650, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_property_num_js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./interop_property_num_js');\nlet foo = GeneratedImportVar_1.getProperty('foo');\n", "line": 16, "column": 1, "endLine": 16, @@ -54,7 +54,7 @@ { "start": 653, "end": 660, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "replacementText": "foo.getProperty(\"num\").toNumber()", "line": 18, "column": 1, "endLine": 18, @@ -75,7 +75,7 @@ { "start": 653, "end": 660, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 18, "column": 2, "endLine": 18, @@ -96,7 +96,7 @@ { "start": 663, "end": 670, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "replacementText": "foo.getProperty(\"num\").toNumber()", "line": 19, "column": 1, "endLine": 19, @@ -117,7 +117,7 @@ { "start": 663, "end": 670, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 19, "column": 2, "endLine": 19, @@ -138,7 +138,7 @@ { "start": 673, "end": 680, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "replacementText": "foo.getProperty(\"num\").toNumber()", "line": 20, "column": 1, "endLine": 20, @@ -159,7 +159,7 @@ { "start": 673, "end": 680, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 20, "column": 2, "endLine": 20, @@ -180,7 +180,7 @@ { "start": 683, "end": 690, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "replacementText": "foo.getProperty(\"num\").toNumber()", "line": 21, "column": 1, "endLine": 21, @@ -201,7 +201,7 @@ { "start": 683, "end": 690, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 21, "column": 2, "endLine": 21, @@ -222,7 +222,7 @@ { "start": 693, "end": 702, - "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", + "replacementText": "(foo.getProperty(\"num\").toNumber())", "line": 22, "column": 1, "endLine": 22, @@ -243,7 +243,7 @@ { "start": 694, "end": 701, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 22, "column": 3, "endLine": 22, @@ -264,7 +264,7 @@ { "start": 705, "end": 714, - "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", + "replacementText": "(foo.getProperty(\"num\").toNumber())", "line": 23, "column": 1, "endLine": 23, @@ -285,7 +285,7 @@ { "start": 706, "end": 713, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 23, "column": 3, "endLine": 23, @@ -306,7 +306,7 @@ { "start": 717, "end": 726, - "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", + "replacementText": "(foo.getProperty(\"num\").toNumber())", "line": 24, "column": 1, "endLine": 24, @@ -327,7 +327,7 @@ { "start": 718, "end": 725, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 24, "column": 3, "endLine": 24, @@ -348,7 +348,7 @@ { "start": 729, "end": 738, - "replacementText": "(foo.getPropertyByName(\"num\").toNumber())", + "replacementText": "(foo.getProperty(\"num\").toNumber())", "line": 25, "column": 1, "endLine": 25, @@ -369,7 +369,7 @@ { "start": 730, "end": 737, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 25, "column": 3, "endLine": 25, 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 index 09086d9892..97d25fc238 100644 --- 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 @@ -14,14 +14,14 @@ */ let GeneratedImportVar_1 = ESValue.load('./interop_property_num_js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let foo = GeneratedImportVar_1.getProperty('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 ++foo.getProperty("num").toNumber(); +-foo.getProperty("num").toNumber(); +!foo.getProperty("num").toNumber(); +~foo.getProperty("num").toNumber(); ++(foo.getProperty("num").toNumber()); +-(foo.getProperty("num").toNumber()); +!(foo.getProperty("num").toNumber()); +~(foo.getProperty("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 index ef4a1a04e1..9ada1a9ba2 100644 --- 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 @@ -28,7 +28,7 @@ "line": 17, "column": 5, "endLine": 17, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 20, "column": 1, "endLine": 20, - "endColumn": 41, + "endColumn": 35, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", @@ -48,7 +48,7 @@ "line": 21, "column": 1, "endLine": 21, - "endColumn": 41, + "endColumn": 35, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", @@ -58,7 +58,7 @@ "line": 23, "column": 1, "endLine": 23, - "endColumn": 41, + "endColumn": 35, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", @@ -68,7 +68,7 @@ "line": 24, "column": 1, "endLine": 24, - "endColumn": 43, + "endColumn": 37, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", @@ -78,7 +78,7 @@ "line": 25, "column": 1, "endLine": 25, - "endColumn": 43, + "endColumn": 37, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", @@ -88,7 +88,7 @@ "line": 27, "column": 1, "endLine": 27, - "endColumn": 43, + "endColumn": 37, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", diff --git a/ets2panda/linter/test/interop/no_await_js_promise.ets.autofix.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.autofix.json index 5254337c77..3803d40f1a 100644 --- a/ets2panda/linter/test/interop/no_await_js_promise.ets.autofix.json +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 693, "end": 693, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./no_await_js_promise_export');\nlet p = GeneratedImportVar_1.getPropertyByName('p');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet pFuncCall = GeneratedImportVar_1.getPropertyByName('pFuncCall');\nlet arrowFunc = GeneratedImportVar_1.getPropertyByName('arrowFunc');\nlet pArrowCall = GeneratedImportVar_1.getPropertyByName('pArrowCall');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./no_await_js_promise_export');\nlet p = GeneratedImportVar_1.getProperty('p');\nlet foo = GeneratedImportVar_1.getProperty('foo');\nlet pFuncCall = GeneratedImportVar_1.getProperty('pFuncCall');\nlet arrowFunc = GeneratedImportVar_1.getProperty('arrowFunc');\nlet pArrowCall = GeneratedImportVar_1.getProperty('pArrowCall');\n", "line": 16, "column": 1, "endLine": 16, diff --git a/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.ets b/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.ets index a89d3e58d3..a1e4ff667c 100644 --- a/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.ets +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.ets @@ -14,11 +14,11 @@ */ let GeneratedImportVar_1 = ESValue.load('./no_await_js_promise_export'); -let p = GeneratedImportVar_1.getPropertyByName('p'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); -let pFuncCall = GeneratedImportVar_1.getPropertyByName('pFuncCall'); -let arrowFunc = GeneratedImportVar_1.getPropertyByName('arrowFunc'); -let pArrowCall = GeneratedImportVar_1.getPropertyByName('pArrowCall'); +let p = GeneratedImportVar_1.getProperty('p'); +let foo = GeneratedImportVar_1.getProperty('foo'); +let pFuncCall = GeneratedImportVar_1.getProperty('pFuncCall'); +let arrowFunc = GeneratedImportVar_1.getProperty('arrowFunc'); +let pArrowCall = GeneratedImportVar_1.getProperty('pArrowCall'); async function awaitPromise() { diff --git a/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.json b/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.json index 5d4c781348..4aebfd2473 100644 --- a/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.json +++ b/ets2panda/linter/test/interop/no_await_js_promise.ets.migrate.json @@ -28,7 +28,7 @@ "line": 17, "column": 5, "endLine": 17, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +48,7 @@ "line": 19, "column": 5, "endLine": 19, - "endColumn": 68, + "endColumn": 62, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +58,7 @@ "line": 20, "column": 5, "endLine": 20, - "endColumn": 68, + "endColumn": 62, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 21, "column": 5, "endLine": 21, - "endColumn": 70, + "endColumn": 64, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.autofix.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.autofix.json index 8b4189586e..bf8dcb076d 100644 --- a/ets2panda/linter/test/interop/no_js_instanceof.ets.autofix.json +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 692, "end": 692, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./no_js_instanceof_file.js');\nlet Foo = GeneratedImportVar_1.getPropertyByName('Foo');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\nlet CreatePerson = GeneratedImportVar_1.getPropertyByName('CreatePerson');\nlet a = GeneratedImportVar_1.getPropertyByName('a');\nlet b = GeneratedImportVar_1.getPropertyByName('b');\nlet MyNamespace = GeneratedImportVar_1.getPropertyByName('MyNamespace');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./no_js_instanceof_file.js');\nlet Foo = GeneratedImportVar_1.getProperty('Foo');\nlet foo = GeneratedImportVar_1.getProperty('foo');\nlet CreatePerson = GeneratedImportVar_1.getProperty('CreatePerson');\nlet a = GeneratedImportVar_1.getProperty('a');\nlet b = GeneratedImportVar_1.getProperty('b');\nlet MyNamespace = GeneratedImportVar_1.getProperty('MyNamespace');\n", "line": 16, "column": 1, "endLine": 16, @@ -316,7 +316,7 @@ { "start": 1296, "end": 1311, - "replacementText": "MyNamespace.getPropertyByName(\"Dog\")", + "replacementText": "MyNamespace.getProperty(\"Dog\")", "line": 72, "column": 36, "endLine": 72, @@ -358,7 +358,7 @@ { "start": 1344, "end": 1359, - "replacementText": "MyNamespace.getPropertyByName(\"Dog\")", + "replacementText": "MyNamespace.getProperty(\"Dog\")", "line": 74, "column": 22, "endLine": 74, @@ -377,7 +377,7 @@ "problem": "InteropJsObjectConditionJudgment", "autofix": [ { - "replacementText": "MyNamespace.getPropertyByName('Dog')", + "replacementText": "MyNamespace.getProperty('Dog')", "start": 1344, "end": 1359, "line": 74, diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.ets b/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.ets index b71a99dcc0..89f487d233 100644 --- a/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.ets +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.ets @@ -14,12 +14,12 @@ */ let GeneratedImportVar_1 = ESValue.load('./no_js_instanceof_file.js'); -let Foo = GeneratedImportVar_1.getPropertyByName('Foo'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); -let CreatePerson = GeneratedImportVar_1.getPropertyByName('CreatePerson'); -let a = GeneratedImportVar_1.getPropertyByName('a'); -let b = GeneratedImportVar_1.getPropertyByName('b'); -let MyNamespace = GeneratedImportVar_1.getPropertyByName('MyNamespace'); +let Foo = GeneratedImportVar_1.getProperty('Foo'); +let foo = GeneratedImportVar_1.getProperty('foo'); +let CreatePerson = GeneratedImportVar_1.getProperty('CreatePerson'); +let a = GeneratedImportVar_1.getProperty('a'); +let b = GeneratedImportVar_1.getProperty('b'); +let MyNamespace = GeneratedImportVar_1.getProperty('MyNamespace'); class Foo1 {} @@ -76,7 +76,7 @@ if(b().isInstanceOf(Array)) { } -const myDog: MyNamespace.Dog = new MyNamespace.getPropertyByName("Dog")('Buddy'); +const myDog: MyNamespace.Dog = new MyNamespace.getProperty("Dog")('Buddy'); if (myDog.isInstanceOf(MyNamespace.Dog)) { console.log("This is a Dog!"); diff --git a/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.json b/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.json index 63aabda702..4a61cb89de 100644 --- a/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.json +++ b/ets2panda/linter/test/interop/no_js_instanceof.ets.migrate.json @@ -28,7 +28,7 @@ "line": 17, "column": 5, "endLine": 17, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 18, "column": 5, "endLine": 18, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -48,7 +48,7 @@ "line": 19, "column": 5, "endLine": 19, - "endColumn": 74, + "endColumn": 68, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -58,7 +58,7 @@ "line": 20, "column": 5, "endLine": 20, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -68,7 +68,7 @@ "line": 21, "column": 5, "endLine": 21, - "endColumn": 52, + "endColumn": 46, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -78,7 +78,7 @@ "line": 22, "column": 5, "endLine": 22, - "endColumn": 72, + "endColumn": 66, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -108,7 +108,7 @@ "line": 79, "column": 36, "endLine": 79, - "endColumn": 65, + "endColumn": 59, "problem": "DynamicCtorCall", "suggest": "", "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", diff --git a/ets2panda/linter/test/interop/object_built_in.ets b/ets2panda/linter/test/interop/object_built_in.ets index 3170f3f087..3b9dceea07 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets +++ b/ets2panda/linter/test/interop/object_built_in.ets @@ -25,3 +25,11 @@ export function foo(prx: Object) { } foo(new X()); // Illegal + +export function shouldPass() { + const bar = JSON.parse('{}'); + console.log(Object.keys(bar).length); +} + +shouldPass() + diff --git a/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json b/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json index d9cadcd5d4..41a2db7981 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json +++ b/ets2panda/linter/test/interop/object_built_in.ets.arkts2.json @@ -55,14 +55,14 @@ "severity": "ERROR" }, { - "line": 27, - "column": 1, - "endLine": 27, - "endColumn": 14, - "problem": "InteropCallObjectParam", + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 33, + "problem": "AnyType", "suggest": "", - "rule": "Class type is not compatible with \"Object\" parameter in interop call (arkts-interop-d2s-static-object-on-dynamic-instance)", + "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/object_built_in.ets.json b/ets2panda/linter/test/interop/object_built_in.ets.json index d2adea10e5..1918dfda67 100644 --- a/ets2panda/linter/test/interop/object_built_in.ets.json +++ b/ets2panda/linter/test/interop/object_built_in.ets.json @@ -45,14 +45,14 @@ "severity": "ERROR" }, { - "line": 27, - "column": 1, - "endLine": 27, - "endColumn": 14, - "problem": "InteropCallObjectParam", + "line": 30, + "column": 11, + "endLine": 30, + "endColumn": 33, + "problem": "AnyType", "suggest": "", - "rule": "Class type is not compatible with \"Object\" parameter in interop call (arkts-interop-d2s-static-object-on-dynamic-instance)", + "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/reflect_built_in.ets.arkts2.json b/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json index 1dd3014588..c76a12de83 100644 --- a/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json +++ b/ets2panda/linter/test/interop/reflect_built_in.ets.arkts2.json @@ -64,26 +64,6 @@ "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": 27, - "column": 1, - "endLine": 27, - "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": 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": 29, "column": 1, @@ -164,16 +144,6 @@ "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": 41, - "column": 1, - "endLine": 41, - "endColumn": 33, - "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": 42, "column": 1, @@ -214,16 +184,6 @@ "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": 46, - "column": 1, - "endLine": 46, - "endColumn": 22, - "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": 47, "column": 1, @@ -264,16 +224,6 @@ "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": 51, - "column": 1, - "endLine": 51, - "endColumn": 31, - "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": 52, "column": 1, @@ -314,16 +264,6 @@ "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": 56, - "column": 1, - "endLine": 56, - "endColumn": 27, - "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": 57, "column": 1, @@ -355,4 +295,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/interop/reflect_built_in.ets.json b/ets2panda/linter/test/interop/reflect_built_in.ets.json index eb39c3a62e..ef3d440bfb 100644 --- a/ets2panda/linter/test/interop/reflect_built_in.ets.json +++ b/ets2panda/linter/test/interop/reflect_built_in.ets.json @@ -54,26 +54,6 @@ "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": 27, - "column": 1, - "endLine": 27, - "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": 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, @@ -134,16 +114,6 @@ "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": 41, - "column": 1, - "endLine": 41, - "endColumn": 33, - "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": 42, "column": 1, @@ -174,16 +144,6 @@ "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": 46, - "column": 1, - "endLine": 46, - "endColumn": 22, - "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": 47, "column": 1, @@ -214,16 +174,6 @@ "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": 51, - "column": 1, - "endLine": 51, - "endColumn": 31, - "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": 52, "column": 1, @@ -254,16 +204,6 @@ "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": 56, - "column": 1, - "endLine": 56, - "endColumn": 27, - "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": 57, "column": 1, @@ -295,4 +235,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.autofix.json b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.autofix.json index 07cb92eb1a..b3d6f3508f 100644 --- a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.autofix.json +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.autofix.json @@ -33,7 +33,7 @@ { "start": 654, "end": 654, - "replacementText": "let GeneratedImportVar_1 = ESValue.load('./unary_operation_js_obj_js.js');\nlet foo = GeneratedImportVar_1.getPropertyByName('foo');\n", + "replacementText": "let GeneratedImportVar_1 = ESValue.load('./unary_operation_js_obj_js.js');\nlet foo = GeneratedImportVar_1.getProperty('foo');\n", "line": 15, "column": 1, "endLine": 15, @@ -54,7 +54,7 @@ { "start": 657, "end": 664, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "replacementText": "foo.getProperty(\"num\").toNumber()", "line": 17, "column": 1, "endLine": 17, @@ -75,7 +75,7 @@ { "start": 657, "end": 664, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 17, "column": 2, "endLine": 17, @@ -96,7 +96,7 @@ { "start": 667, "end": 674, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "replacementText": "foo.getProperty(\"num\").toNumber()", "line": 18, "column": 1, "endLine": 18, @@ -117,7 +117,7 @@ { "start": 667, "end": 674, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 18, "column": 2, "endLine": 18, @@ -138,7 +138,7 @@ { "start": 677, "end": 684, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "replacementText": "foo.getProperty(\"num\").toNumber()", "line": 19, "column": 1, "endLine": 19, @@ -159,7 +159,7 @@ { "start": 677, "end": 684, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 19, "column": 2, "endLine": 19, @@ -180,7 +180,7 @@ { "start": 687, "end": 694, - "replacementText": "foo.getPropertyByName(\"num\").toNumber()", + "replacementText": "foo.getProperty(\"num\").toNumber()", "line": 20, "column": 1, "endLine": 20, @@ -201,7 +201,7 @@ { "start": 687, "end": 694, - "replacementText": "foo.getPropertyByName(\"num\")", + "replacementText": "foo.getProperty(\"num\")", "line": 20, "column": 2, "endLine": 20, diff --git a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.ets b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.ets index 5448d6f5f0..d0a648c942 100644 --- a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.ets +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.ets @@ -13,10 +13,10 @@ * limitations under the License. */ let GeneratedImportVar_1 = ESValue.load('./unary_operation_js_obj_js.js'); -let foo = GeneratedImportVar_1.getPropertyByName('foo'); +let foo = GeneratedImportVar_1.getProperty('foo'); -+foo.getPropertyByName("num").toNumber(); --foo.getPropertyByName("num").toNumber(); -!foo.getPropertyByName("num").toNumber(); -~foo.getPropertyByName("num").toNumber(); \ No newline at end of file ++foo.getProperty("num").toNumber(); +-foo.getProperty("num").toNumber(); +!foo.getProperty("num").toNumber(); +~foo.getProperty("num").toNumber(); \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.json b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.json index 4d448e180c..8fbd5964c4 100644 --- a/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.json +++ b/ets2panda/linter/test/interop/unary_operation_js_obj.ets.migrate.json @@ -28,7 +28,7 @@ "line": 16, "column": 5, "endLine": 16, - "endColumn": 56, + "endColumn": 50, "problem": "AnyType", "suggest": "", "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", @@ -38,7 +38,7 @@ "line": 19, "column": 1, "endLine": 19, - "endColumn": 41, + "endColumn": 35, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", @@ -48,7 +48,7 @@ "line": 20, "column": 1, "endLine": 20, - "endColumn": 41, + "endColumn": 35, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", @@ -58,7 +58,7 @@ "line": 22, "column": 1, "endLine": 22, - "endColumn": 41, + "endColumn": 35, "problem": "UnaryArithmNotNumber", "suggest": "", "rule": "Unary operators \"+\", \"-\" and \"~\" work only on numbers (arkts-no-polymorphic-unops)", diff --git a/ets2panda/linter/test/interop/unique_types.ets b/ets2panda/linter/test/interop/unique_types.ets index da2c034f53..9c16a54d2b 100644 --- a/ets2panda/linter/test/interop/unique_types.ets +++ b/ets2panda/linter/test/interop/unique_types.ets @@ -14,22 +14,387 @@ */ import { - objectLiteralType, - intersectionType, - tsFunction, - stringType, - enumType + any_var, + unknown_var, + symbol_var, + function_var, + A, + B, + TestHelper, + throw_number, + throw_string, + throw_boolean, + throw_bigint, + throw_obj, + throw_error, + throwErrorSubClass, + SubError, + throwRangeError, + ObjectLiteralClass, + ObjectLiteralInter, + MyClassDecorator, + propertyDecorator, + methodDecorator, + parameterDecorator, + accessorDecorator, + readonly1, + num_boxed, + bool_boxed, + str_boxed, + bigint_boxed, + ts_object_method, + ts_object_method_getOwnPropertyDescriptor, + ts_object_method_getOwnPropertyDescriptors, + ts_object_method_getOwnPropertyNames, + ts_object_method_hasOwn, + ts_object_method_isExtensible, + ts_object_method_isFrozen, + ts_object_method_isSealed, + ts_object_method_keys, + ts_object_method_values, + interObj, + ts_reflect_method, + ts_reflect_method_apply, + ts_reflect_method_defineProperty, + ts_reflect_method_deleteProperty, + ts_reflect_method_getOwnPropertyDescriptor, + ts_reflect_method_ownKeys, + ts_reflect_method_isExtensible, + ts_reflect_method_set, + ts_reflect_method_setPrototypeOf } from "./ignore_files/unique_types"; -objectLiteralType.name = "test" -intersectionType.name = "test"; +typeof any_var === 'object'; +typeof unknown_var === 'number'; +typeof symbol_var === 'object'; +function_var() === true; +A.instance; +let obj: B = { name: "hello" }; -try { -tsFunction(); -} catch (e) { +export function test_ts_non_standard_exception(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_TS_NON_STANDARD_EXCEPTION"); + + test_helper.test(() => { + try { + throw_number(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e as number === 123; + } + return false; + }, "e as number === 123"); + + test_helper.test(() => { + try { + throw_boolean(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e as boolean === true; + } + return false; + }, "e as boolean === true"); + + test_helper.test(() => { + try { + throw_bigint(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e as bigint === 111n; + } + return false; + }, "e as bigint === 111n"); + + test_helper.test(() => { + try { + throw_string(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e as string === "error"; + } + return false; + }, "e as string === "error""); + + test_helper.test(() => { + try { + throw_obj(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e.name === "error"; + } + return false; + }, "e.name === "error""); + + test_helper.test(() => { + try { + throw_error(); + } catch (e) { + let errObj: Error = e as Error; + return errObj.name === "error"; + } + return false; + }, "errObj.name === "error""); + + test_helper.test(() => { + try { + throwErrorSubClass(); // arkts-interop-ts2s-ts-exception + } catch (e) { + let errObj = e as SubError; + return errObj.extraField === 123 && errObj.foo() === 456; + } + return false; + }, "errObj.extraField === 123 && errObj.foo() === 456"); + + test_helper.test(() => { + let flag = false + try { + throwRangeError(); // arkts-interop-ts2s-ts-exception + } catch (e) { + let errObj: RangeError = e as RangeError; + return errObj instanceof RangeError; + } + return flag; + }, "Throw: throwRangeError"); + + testCaseRet.push(test_helper.done()); +} + +export function test_object_literal(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_OBJECT_LITERAL"); + + test_helper.test(() => { + let obj: ObjectLiteralClass = { name: "hello" }; // arkts-obj-literal-generate-class-instance + return obj.name === "hello" && obj instanceof ObjectLiteralClass; + }, "obj.name === "hello""); + + test_helper.test(() => { + let obj: ObjectLiteralInter = { name: "hello" }; // arkts-obj-literal-generate-class-instance + return obj.name === "hello" && obj instanceof ObjectLiteralInter; + }, "obj.name === "hello""); + + testCaseRet.push(test_helper.done()); +} + +// 1 ArkTS使用TS装饰器 +// 规则名 arkts-interop-ts2s-no-ts-decorator +// case 1 类装饰器 top level +@MyClassDecorator // arkts-no-ts-decorators + arkts-interop-ts2s-no-ts-decorator +class K {} + +//case 2 类属性装饰器 +class MyClass { + @propertyDecorator// arkts-no-ts-decorators + myProperty: string; +} + +//case 3 方法装饰器 +class MathFunctions { + @methodDecorator// arkts-no-ts-decorators + double1(value: number): number { + return value; + } +} + +//case 4 方法装饰器 +class MyClass1 { + log(value: string, @parameterDecorator metadata: any) {// arkts-no-ts-decorators + console.log(Logged: ${value}); + } +} + +//case 5 访问器装饰器 +class Person { + private _name: string; + @accessorDecorator// arkts-no-ts-decorators + get name(): string { + return this._name; + } + set name(value: string) { + this._name = value; + } +} + +//case 6 访问器工厂 +class Person1 { + private _age: number; + @readonly(true)// arkts-no-ts-decorators + get age(): number { + return this._age; + } + set age(value: number) { + this._age = value; + } +} + +namespace NS{ + // case 7 类装饰器 top level + @MyClassDecorator// arkts-no-ts-decorators + arkts-interop-ts2s-no-ts-decorator + class K {} + + //case 8 类属性装饰器 + class MyClass { + @propertyDecorator// arkts-no-ts-decorators + myProperty: string; + } + + //case 9 方法装饰器 + class MathFunctions { + @methodDecorator// arkts-no-ts-decorators + double1(value: number): number { + return value; + } + } + + //case 10 方法装饰器 + class MyClass1 { + log(value: string, @parameterDecorator metadata: any) {// arkts-no-ts-decorators + console.log(Logged: ${value}); + } + } + + //case 11 访问器装饰器 + class Person { + private _name: string; + constructor(name: string) { + this._name = name; + } + @accessorDecorator// arkts-no-ts-decorators + get name(): string { + return this._name; + } + set name(value: string) { + this._name = value; + } + } + + //case 12 访问器工厂 + class Person1 { + private _age: number; + constructor(age: number) { + this._age = age; + } + @readonly1(true)// arkts-no-ts-decorators + get age(): number { + return this._age; + } + set age(value: number) { + this._age = value; + } + } +} + +export function test_ts_boxed_type(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_TS_BOXED_TYPE"); + + test_helper.test(() => { + return typeof num_boxed === object; + }, "typeof num_boxed === object"); + + test_helper.test(() => { + return typeof bool_boxed === object; + }, "typeof bool_boxed === object"); + + test_helper.test(() => { + return typeof str_boxed === object; + }, "typeof str_boxed === object"); + + test_helper.test(() => { + return typeof bigint_boxed === object; + }, "typeof bigint_boxed === object"); + testCaseRet.push(test_helper.done()); +} + +export function test_ts_object_method(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_TS_OBJECT_METHOD"); + + test_helper.test(() => { + ts_object_method(new Object2()) + ts_object_method_getOwnPropertyDescriptor(new Object2()) + ts_object_method_getOwnPropertyDescriptors(new Object2()) + ts_object_method_getOwnPropertyNames(new Object2()) + ts_object_method_hasOwn(new Object2()) + ts_object_method_isExtensible(new Object2()) + ts_object_method_isFrozen(new Object2()) + ts_object_method_isSealed(new Object2()) + ts_object_method_keys(new Object2()) + ts_object_method_keys(new Object2()) + ts_object_method_values(new Object2()) + return true; + }, "true"); + + test_helper.test(() => { + interface Iface { + a:number + } + let a1:Iface = {a:1} + ts_object_method(a1) + ts_object_method_getOwnPropertyDescriptor(a1) + ts_object_method_getOwnPropertyDescriptors(a1) + ts_object_method_getOwnPropertyNames(a1) + ts_object_method_hasOwn(a1) + ts_object_method_isExtensible(a1) + ts_object_method_isFrozen(a1) + ts_object_method_isSealed(a1) + ts_object_method_keys(a1) + ts_object_method_keys(a1) + ts_object_method_values(a1) + return true; + }, "true"); + + test_helper.test(() => { + ts_object_method(interObj) + return true; + }, "false"); + + testCaseRet.push(test_helper.done()); +} + +class Reflect2 { + a: string = 'hello' + getName() { return this.a } } -stringType = "test" //should pass +// 5 Object内置方法作用在ArkTS对象 +// 规则名 arkts-interop-ts2s-ts-object-on-static-instance +export function test_ts_reflect_method(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_TS_REFLECT_METHOD"); + test_helper.test(() => { + ts_reflect_method(new Reflect2()) + ts_reflect_method_apply(new Reflect2()) + ts_reflect_method_defineProperty(new Reflect2()) + ts_reflect_method_deleteProperty(new Reflect2()) + ts_reflect_method_getOwnPropertyDescriptor(new Reflect2()) + ts_reflect_method_ownKeys(new Reflect2()) + ts_reflect_method_isExtensible(new Reflect2()) + ts_reflect_method_set(new Reflect2()) + ts_reflect_method_setPrototypeOf(new Reflect2()) + return true; + }, "reflect class 1.2 "); + + test_helper.test(() => { + interface Iface { + a:number + } + let a1:Iface = {a:1} + ts_reflect_method(a1) + ts_reflect_method_apply(a1) + ts_reflect_method_defineProperty(a1) + ts_reflect_method_deleteProperty(a1) + ts_reflect_method_getOwnPropertyDescriptor(a1) + ts_reflect_method_ownKeys(a1) + ts_reflect_method_isExtensible(a1) + ts_reflect_method_set(a1) + ts_reflect_method_setPrototypeOf(a1) + return true; + }, "reflect interface 1.2"); + + test_helper.test(() => { + ts_reflect_method(interObj) + ts_reflect_method_apply(interObj) + ts_reflect_method_defineProperty(interObj) + ts_reflect_method_deleteProperty(interObj) + ts_reflect_method_getOwnPropertyDescriptor(interObj) + ts_reflect_method_ownKeys(interObj) + ts_reflect_method_isExtensible(interObj) + ts_reflect_method_set(interObj) + ts_reflect_method_setPrototypeOf(interObj) + return true; + }, "reflect interObj 1.0 "); -enumType = "A"; //should fail + testCaseRet.push(test_helper.done()); +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unique_types.ets.arkts2.json b/ets2panda/linter/test/interop/unique_types.ets.arkts2.json index b3274fd874..7fb34afcb3 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.arkts2.json +++ b/ets2panda/linter/test/interop/unique_types.ets.arkts2.json @@ -15,63 +15,543 @@ ], "result": [ { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 23, + "line": 68, + "column": 8, + "endLine": 68, + "endColumn": 15, "problem": "InteropDirectAccessToTSTypes", "suggest": "", "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 26, - "column": 1, - "endLine": 26, - "endColumn": 22, + "line": 69, + "column": 8, + "endLine": 69, + "endColumn": 19, + "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 18, "problem": "InteropDirectAccessToTSTypes", "suggest": "", "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 29, + "line": 71, "column": 1, - "endLine": 29, + "endLine": 71, "endColumn": 13, - "problem": "InteropTSFunctionInvoke", + "problem": "ExplicitFunctionType", "suggest": "", - "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { - "line": 29, + "line": 71, "column": 1, - "endLine": 29, - "endColumn": 11, + "endLine": 71, + "endColumn": 13, "problem": "InteropDirectAccessToTSTypes", "suggest": "", "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 33, + "line": 76, + "column": 7, + "endLine": 76, + "endColumn": 69, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 25, + "endLine": 76, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 7, + "endLine": 80, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 30, + "endLine": 82, + "endColumn": 33, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 7, + "endLine": 89, + "endColumn": 22, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 7, + "endLine": 98, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 7, + "endLine": 107, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 7, + "endLine": 116, + "endColumn": 18, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 36, + "endLine": 138, + "endColumn": 39, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 60, + "endLine": 138, + "endColumn": 63, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 7, + "endLine": 158, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 25, + "endLine": 158, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 176, "column": 1, - "endLine": 33, + "endLine": 176, + "endColumn": 18, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 181, + "column": 3, + "endLine": 181, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 187, + "column": 3, + "endLine": 187, + "endColumn": 19, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 22, + "endLine": 195, + "endColumn": 41, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 52, + "endLine": 195, + "endColumn": 55, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 203, + "column": 3, + "endLine": 203, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 215, + "column": 3, + "endLine": 215, + "endColumn": 18, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 3, + "endLine": 226, "endColumn": 20, - "problem": "InteropDirectAccessToTSTypes", + "problem": "DecoratorsNotSupported", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", "severity": "ERROR" }, { - "line": 33, - "column": 1, - "endLine": 33, - "endColumn": 11, - "problem": "InteropDirectAccessToTSTypes", + "line": 231, + "column": 5, + "endLine": 231, + "endColumn": 23, + "problem": "DecoratorsNotSupported", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 237, + "column": 5, + "endLine": 237, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 24, + "endLine": 245, + "endColumn": 43, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 54, + "endLine": 245, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 256, + "column": 5, + "endLine": 256, + "endColumn": 23, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 271, + "column": 5, + "endLine": 271, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 282, + "column": 7, + "endLine": 282, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 282, + "column": 25, + "endLine": 282, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 7, + "endLine": 303, + "endColumn": 60, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 25, + "endLine": 303, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 306, + "column": 26, + "endLine": 306, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 307, + "column": 51, + "endLine": 307, + "endColumn": 58, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 308, + "column": 52, + "endLine": 308, + "endColumn": 59, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 309, + "column": 46, + "endLine": 309, + "endColumn": 53, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 310, + "column": 33, + "endLine": 310, + "endColumn": 40, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 311, + "column": 39, + "endLine": 311, + "endColumn": 46, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 312, + "column": 35, + "endLine": 312, + "endColumn": 42, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 313, + "column": 35, + "endLine": 313, + "endColumn": 42, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 314, + "column": 31, + "endLine": 314, + "endColumn": 38, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 315, + "column": 31, + "endLine": 315, + "endColumn": 38, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 316, + "column": 33, + "endLine": 316, + "endColumn": 40, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 324, + "column": 23, + "endLine": 324, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 355, + "column": 7, + "endLine": 355, + "endColumn": 61, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 355, + "column": 25, + "endLine": 355, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 373, + "column": 23, + "endLine": 373, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 3, + "endLine": 182, + "endColumn": 13, + "problem": "StrictDiagnostic", + "suggest": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 202, + "column": 11, + "endLine": 202, + "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": 214, + "column": 11, + "endLine": 214, + "endColumn": 15, + "problem": "StrictDiagnostic", + "suggest": "Property '_age' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '_age' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 232, + "column": 5, + "endLine": 232, + "endColumn": 15, + "problem": "StrictDiagnostic", + "suggest": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/unique_types.ets.autofix.json b/ets2panda/linter/test/interop/unique_types.ets.autofix.json index a6deb3a499..bdb124b2ed 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.autofix.json +++ b/ets2panda/linter/test/interop/unique_types.ets.autofix.json @@ -15,85 +15,609 @@ ], "result": [ { - "line": 24, - "column": 1, - "endLine": 24, - "endColumn": 23, + "line": 68, + "column": 8, + "endLine": 68, + "endColumn": 15, + "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + }, + { + "line": 69, + "column": 8, + "endLine": 69, + "endColumn": 19, "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + }, + { + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 18, + "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + }, + { + "line": 71, + "column": 1, + "endLine": 71, + "endColumn": 13, + "problem": "ExplicitFunctionType", "autofix": [ { - "start": 731, - "end": 762, - "replacementText": "objectLiteralType.setPropertyByName('name',ESValue.wrap(\"test\"))", - "line": 24, + "start": 1767, + "end": 1779, + "replacementText": "function_var.unsafeCall", + "line": 71, "column": 1, - "endLine": 24, - "endColumn": 23 + "endLine": 71, + "endColumn": 13 } ], "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", "severity": "ERROR" }, { - "line": 26, + "line": 71, "column": 1, - "endLine": 26, - "endColumn": 22, + "endLine": 71, + "endColumn": 13, "problem": "InteropDirectAccessToTSTypes", + "suggest": "", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 7, + "endLine": 76, + "endColumn": 69, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 25, + "endLine": 76, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 7, + "endLine": 80, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 82, + "column": 30, + "endLine": 82, + "endColumn": 33, + "problem": "NumericSemantics", "autofix": [ { - "start": 764, - "end": 794, - "replacementText": "intersectionType.setPropertyByName('name',ESValue.wrap(\"test\"))", - "line": 26, - "column": 1, - "endLine": 26, - "endColumn": 22 + "start": 2118, + "end": 2121, + "replacementText": "123.0", + "line": 82, + "column": 30, + "endLine": 82, + "endColumn": 33 } ], "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, { - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 13, + "line": 89, + "column": 7, + "endLine": 89, + "endColumn": 22, "problem": "InteropTSFunctionInvoke", "suggest": "", "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", "severity": "ERROR" }, { - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 11, - "problem": "InteropDirectAccessToTSTypes", + "line": 98, + "column": 7, + "endLine": 98, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", "severity": "ERROR" }, { - "line": 33, + "line": 107, + "column": 7, + "endLine": 107, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 7, + "endLine": 116, + "endColumn": 18, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 36, + "endLine": 138, + "endColumn": 39, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 3384, + "end": 3387, + "replacementText": "123.0", + "line": 138, + "column": 36, + "endLine": 138, + "endColumn": 39 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 138, + "column": 60, + "endLine": 138, + "endColumn": 63, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 3408, + "end": 3411, + "replacementText": "456.0", + "line": 138, + "column": 60, + "endLine": 138, + "endColumn": 63 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 7, + "endLine": 158, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 25, + "endLine": 158, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 176, "column": 1, - "endLine": 33, + "endLine": 176, + "endColumn": 18, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 181, + "column": 3, + "endLine": 181, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 187, + "column": 3, + "endLine": 187, + "endColumn": 19, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 22, + "endLine": 195, + "endColumn": 41, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 52, + "endLine": 195, + "endColumn": 55, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 203, + "column": 3, + "endLine": 203, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 215, + "column": 3, + "endLine": 215, + "endColumn": 18, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 3, + "endLine": 226, "endColumn": 20, - "problem": "InteropDirectAccessToTSTypes", + "problem": "DecoratorsNotSupported", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", "severity": "ERROR" }, { - "line": 33, - "column": 1, - "endLine": 33, - "endColumn": 11, - "problem": "InteropDirectAccessToTSTypes", + "line": 231, + "column": 5, + "endLine": 231, + "endColumn": 23, + "problem": "DecoratorsNotSupported", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 237, + "column": 5, + "endLine": 237, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 24, + "endLine": 245, + "endColumn": 43, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 54, + "endLine": 245, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 256, + "column": 5, + "endLine": 256, + "endColumn": 23, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 271, + "column": 5, + "endLine": 271, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 282, + "column": 7, + "endLine": 282, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 282, + "column": 25, + "endLine": 282, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 7, + "endLine": 303, + "endColumn": 60, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 25, + "endLine": 303, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 306, + "column": 26, + "endLine": 306, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 307, + "column": 51, + "endLine": 307, + "endColumn": 58, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 308, + "column": 52, + "endLine": 308, + "endColumn": 59, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 309, + "column": 46, + "endLine": 309, + "endColumn": 53, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 310, + "column": 33, + "endLine": 310, + "endColumn": 40, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 311, + "column": 39, + "endLine": 311, + "endColumn": 46, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 312, + "column": 35, + "endLine": 312, + "endColumn": 42, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 313, + "column": 35, + "endLine": 313, + "endColumn": 42, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 314, + "column": 31, + "endLine": 314, + "endColumn": 38, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 315, + "column": 31, + "endLine": 315, + "endColumn": 38, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 316, + "column": 33, + "endLine": 316, + "endColumn": 40, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 324, + "column": 23, + "endLine": 324, + "endColumn": 24, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 7971, + "end": 7972, + "replacementText": "1.0", + "line": 324, + "column": 23, + "endLine": 324, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 355, + "column": 7, + "endLine": 355, + "endColumn": 61, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 355, + "column": 25, + "endLine": 355, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 373, + "column": 23, + "endLine": 373, + "endColumn": 24, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 9425, + "end": 9426, + "replacementText": "1.0", + "line": 373, + "column": 23, + "endLine": 373, + "endColumn": 24 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 3, + "endLine": 182, + "endColumn": 13, + "problem": "StrictDiagnostic", + "suggest": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 202, + "column": 11, + "endLine": 202, + "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": 214, + "column": 11, + "endLine": 214, + "endColumn": 15, + "problem": "StrictDiagnostic", + "suggest": "Property '_age' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '_age' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 232, + "column": 5, + "endLine": 232, + "endColumn": 15, + "problem": "StrictDiagnostic", + "suggest": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/interop/unique_types.ets.json b/ets2panda/linter/test/interop/unique_types.ets.json index ca88f857e9..017acb4fb6 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.json +++ b/ets2panda/linter/test/interop/unique_types.ets.json @@ -13,5 +13,116 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [] + "result": [ + { + "line": 76, + "column": 7, + "endLine": 76, + "endColumn": 69, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 7, + "endLine": 158, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 52, + "endLine": 195, + "endColumn": 55, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 54, + "endLine": 245, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 282, + "column": 7, + "endLine": 282, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 7, + "endLine": 303, + "endColumn": 60, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 355, + "column": 7, + "endLine": 355, + "endColumn": 61, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 3, + "endLine": 182, + "endColumn": 13, + "problem": "StrictDiagnostic", + "suggest": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 202, + "column": 11, + "endLine": 202, + "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": 214, + "column": 11, + "endLine": 214, + "endColumn": 15, + "problem": "StrictDiagnostic", + "suggest": "Property '_age' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '_age' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 232, + "column": 5, + "endLine": 232, + "endColumn": 15, + "problem": "StrictDiagnostic", + "suggest": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'myProperty' 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/interop/unique_types.ets.migrate.ets b/ets2panda/linter/test/interop/unique_types.ets.migrate.ets index 884003da24..6f0585bf51 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.migrate.ets +++ b/ets2panda/linter/test/interop/unique_types.ets.migrate.ets @@ -14,22 +14,387 @@ */ import { - objectLiteralType, - intersectionType, - tsFunction, - stringType, - enumType + any_var, + unknown_var, + symbol_var, + function_var, + A, + B, + TestHelper, + throw_number, + throw_string, + throw_boolean, + throw_bigint, + throw_obj, + throw_error, + throwErrorSubClass, + SubError, + throwRangeError, + ObjectLiteralClass, + ObjectLiteralInter, + MyClassDecorator, + propertyDecorator, + methodDecorator, + parameterDecorator, + accessorDecorator, + readonly1, + num_boxed, + bool_boxed, + str_boxed, + bigint_boxed, + ts_object_method, + ts_object_method_getOwnPropertyDescriptor, + ts_object_method_getOwnPropertyDescriptors, + ts_object_method_getOwnPropertyNames, + ts_object_method_hasOwn, + ts_object_method_isExtensible, + ts_object_method_isFrozen, + ts_object_method_isSealed, + ts_object_method_keys, + ts_object_method_values, + interObj, + ts_reflect_method, + ts_reflect_method_apply, + ts_reflect_method_defineProperty, + ts_reflect_method_deleteProperty, + ts_reflect_method_getOwnPropertyDescriptor, + ts_reflect_method_ownKeys, + ts_reflect_method_isExtensible, + ts_reflect_method_set, + ts_reflect_method_setPrototypeOf } from "./ignore_files/unique_types"; -objectLiteralType.setPropertyByName('name',ESValue.wrap("test")) -intersectionType.setPropertyByName('name',ESValue.wrap("test")); +typeof any_var === 'object'; +typeof unknown_var === 'number'; +typeof symbol_var === 'object'; +function_var.unsafeCall() === true; +A.instance; +let obj: B = { name: "hello" }; -try { -tsFunction(); -} catch (e) { +export function test_ts_non_standard_exception(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_TS_NON_STANDARD_EXCEPTION"); + + test_helper.test(() => { + try { + throw_number(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e as number === 123.0; + } + return false; + }, "e as number === 123"); + + test_helper.test(() => { + try { + throw_boolean(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e as boolean === true; + } + return false; + }, "e as boolean === true"); + + test_helper.test(() => { + try { + throw_bigint(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e as bigint === 111n; + } + return false; + }, "e as bigint === 111n"); + + test_helper.test(() => { + try { + throw_string(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e as string === "error"; + } + return false; + }, "e as string === "error""); + + test_helper.test(() => { + try { + throw_obj(); // arkts-interop-ts2s-ts-exception + } catch (e) { + return e.name === "error"; + } + return false; + }, "e.name === "error""); + + test_helper.test(() => { + try { + throw_error(); + } catch (e) { + let errObj: Error = e as Error; + return errObj.name === "error"; + } + return false; + }, "errObj.name === "error""); + + test_helper.test(() => { + try { + throwErrorSubClass(); // arkts-interop-ts2s-ts-exception + } catch (e) { + let errObj = e as SubError; + return errObj.extraField === 123.0 && errObj.foo() === 456.0; + } + return false; + }, "errObj.extraField === 123 && errObj.foo() === 456"); + + test_helper.test(() => { + let flag = false + try { + throwRangeError(); // arkts-interop-ts2s-ts-exception + } catch (e) { + let errObj: RangeError = e as RangeError; + return errObj instanceof RangeError; + } + return flag; + }, "Throw: throwRangeError"); + + testCaseRet.push(test_helper.done()); +} + +export function test_object_literal(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_OBJECT_LITERAL"); + + test_helper.test(() => { + let obj: ObjectLiteralClass = { name: "hello" }; // arkts-obj-literal-generate-class-instance + return obj.name === "hello" && obj instanceof ObjectLiteralClass; + }, "obj.name === "hello""); + + test_helper.test(() => { + let obj: ObjectLiteralInter = { name: "hello" }; // arkts-obj-literal-generate-class-instance + return obj.name === "hello" && obj instanceof ObjectLiteralInter; + }, "obj.name === "hello""); + + testCaseRet.push(test_helper.done()); +} + +// 1 ArkTS使用TS装饰器 +// 规则名 arkts-interop-ts2s-no-ts-decorator +// case 1 类装饰器 top level +@MyClassDecorator // arkts-no-ts-decorators + arkts-interop-ts2s-no-ts-decorator +class K {} + +//case 2 类属性装饰器 +class MyClass { + @propertyDecorator// arkts-no-ts-decorators + myProperty: string; +} + +//case 3 方法装饰器 +class MathFunctions { + @methodDecorator// arkts-no-ts-decorators + double1(value: number): number { + return value; + } +} + +//case 4 方法装饰器 +class MyClass1 { + log(value: string, @parameterDecorator metadata: any) {// arkts-no-ts-decorators + console.log(Logged: ${value}); + } +} + +//case 5 访问器装饰器 +class Person { + private _name: string; + @accessorDecorator// arkts-no-ts-decorators + get name(): string { + return this._name; + } + set name(value: string) { + this._name = value; + } +} + +//case 6 访问器工厂 +class Person1 { + private _age: number; + @readonly(true)// arkts-no-ts-decorators + get age(): number { + return this._age; + } + set age(value: number) { + this._age = value; + } +} + +namespace NS{ + // case 7 类装饰器 top level + @MyClassDecorator// arkts-no-ts-decorators + arkts-interop-ts2s-no-ts-decorator + class K {} + + //case 8 类属性装饰器 + class MyClass { + @propertyDecorator// arkts-no-ts-decorators + myProperty: string; + } + + //case 9 方法装饰器 + class MathFunctions { + @methodDecorator// arkts-no-ts-decorators + double1(value: number): number { + return value; + } + } + + //case 10 方法装饰器 + class MyClass1 { + log(value: string, @parameterDecorator metadata: any) {// arkts-no-ts-decorators + console.log(Logged: ${value}); + } + } + + //case 11 访问器装饰器 + class Person { + private _name: string; + constructor(name: string) { + this._name = name; + } + @accessorDecorator// arkts-no-ts-decorators + get name(): string { + return this._name; + } + set name(value: string) { + this._name = value; + } + } + + //case 12 访问器工厂 + class Person1 { + private _age: number; + constructor(age: number) { + this._age = age; + } + @readonly1(true)// arkts-no-ts-decorators + get age(): number { + return this._age; + } + set age(value: number) { + this._age = value; + } + } +} + +export function test_ts_boxed_type(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_TS_BOXED_TYPE"); + + test_helper.test(() => { + return typeof num_boxed === object; + }, "typeof num_boxed === object"); + + test_helper.test(() => { + return typeof bool_boxed === object; + }, "typeof bool_boxed === object"); + + test_helper.test(() => { + return typeof str_boxed === object; + }, "typeof str_boxed === object"); + + test_helper.test(() => { + return typeof bigint_boxed === object; + }, "typeof bigint_boxed === object"); + testCaseRet.push(test_helper.done()); +} + +export function test_ts_object_method(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_TS_OBJECT_METHOD"); + + test_helper.test(() => { + ts_object_method(new Object2()) + ts_object_method_getOwnPropertyDescriptor(new Object2()) + ts_object_method_getOwnPropertyDescriptors(new Object2()) + ts_object_method_getOwnPropertyNames(new Object2()) + ts_object_method_hasOwn(new Object2()) + ts_object_method_isExtensible(new Object2()) + ts_object_method_isFrozen(new Object2()) + ts_object_method_isSealed(new Object2()) + ts_object_method_keys(new Object2()) + ts_object_method_keys(new Object2()) + ts_object_method_values(new Object2()) + return true; + }, "true"); + + test_helper.test(() => { + interface Iface { + a:number + } + let a1:Iface = {a:1.0} + ts_object_method(a1) + ts_object_method_getOwnPropertyDescriptor(a1) + ts_object_method_getOwnPropertyDescriptors(a1) + ts_object_method_getOwnPropertyNames(a1) + ts_object_method_hasOwn(a1) + ts_object_method_isExtensible(a1) + ts_object_method_isFrozen(a1) + ts_object_method_isSealed(a1) + ts_object_method_keys(a1) + ts_object_method_keys(a1) + ts_object_method_values(a1) + return true; + }, "true"); + + test_helper.test(() => { + ts_object_method(interObj) + return true; + }, "false"); + + testCaseRet.push(test_helper.done()); +} + +class Reflect2 { + a: string = 'hello' + getName() { return this.a } } -stringType = "test" //should pass +// 5 Object内置方法作用在ArkTS对象 +// 规则名 arkts-interop-ts2s-ts-object-on-static-instance +export function test_ts_reflect_method(testCaseRet: Array) { + let test_helper = new TestHelper("TEST_TS_REFLECT_METHOD"); + test_helper.test(() => { + ts_reflect_method(new Reflect2()) + ts_reflect_method_apply(new Reflect2()) + ts_reflect_method_defineProperty(new Reflect2()) + ts_reflect_method_deleteProperty(new Reflect2()) + ts_reflect_method_getOwnPropertyDescriptor(new Reflect2()) + ts_reflect_method_ownKeys(new Reflect2()) + ts_reflect_method_isExtensible(new Reflect2()) + ts_reflect_method_set(new Reflect2()) + ts_reflect_method_setPrototypeOf(new Reflect2()) + return true; + }, "reflect class 1.2 "); + + test_helper.test(() => { + interface Iface { + a:number + } + let a1:Iface = {a:1.0} + ts_reflect_method(a1) + ts_reflect_method_apply(a1) + ts_reflect_method_defineProperty(a1) + ts_reflect_method_deleteProperty(a1) + ts_reflect_method_getOwnPropertyDescriptor(a1) + ts_reflect_method_ownKeys(a1) + ts_reflect_method_isExtensible(a1) + ts_reflect_method_set(a1) + ts_reflect_method_setPrototypeOf(a1) + return true; + }, "reflect interface 1.2"); + + test_helper.test(() => { + ts_reflect_method(interObj) + ts_reflect_method_apply(interObj) + ts_reflect_method_defineProperty(interObj) + ts_reflect_method_deleteProperty(interObj) + ts_reflect_method_getOwnPropertyDescriptor(interObj) + ts_reflect_method_ownKeys(interObj) + ts_reflect_method_isExtensible(interObj) + ts_reflect_method_set(interObj) + ts_reflect_method_setPrototypeOf(interObj) + return true; + }, "reflect interObj 1.0 "); -enumType = "A"; //should fail + testCaseRet.push(test_helper.done()); +} \ No newline at end of file diff --git a/ets2panda/linter/test/interop/unique_types.ets.migrate.json b/ets2panda/linter/test/interop/unique_types.ets.migrate.json index 6e0fbe1a85..e78688989e 100644 --- a/ets2panda/linter/test/interop/unique_types.ets.migrate.json +++ b/ets2panda/linter/test/interop/unique_types.ets.migrate.json @@ -15,43 +15,473 @@ ], "result": [ { - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 13, - "problem": "InteropTSFunctionInvoke", + "line": 68, + "column": 8, + "endLine": 68, + "endColumn": 15, + "problem": "InteropDirectAccessToTSTypes", "suggest": "", - "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 29, - "column": 1, - "endLine": 29, - "endColumn": 11, + "line": 69, + "column": 8, + "endLine": 69, + "endColumn": 19, "problem": "InteropDirectAccessToTSTypes", "suggest": "", "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 33, - "column": 1, - "endLine": 33, - "endColumn": 20, + "line": 70, + "column": 8, + "endLine": 70, + "endColumn": 18, "problem": "InteropDirectAccessToTSTypes", "suggest": "", "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", "severity": "ERROR" }, { - "line": 33, + "line": 76, + "column": 7, + "endLine": 76, + "endColumn": 69, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 76, + "column": 25, + "endLine": 76, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 80, + "column": 7, + "endLine": 80, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 89, + "column": 7, + "endLine": 89, + "endColumn": 22, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 7, + "endLine": 98, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 107, + "column": 7, + "endLine": 107, + "endColumn": 21, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 116, + "column": 7, + "endLine": 116, + "endColumn": 18, + "problem": "InteropTSFunctionInvoke", + "suggest": "", + "rule": "Trying to catch typescript errors is not permitted (arkts-interop-ts2s-ts-exception)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 7, + "endLine": 158, + "endColumn": 58, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 158, + "column": 25, + "endLine": 158, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 176, "column": 1, - "endLine": 33, - "endColumn": 11, - "problem": "InteropDirectAccessToTSTypes", + "endLine": 176, + "endColumn": 18, + "problem": "DecoratorsNotSupported", "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 181, + "column": 3, + "endLine": 181, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 187, + "column": 3, + "endLine": 187, + "endColumn": 19, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 22, + "endLine": 195, + "endColumn": 41, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 195, + "column": 52, + "endLine": 195, + "endColumn": 55, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 203, + "column": 3, + "endLine": 203, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 215, + "column": 3, + "endLine": 215, + "endColumn": 18, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 226, + "column": 3, + "endLine": 226, + "endColumn": 20, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 231, + "column": 5, + "endLine": 231, + "endColumn": 23, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 237, + "column": 5, + "endLine": 237, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 24, + "endLine": 245, + "endColumn": 43, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 245, + "column": 54, + "endLine": 245, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 256, + "column": 5, + "endLine": 256, + "endColumn": 23, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 271, + "column": 5, + "endLine": 271, + "endColumn": 21, + "problem": "DecoratorsNotSupported", + "suggest": "", + "rule": "Decorators are not supported(arkts-no-ts-decorators)", + "severity": "ERROR" + }, + { + "line": 282, + "column": 7, + "endLine": 282, + "endColumn": 57, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 282, + "column": 25, + "endLine": 282, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 7, + "endLine": 303, + "endColumn": 60, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 303, + "column": 25, + "endLine": 303, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 306, + "column": 26, + "endLine": 306, + "endColumn": 33, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 307, + "column": 51, + "endLine": 307, + "endColumn": 58, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 308, + "column": 52, + "endLine": 308, + "endColumn": 59, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 309, + "column": 46, + "endLine": 309, + "endColumn": 53, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 310, + "column": 33, + "endLine": 310, + "endColumn": 40, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 311, + "column": 39, + "endLine": 311, + "endColumn": 46, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 312, + "column": 35, + "endLine": 312, + "endColumn": 42, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 313, + "column": 35, + "endLine": 313, + "endColumn": 42, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 314, + "column": 31, + "endLine": 314, + "endColumn": 38, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 315, + "column": 31, + "endLine": 315, + "endColumn": 38, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 316, + "column": 33, + "endLine": 316, + "endColumn": 40, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 355, + "column": 7, + "endLine": 355, + "endColumn": 61, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 355, + "column": 25, + "endLine": 355, + "endColumn": 35, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 182, + "column": 3, + "endLine": 182, + "endColumn": 13, + "problem": "StrictDiagnostic", + "suggest": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 202, + "column": 11, + "endLine": 202, + "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": 214, + "column": 11, + "endLine": 214, + "endColumn": 15, + "problem": "StrictDiagnostic", + "suggest": "Property '_age' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property '_age' has no initializer and is not definitely assigned in the constructor.", + "severity": "ERROR" + }, + { + "line": 232, + "column": 5, + "endLine": 232, + "endColumn": 15, + "problem": "StrictDiagnostic", + "suggest": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", + "rule": "Property 'myProperty' has no initializer and is not definitely assigned in the constructor.", "severity": "ERROR" } ] 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 bedac192c9..15853498f4 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 @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n TextAttribute,\n AnimatableExtend,\n Entry,\n Component,\n State,\n Column,\n Text,\n Curve,\n Button,\n} from '@kit.ArkUI';", "line": 31, "column": 7, "endLine": 31, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n TextAttribute,\n AnimatableExtend,\n Entry,\n Component,\n State,\n Column,\n Text,\n Curve,\n Button,\n} from '@kit.ArkUI';", "line": 31, "column": 7, "endLine": 31, @@ -213,7 +213,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n TextAttribute,\n AnimatableExtend,\n Entry,\n Component,\n State,\n Column,\n Text,\n Curve,\n Button,\n} from '@kit.ArkUI';", "line": 31, "column": 7, "endLine": 31, @@ -234,7 +234,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n TextAttribute,\n AnimatableExtend,\n Entry,\n Component,\n State,\n Column,\n Text,\n Curve,\n Button,\n} from '@kit.ArkUI';", "line": 31, "column": 7, "endLine": 31, @@ -255,7 +255,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n TextAttribute,\n AnimatableExtend,\n Entry,\n Component,\n State,\n Column,\n Text,\n Curve,\n Button,\n} from '@kit.ArkUI';", "line": 31, "column": 7, "endLine": 31, @@ -276,7 +276,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n TextAttribute,\n AnimatableExtend,\n Entry,\n Component,\n State,\n Column,\n Text,\n Curve,\n Button,\n} from '@kit.ArkUI';", "line": 31, "column": 7, "endLine": 31, @@ -297,7 +297,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n TextAttribute,\n AnimatableExtend,\n Entry,\n Component,\n State,\n Column,\n Text,\n Curve,\n Button,\n} from '@kit.ArkUI';", "line": 31, "column": 7, "endLine": 31, @@ -318,7 +318,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n TextAttribute,\n AnimatableExtend,\n Entry,\n Component,\n State,\n Column,\n Text,\n Curve,\n Button,\n} from '@kit.ArkUI';", "line": 31, "column": 7, "endLine": 31, 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 index cc98fd6d8d..5404e94034 100644 --- a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.ets @@ -13,7 +13,17 @@ * limitations under the License. */ -import { TextAttribute, AnimatableExtend, Entry, Component, State, Column, Text, Curve, Button } from '@kit.ArkUI'; +import { + TextAttribute, + AnimatableExtend, + 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/animatable_extend_decorator_1.ets.migrate.json b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.json index 32075de8ac..7ed822c159 100644 --- a/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.json +++ b/ets2panda/linter/test/main/animatable_extend_decorator_1.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 20, + "line": 30, "column": 5, - "endLine": 20, + "endLine": 30, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 31, "column": 12, - "endLine": 21, + "endLine": 31, "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 29, "column": 26, - "endLine": 19, + "endLine": 29, "endColumn": 30, "problem": "InvalidIdentifier", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 19, + "line": 29, "column": 63, - "endLine": 19, + "endLine": 29, "endColumn": 67, "problem": "ThisType", "suggest": "", diff --git a/ets2panda/linter/test/main/arkts-array-type-immutable.ets b/ets2panda/linter/test/main/arkts-array-type-immutable.ets index c0d79ba065..8f805d8229 100644 --- a/ets2panda/linter/test/main/arkts-array-type-immutable.ets +++ b/ets2panda/linter/test/main/arkts-array-type-immutable.ets @@ -37,7 +37,7 @@ function test(a: number[]): void { } let arrayTypeImmutableA2: [number] = [1]; -let arrayTypeImmutableB2: [number | string] = arrayTypeImmutableA2; +let arrayTypeImmutableB2: [number | string] = arrayTypeImmutableA2; // error class ArrayTypeImmutableA{ arrayTypeImmutableA: number[] = [1]; @@ -45,8 +45,8 @@ class ArrayTypeImmutableA{ arrayTypeImmutableB1: (number | string)[] = this.arrayTypeImmutableA; // error arrayTypeImmutableA2: [number] = [1]; - arrayTypeImmutableB2: [number | string] = arrayTypeImmutableA2; - arrayTypeImmutableB21: [number | string] = this.arrayTypeImmutableA2; + arrayTypeImmutableB2: [number | string] = arrayTypeImmutableA2; // error + arrayTypeImmutableB21: [number | string] = this.arrayTypeImmutableA2; // error } interface IA { 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 index fa6b50ae6c..e2441885c3 100644 --- a/ets2panda/linter/test/main/arkts-array-type-immutable.ets.arkts2.json +++ b/ets2panda/linter/test/main/arkts-array-type-immutable.ets.arkts2.json @@ -134,6 +134,16 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 40, + "column": 5, + "endLine": 40, + "endColumn": 67, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 43, "column": 36, @@ -174,6 +184,26 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, + { + "line": 48, + "column": 3, + "endLine": 48, + "endColumn": 66, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 3, + "endLine": 49, + "endColumn": 72, + "problem": "ArrayTypeImmutable", + "suggest": "", + "rule": "Array type is immutable in ArkTS1.2 (arkts-array-type-immutable)", + "severity": "ERROR" + }, { "line": 67, "column": 6, diff --git a/ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets b/ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets new file mode 100755 index 0000000000..54a185e6c9 --- /dev/null +++ b/ets2panda/linter/test/main/arkts_promise_need_void_resolve.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 test(): Promise{ + return new Promise((resolve: () => void, reject) => { resolve() }) } \ No newline at end of file diff --git a/ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets.args.json b/ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets.args.json new file mode 100755 index 0000000000..b9d72da174 --- /dev/null +++ b/ets2panda/linter/test/main/arkts_promise_need_void_resolve.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_promise_need_void_resolve.ets.arkts2.json b/ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets.arkts2.json new file mode 100755 index 0000000000..83f403ba1f --- /dev/null +++ b/ets2panda/linter/test/main/arkts_promise_need_void_resolve.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": 17, + "column": 40, + "endLine": 17, + "endColumn": 50, + "problem": "PromiseVoidNeedResolveArg", + "suggest": "", + "rule": "Promiseconstructor only supports using resolve (undefined) (arkts-promise-with-void-type-need-undefined-as-resolve-arg)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets.json b/ets2panda/linter/test/main/arkts_promise_need_void_resolve.ets.json new file mode 100755 index 0000000000..127a98a334 --- /dev/null +++ b/ets2panda/linter/test/main/arkts_promise_need_void_resolve.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/avoid_using_union_types.ets b/ets2panda/linter/test/main/avoid_using_union_types.ets index 4b633916d9..da1290b868 100644 --- a/ets2panda/linter/test/main/avoid_using_union_types.ets +++ b/ets2panda/linter/test/main/avoid_using_union_types.ets @@ -36,4 +36,12 @@ function foo(a: A | B | C) { } let data: Uint8Array = new Uint8Array(); -let reqPb = data.buffer.slice(data.byteOffset, data.byteLength + data.byteOffset); \ No newline at end of file +let reqPb = data.buffer.slice(data.byteOffset, data.byteLength + data.byteOffset); +class D { + tt() {} +} +class E { + tt() {} +} +let ab: D|E = new D(); +ab.tt(); \ No newline at end of file diff --git a/ets2panda/linter/test/main/custom_layout.ets.arkts2.json b/ets2panda/linter/test/main/custom_layout.ets.arkts2.json index afc0270a64..56fe9a2758 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.arkts2.json +++ b/ets2panda/linter/test/main/custom_layout.ets.arkts2.json @@ -111,7 +111,7 @@ "endColumn": 21, "problem": "CustomLayoutNeedAddDecorator", "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "The Custom component \"CustomLayout1\" with custom layout capability needs to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { @@ -181,7 +181,7 @@ "endColumn": 21, "problem": "CustomLayoutNeedAddDecorator", "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "The Custom component \"CustomLayout2\" with custom layout capability needs to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { @@ -271,7 +271,7 @@ "endColumn": 21, "problem": "CustomLayoutNeedAddDecorator", "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "The Custom component \"CustomLayout3\" with custom layout capability needs to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { diff --git a/ets2panda/linter/test/main/custom_layout.ets.autofix.json b/ets2panda/linter/test/main/custom_layout.ets.autofix.json index ac5f81be97..23fd6cb93c 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.autofix.json +++ b/ets2panda/linter/test/main/custom_layout.ets.autofix.json @@ -221,7 +221,7 @@ } ], "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "The Custom component \"CustomLayout1\" with custom layout capability needs to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { @@ -368,7 +368,7 @@ } ], "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "The Custom component \"CustomLayout2\" with custom layout capability needs to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { @@ -557,7 +557,7 @@ } ], "suggest": "", - "rule": "Custom components with custom layout capability need to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", + "rule": "The Custom component \"CustomLayout3\" with custom layout capability needs to add the \"@CustomLayout\" decorator (arkui-custom-layout-need-add-decorator)", "severity": "ERROR" }, { @@ -801,7 +801,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -822,7 +822,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -843,7 +843,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -864,7 +864,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -885,7 +885,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -906,7 +906,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -927,7 +927,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -948,7 +948,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -969,7 +969,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -990,7 +990,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1011,7 +1011,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1032,7 +1032,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1053,7 +1053,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1074,7 +1074,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1095,7 +1095,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1116,7 +1116,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1137,7 +1137,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1158,7 +1158,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1179,7 +1179,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1200,7 +1200,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1221,7 +1221,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1242,7 +1242,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1263,7 +1263,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1284,7 +1284,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1305,7 +1305,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1326,7 +1326,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1347,7 +1347,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1368,7 +1368,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1389,7 +1389,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1410,7 +1410,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1431,7 +1431,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1452,7 +1452,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1473,7 +1473,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1494,7 +1494,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1515,7 +1515,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, @@ -1536,7 +1536,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n Column,\n Builder,\n ForEach,\n Text,\n BuilderParam,\n State,\n SizeResult,\n GeometryInfo,\n Layoutable,\n ConstraintSizeOptions,\n Measurable,\n MeasureResult,\n} from '@kit.ArkUI';", "line": 133, "column": 2, "endLine": 133, diff --git a/ets2panda/linter/test/main/custom_layout.ets.migrate.ets b/ets2panda/linter/test/main/custom_layout.ets.migrate.ets index 5053380e4c..4af3bc0901 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.migrate.ets +++ b/ets2panda/linter/test/main/custom_layout.ets.migrate.ets @@ -15,7 +15,22 @@ import { CustomLayout } from '@kit.ArkUI'; -import { Entry, Component, Column, Builder, ForEach, Text, BuilderParam, State, SizeResult, GeometryInfo, Layoutable, ConstraintSizeOptions, Measurable, MeasureResult } from '@kit.ArkUI'; +import { + Entry, + Component, + Column, + Builder, + ForEach, + Text, + BuilderParam, + State, + SizeResult, + GeometryInfo, + Layoutable, + ConstraintSizeOptions, + Measurable, + MeasureResult, +} from '@kit.ArkUI'; @Entry @Component diff --git a/ets2panda/linter/test/main/custom_layout.ets.migrate.json b/ets2panda/linter/test/main/custom_layout.ets.migrate.json index 21ac1fc70c..05a4428e94 100644 --- a/ets2panda/linter/test/main/custom_layout.ets.migrate.json +++ b/ets2panda/linter/test/main/custom_layout.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 45, + "line": 60, "column": 1, - "endLine": 45, + "endLine": 60, "endColumn": 14, "problem": "DecoratorsNotSupported", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 72, + "line": 87, "column": 1, - "endLine": 72, + "endLine": 87, "endColumn": 14, "problem": "DecoratorsNotSupported", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 103, + "line": 118, "column": 1, - "endLine": 103, + "endLine": 118, "endColumn": 14, "problem": "DecoratorsNotSupported", "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 3987f67867..e75da4ad63 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.autofix.json @@ -108,7 +108,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Link,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 39, "column": 7, "endLine": 39, @@ -129,7 +129,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Link,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 39, "column": 7, "endLine": 39, @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Link,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 39, "column": 7, "endLine": 39, @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Link,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 39, "column": 7, "endLine": 39, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Link,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 39, "column": 7, "endLine": 39, @@ -213,7 +213,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Link,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 39, "column": 7, "endLine": 39, @@ -234,7 +234,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Link,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 39, "column": 7, "endLine": 39, @@ -255,7 +255,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Link, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Link,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 39, "column": 7, "endLine": 39, diff --git a/ets2panda/linter/test/main/dollar_binding_1.ets.migrate.ets b/ets2panda/linter/test/main/dollar_binding_1.ets.migrate.ets index aa775da121..305664a70e 100644 --- a/ets2panda/linter/test/main/dollar_binding_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/dollar_binding_1.ets.migrate.ets @@ -13,7 +13,14 @@ * limitations under the License. */ -import { Component, State, Column, Link, Row, Text } from '@kit.ArkUI'; +import { + Component, + State, + Column, + Link, + Row, + Text, +} from '@kit.ArkUI'; @Component struct MyComponent { 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 b76e000be1..441c4d3b9a 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 @@ -87,7 +87,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -108,7 +108,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -129,7 +129,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -213,7 +213,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -234,7 +234,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -255,7 +255,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, @@ -276,7 +276,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n} from '@kit.ArkUI';", "line": 37, "column": 7, "endLine": 37, 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 index bb6147cf5b..526e8fd4e0 100644 --- a/ets2panda/linter/test/main/double_dollar_binding_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/double_dollar_binding_1.ets.migrate.ets @@ -13,7 +13,16 @@ * limitations under the License. */ -import { Component, State, Row, Slider, $$, Checkbox, Blank, Text } from '@kit.ArkUI'; +import { + Component, + State, + Row, + Slider, + $$, + Checkbox, + Blank, + Text, +} from '@kit.ArkUI'; @Component struct MyComponent { 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 4115b5173b..f70c84d164 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 @@ -255,7 +255,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -276,7 +276,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -297,7 +297,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -318,7 +318,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -339,7 +339,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -360,7 +360,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -381,7 +381,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -402,7 +402,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -423,7 +423,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -444,7 +444,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -465,7 +465,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -486,7 +486,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -507,7 +507,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -528,7 +528,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -549,7 +549,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -570,7 +570,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -591,7 +591,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -612,7 +612,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -633,7 +633,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -654,7 +654,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -675,7 +675,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -696,7 +696,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -717,7 +717,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -738,7 +738,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -759,7 +759,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -780,7 +780,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -801,7 +801,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -822,7 +822,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -843,7 +843,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -864,7 +864,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -885,7 +885,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -906,7 +906,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -927,7 +927,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -948,7 +948,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, @@ -969,7 +969,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Row,\n Slider,\n $$,\n Checkbox,\n Blank,\n Text,\n Entry,\n ComponentV2,\n Local,\n Column,\n Button,\n Param,\n Event,\n} from '@kit.ArkUI';", "line": 107, "column": 7, "endLine": 107, 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 index 6f1805da3f..e95837b57f 100644 --- a/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.ets @@ -13,7 +13,23 @@ * limitations under the License. */ -import { Component, State, Row, Slider, $$, Checkbox, Blank, Text, Entry, ComponentV2, Local, Column, Button, Param, Event } from '@kit.ArkUI'; +import { + Component, + State, + Row, + Slider, + $$, + Checkbox, + Blank, + Text, + Entry, + ComponentV2, + Local, + Column, + Button, + Param, + Event, +} from '@kit.ArkUI'; import { MyCard } from './' 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 index c697fe6484..83e5c37e26 100644 --- a/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.json +++ b/ets2panda/linter/test/main/double_excla_binding_1.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 102, + "line": 118, "column": 15, - "endLine": 102, + "endLine": 118, "endColumn": 20, "problem": "AnyType", "suggest": "", diff --git a/ets2panda/linter/test/main/double_excla_binding_3.ets.autofix.json b/ets2panda/linter/test/main/double_excla_binding_3.ets.autofix.json index 36d4ed4525..7b9fc728ca 100644 --- a/ets2panda/linter/test/main/double_excla_binding_3.ets.autofix.json +++ b/ets2panda/linter/test/main/double_excla_binding_3.ets.autofix.json @@ -24,7 +24,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 29, "column": 7, "endLine": 29, @@ -45,7 +45,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 29, "column": 7, "endLine": 29, @@ -66,7 +66,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 29, "column": 7, "endLine": 29, @@ -87,7 +87,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 29, "column": 7, "endLine": 29, @@ -108,7 +108,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 29, "column": 7, "endLine": 29, @@ -129,7 +129,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 29, "column": 7, "endLine": 29, @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n} from '@kit.ArkUI';", "line": 29, "column": 7, "endLine": 29, diff --git a/ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.ets b/ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.ets index b646a64c49..78c6487540 100644 --- a/ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.ets +++ b/ets2panda/linter/test/main/double_excla_binding_3.ets.migrate.ets @@ -13,7 +13,13 @@ * limitations under the License. */ -import { Entry, Component, State, Row, Text } from '@kit.ArkUI'; +import { + Entry, + Component, + State, + Row, + Text, +} from '@kit.ArkUI'; class User { name: string = "Jack" diff --git a/ets2panda/linter/test/main/dynamic_ctor_call.ets.arkts2.json b/ets2panda/linter/test/main/dynamic_ctor_call.ets.arkts2.json index b4ee74500e..0ef26c352d 100644 --- a/ets2panda/linter/test/main/dynamic_ctor_call.ets.arkts2.json +++ b/ets2panda/linter/test/main/dynamic_ctor_call.ets.arkts2.json @@ -124,16 +124,6 @@ "rule": "Construct signatures are not supported in interfaces (arkts-no-ctor-signatures-iface)", "severity": "ERROR" }, - { - "line": 39, - "column": 14, - "endLine": 39, - "endColumn": 18, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 39, "column": 14, diff --git a/ets2panda/linter/test/main/explicit_function_type.ets b/ets2panda/linter/test/main/explicit_function_type.ets index 9b44052197..c42f90e3fb 100755 --- a/ets2panda/linter/test/main/explicit_function_type.ets +++ b/ets2panda/linter/test/main/explicit_function_type.ets @@ -172,4 +172,9 @@ let ab3 = new AB3(); ab3.fn3(); const fn29: Function[] = []; -fn29[1](); \ No newline at end of file +fn29[1](); + +SysApiWrapper.setTimeout = (handler: Function | string, delay?: number): number => { + (handler as Function)?.(); + return Math.random(); +} \ No newline at end of file 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 54fab7a23c..3427352803 100755 --- a/ets2panda/linter/test/main/explicit_function_type.ets.arkts2.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.arkts2.json @@ -343,6 +343,16 @@ "suggest": "", "rule": "Array bound not checked. (arkts-runtime-array-check)", "severity": "ERROR" + }, + { + "line": 178, + "column": 3, + "endLine": 178, + "endColumn": 24, + "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/main/explicit_function_type.ets.autofix.json b/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json index a9ddde793c..9512b29aac 100644 --- a/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json +++ b/ets2panda/linter/test/main/explicit_function_type.ets.autofix.json @@ -106,9 +106,9 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "fn.unsafeCall", "start": 1572, "end": 1574, + "replacementText": "fn.unsafeCall", "line": 57, "column": 3, "endLine": 57, @@ -374,9 +374,9 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "callback.unsafeCall", "start": 2921, "end": 2929, + "replacementText": "callback.unsafeCall", "line": 139, "column": 3, "endLine": 139, @@ -446,9 +446,9 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "curr.unsafeCall", "start": 3458, "end": 3462, + "replacementText": "curr.unsafeCall", "line": 160, "column": 62, "endLine": 160, @@ -467,9 +467,9 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "prev.unsafeCall", "start": 3463, "end": 3467, + "replacementText": "prev.unsafeCall", "line": 160, "column": 67, "endLine": 160, @@ -488,9 +488,9 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "f1.unsafeCall", "start": 3586, "end": 3588, + "replacementText": "f1.unsafeCall", "line": 166, "column": 1, "endLine": 166, @@ -509,9 +509,9 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "ab3.fn3.unsafeCall", "start": 3656, "end": 3663, + "replacementText": "ab3.fn3.unsafeCall", "line": 172, "column": 1, "endLine": 172, @@ -530,9 +530,9 @@ "problem": "ExplicitFunctionType", "autofix": [ { - "replacementText": "fn29[1].unsafeCall", "start": 3697, "end": 3704, + "replacementText": "fn29[1].unsafeCall", "line": 175, "column": 1, "endLine": 175, @@ -552,6 +552,27 @@ "suggest": "", "rule": "Array bound not checked. (arkts-runtime-array-check)", "severity": "ERROR" + }, + { + "line": 178, + "column": 3, + "endLine": 178, + "endColumn": 24, + "problem": "ExplicitFunctionType", + "autofix": [ + { + "start": 3796, + "end": 3819, + "replacementText": "(handler as Function)?.unsafeCall", + "line": 178, + "column": 3, + "endLine": 178, + "endColumn": 24 + } + ], + "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/main/explicit_function_type.ets.migrate.ets b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets index 7d20e3f229..c5ecffb429 100644 --- a/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets +++ b/ets2panda/linter/test/main/explicit_function_type.ets.migrate.ets @@ -172,4 +172,9 @@ let ab3 = new AB3(); ab3.fn3.unsafeCall(); const fn29: Function[] = []; -fn29[1].unsafeCall(); \ No newline at end of file +fn29[1].unsafeCall(); + +SysApiWrapper.setTimeout = (handler: Function | string, delay?: number): number => { + (handler as Function)?.unsafeCall(); + return Math.random(); +} \ No newline at end of file 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 375b4f7440..ebebb8c78c 100644 --- a/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.autofix.json @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Column,\n Text,\n ColumnAttribute,\n Color,\n} from '@kit.ArkUI';", "line": 35, "column": 20, "endLine": 35, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Column,\n Text,\n ColumnAttribute,\n Color,\n} from '@kit.ArkUI';", "line": 35, "column": 20, "endLine": 35, @@ -213,7 +213,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Column,\n Text,\n ColumnAttribute,\n Color,\n} from '@kit.ArkUI';", "line": 35, "column": 20, "endLine": 35, @@ -234,7 +234,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Column,\n Text,\n ColumnAttribute,\n Color,\n} from '@kit.ArkUI';", "line": 35, "column": 20, "endLine": 35, diff --git a/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.ets b/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.ets index da62cffcb5..319255d85f 100644 --- a/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.ets @@ -13,7 +13,13 @@ * limitations under the License. */ -import { Component, Column, Text, ColumnAttribute, Color } from '@kit.ArkUI'; +import { + Component, + Column, + Text, + ColumnAttribute, + Color, +} from '@kit.ArkUI'; @Component struct MyCard { diff --git a/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.json b/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.json index be60c93486..3844838bf1 100644 --- a/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.json +++ b/ets2panda/linter/test/main/extend_decorator_1.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 31, + "line": 37, "column": 5, - "endLine": 31, + "endLine": 37, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 32, + "line": 38, "column": 5, - "endLine": 32, + "endLine": 38, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 33, + "line": 39, "column": 5, - "endLine": 33, + "endLine": 39, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 40, "column": 5, - "endLine": 34, + "endLine": 40, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 35, + "line": 41, "column": 5, - "endLine": 35, + "endLine": 41, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 42, "column": 5, - "endLine": 36, + "endLine": 42, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 37, + "line": 43, "column": 5, - "endLine": 37, + "endLine": 43, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 38, + "line": 44, "column": 5, - "endLine": 38, + "endLine": 44, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 42, + "line": 48, "column": 12, - "endLine": 42, + "endLine": 48, "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 36, "column": 20, - "endLine": 30, + "endLine": 36, "endColumn": 24, "problem": "InvalidIdentifier", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 36, "column": 44, - "endLine": 30, + "endLine": 36, "endColumn": 48, "problem": "ThisType", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 46, + "line": 52, "column": 5, - "endLine": 46, + "endLine": 52, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 47, + "line": 53, "column": 5, - "endLine": 47, + "endLine": 53, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -145,9 +145,9 @@ "severity": "ERROR" }, { - "line": 48, + "line": 54, "column": 12, - "endLine": 48, + "endLine": 54, "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", @@ -155,9 +155,9 @@ "severity": "ERROR" }, { - "line": 45, + "line": 51, "column": 20, - "endLine": 45, + "endLine": 51, "endColumn": 24, "problem": "InvalidIdentifier", "suggest": "", @@ -165,9 +165,9 @@ "severity": "ERROR" }, { - "line": 45, + "line": 51, "column": 61, - "endLine": 45, + "endLine": 51, "endColumn": 65, "problem": "ThisType", "suggest": "", diff --git a/ets2panda/linter/test/main/func_inferred_type_args_2.ets b/ets2panda/linter/test/main/func_inferred_type_args_2.ets index 0d7b3467d1..5a79d6f480 100644 --- a/ets2panda/linter/test/main/func_inferred_type_args_2.ets +++ b/ets2panda/linter/test/main/func_inferred_type_args_2.ets @@ -94,3 +94,7 @@ class A { } } new A(new C()) +let a: Array | undefined = new Array(); +let aa: Array | Set | undefined = new Array(); +let b: Array | Array | undefined = new Array(); +let test: string[] = new Array(); \ 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 index bc1cd482a4..81e3df826f 100644 --- 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 @@ -254,16 +254,6 @@ "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, - { - "line": 44, - "column": 14, - "endLine": 44, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 44, "column": 10, @@ -274,16 +264,6 @@ "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, - { - "line": 48, - "column": 14, - "endLine": 48, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 48, "column": 10, @@ -304,16 +284,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 52, - "column": 14, - "endLine": 52, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 52, "column": 10, @@ -334,16 +304,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 56, - "column": 14, - "endLine": 56, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 56, "column": 10, @@ -354,16 +314,6 @@ "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, - { - "line": 61, - "column": 16, - "endLine": 61, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 61, "column": 12, @@ -374,16 +324,6 @@ "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, - { - "line": 65, - "column": 16, - "endLine": 65, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 65, "column": 12, @@ -404,16 +344,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 69, - "column": 16, - "endLine": 69, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 69, "column": 12, @@ -434,16 +364,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 73, - "column": 16, - "endLine": 73, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 73, "column": 12, @@ -514,6 +434,46 @@ "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" }, + { + "line": 97, + "column": 36, + "endLine": 97, + "endColumn": 47, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 51, + "endLine": 98, + "endColumn": 62, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 52, + "endLine": 99, + "endColumn": 63, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 100, + "column": 22, + "endLine": 100, + "endColumn": 33, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, { "line": 84, "column": 2, 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 index e59af03e37..202b0cc81c 100644 --- 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 @@ -375,16 +375,6 @@ "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, - { - "line": 44, - "column": 14, - "endLine": 44, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 44, "column": 10, @@ -406,16 +396,6 @@ "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, - { - "line": 48, - "column": 14, - "endLine": 48, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 48, "column": 10, @@ -447,16 +427,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 52, - "column": 14, - "endLine": 52, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 52, "column": 10, @@ -477,16 +447,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 56, - "column": 14, - "endLine": 56, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 56, "column": 10, @@ -497,16 +457,6 @@ "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, - { - "line": 61, - "column": 16, - "endLine": 61, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 61, "column": 12, @@ -528,16 +478,6 @@ "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", "severity": "ERROR" }, - { - "line": 65, - "column": 16, - "endLine": 65, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 65, "column": 12, @@ -569,16 +509,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 69, - "column": 16, - "endLine": 69, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 69, "column": 12, @@ -599,16 +529,6 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, - { - "line": 73, - "column": 16, - "endLine": 73, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 73, "column": 12, @@ -734,6 +654,79 @@ "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" }, + { + "line": 97, + "column": 36, + "endLine": 97, + "endColumn": 47, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 2592, + "end": 2592, + "replacementText": "", + "line": 97, + "column": 36, + "endLine": 97, + "endColumn": 47 + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 51, + "endLine": 98, + "endColumn": 62, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 2655, + "end": 2655, + "replacementText": "", + "line": 98, + "column": 51, + "endLine": 98, + "endColumn": 62 + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 52, + "endLine": 99, + "endColumn": 63, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 100, + "column": 22, + "endLine": 100, + "endColumn": 33, + "problem": "GenericCallNoTypeArgs", + "autofix": [ + { + "start": 2753, + "end": 2753, + "replacementText": "", + "line": 100, + "column": 22, + "endLine": 100, + "endColumn": 33 + } + ], + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, { "line": 84, "column": 2, @@ -744,7 +737,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Track, CommonAttribute } from '@kit.ArkUI';\n", + "replacementText": "\n\nimport {\n Observed,\n Track,\n CommonAttribute,\n} from '@kit.ArkUI';\n", "line": 86, "column": 94, "endLine": 86, @@ -765,7 +758,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Track, CommonAttribute } from '@kit.ArkUI';\n", + "replacementText": "\n\nimport {\n Observed,\n Track,\n CommonAttribute,\n} from '@kit.ArkUI';\n", "line": 86, "column": 94, "endLine": 86, @@ -786,7 +779,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Track, CommonAttribute } from '@kit.ArkUI';\n", + "replacementText": "\n\nimport {\n Observed,\n Track,\n CommonAttribute,\n} from '@kit.ArkUI';\n", "line": 86, "column": 94, "endLine": 86, @@ -807,7 +800,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Observed, Track, CommonAttribute } from '@kit.ArkUI';\n", + "replacementText": "\n\nimport {\n Observed,\n Track,\n CommonAttribute,\n} from '@kit.ArkUI';\n", "line": 86, "column": 94, "endLine": 86, 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 index f76d33da37..bdd57c5703 100644 --- 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 @@ -13,7 +13,11 @@ * limitations under the License. */ -import { Observed, Track, CommonAttribute } from '@kit.ArkUI'; +import { + Observed, + Track, + CommonAttribute, +} from '@kit.ArkUI'; import { AttributeUpdater } from '@kit.ArkUI'; @@ -97,3 +101,7 @@ class A { } } new A(new C()) +let a: Array | undefined = new Array(); +let aa: Array | Set | undefined = new Array(); +let b: Array | Array | undefined = new Array(); +let test: string[] = new Array(); \ No newline at end of file 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 index 7926f03ac9..620729cb92 100644 --- 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 @@ -15,9 +15,9 @@ ], "result": [ { - "line": 20, + "line": 24, "column": 7, - "endLine": 20, + "endLine": 24, "endColumn": 35, "problem": "AnyType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 20, + "line": 24, "column": 24, - "endLine": 20, + "endLine": 24, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 28, "column": 7, - "endLine": 24, + "endLine": 28, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 28, "column": 7, - "endLine": 24, + "endLine": 28, "endColumn": 33, "problem": "AnyType", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 24, + "line": 28, "column": 24, - "endLine": 24, + "endLine": 28, "endColumn": 33, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 33, "column": 3, - "endLine": 29, + "endLine": 33, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 33, "column": 3, - "endLine": 29, + "endLine": 33, "endColumn": 37, "problem": "AnyType", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 33, "column": 27, - "endLine": 29, + "endLine": 33, "endColumn": 36, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 34, "column": 10, - "endLine": 30, + "endLine": 34, "endColumn": 23, "problem": "StructuralIdentity", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 30, + "line": 34, "column": 39, - "endLine": 30, + "endLine": 34, "endColumn": 48, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 40, "column": 7, - "endLine": 36, + "endLine": 40, "endColumn": 35, "problem": "UnknownType", "suggest": "", @@ -125,9 +125,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 40, "column": 22, - "endLine": 36, + "endLine": 40, "endColumn": 35, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 39, + "line": 43, "column": 30, - "endLine": 39, + "endLine": 43, "endColumn": 39, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -145,29 +145,9 @@ "severity": "ERROR" }, { - "line": 47, - "column": 14, - "endLine": 47, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 51, - "column": 14, - "endLine": 51, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 55, + "line": 59, "column": 10, - "endLine": 55, + "endLine": 59, "endColumn": 19, "problem": "StructuralIdentity", "suggest": "", @@ -175,19 +155,9 @@ "severity": "ERROR" }, { - "line": 55, - "column": 14, - "endLine": 55, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 55, + "line": 59, "column": 10, - "endLine": 55, + "endLine": 59, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -195,9 +165,9 @@ "severity": "ERROR" }, { - "line": 59, + "line": 63, "column": 10, - "endLine": 59, + "endLine": 63, "endColumn": 19, "problem": "StructuralIdentity", "suggest": "", @@ -205,19 +175,9 @@ "severity": "ERROR" }, { - "line": 59, - "column": 14, - "endLine": 59, - "endColumn": 17, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 59, + "line": 63, "column": 10, - "endLine": 59, + "endLine": 63, "endColumn": 19, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -225,29 +185,9 @@ "severity": "ERROR" }, { - "line": 64, - "column": 16, - "endLine": 64, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 68, - "column": 16, - "endLine": 68, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 72, + "line": 76, "column": 12, - "endLine": 72, + "endLine": 76, "endColumn": 21, "problem": "StructuralIdentity", "suggest": "", @@ -255,19 +195,9 @@ "severity": "ERROR" }, { - "line": 72, - "column": 16, - "endLine": 72, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 72, + "line": 76, "column": 12, - "endLine": 72, + "endLine": 76, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -275,9 +205,9 @@ "severity": "ERROR" }, { - "line": 76, + "line": 80, "column": 12, - "endLine": 76, + "endLine": 80, "endColumn": 21, "problem": "StructuralIdentity", "suggest": "", @@ -285,19 +215,9 @@ "severity": "ERROR" }, { - "line": 76, - "column": 16, - "endLine": 76, - "endColumn": 19, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 76, + "line": 80, "column": 12, - "endLine": 76, + "endLine": 80, "endColumn": 21, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -305,14 +225,24 @@ "severity": "ERROR" }, { - "line": 89, + "line": 93, "column": 77, - "endLine": 89, + "endLine": 93, "endColumn": 93, "problem": "DynamicCtorCall", "suggest": "", "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", "severity": "ERROR" + }, + { + "line": 106, + "column": 52, + "endLine": 106, + "endColumn": 63, + "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/index_access_static_and_class_instance.ets b/ets2panda/linter/test/main/index_access_static_and_class_instance.ets new file mode 100644 index 0000000000..942125e00d --- /dev/null +++ b/ets2panda/linter/test/main/index_access_static_and_class_instance.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. + */ + +class A { + static foo1(){} + foo2(){} +} + +let a = new A(); +(a as object)["foo2"]; //arkts-no-ops-by-index autofix is right + +(A as object)["foo1"]; // arkts-no-classes-as-obj autofix is right diff --git a/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.args.json b/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.args.json new file mode 100755 index 0000000000..6958168fef --- /dev/null +++ b/ets2panda/linter/test/main/index_access_static_and_class_instance.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/index_access_static_and_class_instance.ets.arkts2.json b/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.arkts2.json new file mode 100644 index 0000000000..21e2ed90d0 --- /dev/null +++ b/ets2panda/linter/test/main/index_access_static_and_class_instance.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": 22, + "column": 1, + "endLine": 22, + "endColumn": 22, + "problem": "PropertyAccessByIndex", + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 2, + "endLine": 24, + "endColumn": 3, + "problem": "ClassAsObjectError", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.autofix.json b/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.autofix.json new file mode 100644 index 0000000000..827a118edf --- /dev/null +++ b/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.autofix.json @@ -0,0 +1,60 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 1, + "endLine": 22, + "endColumn": 22, + "problem": "PropertyAccessByIndex", + "autofix": [ + { + "replacementText": "a.foo2", + "start": 664, + "end": 685, + "line": 22, + "column": 1, + "endLine": 22, + "endColumn": 22 + } + ], + "suggest": "", + "rule": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 2, + "endLine": 24, + "endColumn": 3, + "problem": "ClassAsObjectError", + "autofix": [ + { + "replacementText": "A.foo1", + "start": 729, + "end": 750, + "line": 24, + "column": 2, + "endLine": 24, + "endColumn": 3 + } + ], + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.json b/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.json new file mode 100644 index 0000000000..9493d7285d --- /dev/null +++ b/ets2panda/linter/test/main/index_access_static_and_class_instance.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": 2, + "endLine": 24, + "endColumn": 3, + "problem": "ClassAsObject", + "suggest": "", + "rule": "Classes cannot be used as objects (arkts-no-classes-as-obj)", + "severity": "WARNING" + } + ] +} diff --git a/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.migrate.ets b/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.migrate.ets new file mode 100644 index 0000000000..eb80664946 --- /dev/null +++ b/ets2panda/linter/test/main/index_access_static_and_class_instance.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. + */ + +class A { + static foo1(){} + foo2(){} +} + +let a = new A(); +a.foo2; //arkts-no-ops-by-index autofix is right + +A.foo1; // arkts-no-classes-as-obj autofix is right diff --git a/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.migrate.json b/ets2panda/linter/test/main/index_access_static_and_class_instance.ets.migrate.json new file mode 100644 index 0000000000..dd03fcf544 --- /dev/null +++ b/ets2panda/linter/test/main/index_access_static_and_class_instance.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/interface_import_1.ets.autofix.json b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json index 3379f754c7..88bab00625 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.autofix.json @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -213,7 +213,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -234,7 +234,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -255,7 +255,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -276,7 +276,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -297,7 +297,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -318,7 +318,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -339,7 +339,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -360,7 +360,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -381,7 +381,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -402,7 +402,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -423,7 +423,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, @@ -444,7 +444,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Column, Button, Text, Row, TextAttribute, ColumnAttribute, AnimatableExtend, $$, ImageFit } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Column,\n Button,\n Text,\n Row,\n TextAttribute,\n ColumnAttribute,\n AnimatableExtend,\n $$,\n ImageFit,\n} from '@kit.ArkUI';", "line": 86, "column": 36, "endLine": 86, diff --git a/ets2panda/linter/test/main/interface_import_1.ets.migrate.ets b/ets2panda/linter/test/main/interface_import_1.ets.migrate.ets index 97155fd1a2..5c0cf73eaa 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/interface_import_1.ets.migrate.ets @@ -13,7 +13,20 @@ * limitations under the License. */ -import { Entry, Component, State, 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'; diff --git a/ets2panda/linter/test/main/interface_import_1.ets.migrate.json b/ets2panda/linter/test/main/interface_import_1.ets.migrate.json index 400a3c7033..8ca1591553 100644 --- a/ets2panda/linter/test/main/interface_import_1.ets.migrate.json +++ b/ets2panda/linter/test/main/interface_import_1.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 63, + "line": 76, "column": 5, - "endLine": 63, + "endLine": 76, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 64, + "line": 77, "column": 12, - "endLine": 64, + "endLine": 77, "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 62, + "line": 75, "column": 20, - "endLine": 62, + "endLine": 75, "endColumn": 24, "problem": "InvalidIdentifier", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 62, + "line": 75, "column": 42, - "endLine": 62, + "endLine": 75, "endColumn": 46, "problem": "ThisType", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 69, + "line": 82, "column": 5, - "endLine": 69, + "endLine": 82, "endColumn": 9, "problem": "FunctionContainsThis", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 70, + "line": 83, "column": 12, - "endLine": 70, + "endLine": 83, "endColumn": 16, "problem": "FunctionContainsThis", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 68, + "line": 81, "column": 26, - "endLine": 68, + "endLine": 81, "endColumn": 30, "problem": "InvalidIdentifier", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 68, + "line": 81, "column": 65, - "endLine": 68, + "endLine": 81, "endColumn": 69, "problem": "ThisType", "suggest": "", diff --git a/ets2panda/linter/test/main/interface_import_3.ets.autofix.json b/ets2panda/linter/test/main/interface_import_3.ets.autofix.json index a149f61d6c..be5fa2b029 100644 --- a/ets2panda/linter/test/main/interface_import_3.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_3.ets.autofix.json @@ -44,7 +44,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n} from '@kit.ArkUI';", "line": 30, "column": 2, "endLine": 30, @@ -65,7 +65,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n} from '@kit.ArkUI';", "line": 30, "column": 2, "endLine": 30, diff --git a/ets2panda/linter/test/main/interface_import_3.ets.migrate.ets b/ets2panda/linter/test/main/interface_import_3.ets.migrate.ets index 437303702c..52825b0256 100644 --- a/ets2panda/linter/test/main/interface_import_3.ets.migrate.ets +++ b/ets2panda/linter/test/main/interface_import_3.ets.migrate.ets @@ -13,7 +13,10 @@ * limitations under the License. */ -import { Entry, Component } from '@kit.ArkUI'; +import { + Entry, + Component, +} from '@kit.ArkUI'; import { A } from './har' diff --git a/ets2panda/linter/test/main/interface_import_3.ets.migrate.json b/ets2panda/linter/test/main/interface_import_3.ets.migrate.json index 97261a31be..89fb6cd577 100644 --- a/ets2panda/linter/test/main/interface_import_3.ets.migrate.json +++ b/ets2panda/linter/test/main/interface_import_3.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 24, + "line": 27, "column": 16, - "endLine": 24, + "endLine": 27, "endColumn": 17, "problem": "DynamicCtorCall", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 27, + "line": 30, "column": 5, - "endLine": 27, + "endLine": 30, "endColumn": 12, "problem": "AnyType", "suggest": "", diff --git a/ets2panda/linter/test/main/interface_import_4.ets.autofix.json b/ets2panda/linter/test/main/interface_import_4.ets.autofix.json index 1ba9932fa3..2699ed7651 100644 --- a/ets2panda/linter/test/main/interface_import_4.ets.autofix.json +++ b/ets2panda/linter/test/main/interface_import_4.ets.autofix.json @@ -223,7 +223,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -244,7 +244,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -265,7 +265,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -286,7 +286,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -307,7 +307,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -328,7 +328,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -349,7 +349,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -370,7 +370,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -391,7 +391,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -412,7 +412,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -433,7 +433,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -454,7 +454,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, @@ -475,7 +475,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n ComponentV2,\n Local,\n Scroller,\n Column,\n List,\n Repeat,\n RepeatItem,\n ListItem,\n Row,\n Text,\n Button,\n} from '@kit.ArkUI';", "line": 40, "column": 7, "endLine": 40, diff --git a/ets2panda/linter/test/main/interface_import_4.ets.migrate.ets b/ets2panda/linter/test/main/interface_import_4.ets.migrate.ets index 0087934e5c..a14500081a 100644 --- a/ets2panda/linter/test/main/interface_import_4.ets.migrate.ets +++ b/ets2panda/linter/test/main/interface_import_4.ets.migrate.ets @@ -13,7 +13,20 @@ * limitations under the License. */ -import { Entry, ComponentV2, Local, Scroller, Column, List, Repeat, RepeatItem, ListItem, Row, Text, Button } from '@kit.ArkUI'; +import { + Entry, + ComponentV2, + Local, + Scroller, + Column, + List, + Repeat, + RepeatItem, + ListItem, + Row, + Text, + Button, +} from '@kit.ArkUI'; @Entry @ComponentV2 diff --git a/ets2panda/linter/test/main/interface_import_4.ets.migrate.json b/ets2panda/linter/test/main/interface_import_4.ets.migrate.json index 1aecbf6f53..eef4db12d7 100644 --- a/ets2panda/linter/test/main/interface_import_4.ets.migrate.json +++ b/ets2panda/linter/test/main/interface_import_4.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 22, + "line": 35, "column": 28, - "endLine": 22, + "endLine": 35, "endColumn": 36, "problem": "DynamicCtorCall", "suggest": "", 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 f6d45915a0..5062fc598a 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.arkts2.json @@ -274,16 +274,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 84, - "column": 12, - "endLine": 84, - "endColumn": 31, - "problem": "InteropDirectAccessToTSTypes", - "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", - "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 c006698019..f3414d739d 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 @@ -656,16 +656,6 @@ "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" }, - { - "line": 84, - "column": 12, - "endLine": 84, - "endColumn": 31, - "problem": "InteropDirectAccessToTSTypes", - "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", - "severity": "ERROR" - }, { "line": 84, "column": 36, @@ -1483,7 +1473,7 @@ { "start": 608, "end": 608, - "replacementText": "\n\nimport { Component, State } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n} from '@kit.ArkUI';", "line": 117, "column": 2, "endLine": 117, @@ -1504,7 +1494,7 @@ { "start": 608, "end": 608, - "replacementText": "\n\nimport { Component, State } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n} from '@kit.ArkUI';", "line": 117, "column": 2, "endLine": 117, diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets index 5c91b9deba..6fb5cb3e0f 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.ets @@ -13,7 +13,10 @@ * limitations under the License. */ -import { Component, State } from '@kit.ArkUI'; +import { + Component, + State, +} from '@kit.ArkUI'; import { ExportLitAsPropName } from './ignore_files/good'; diff --git a/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json index 2597882d05..a180c18573 100644 --- a/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.json +++ b/ets2panda/linter/test/main/literals_as_prop_names.ets.migrate.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,9 +15,9 @@ ], "result": [ { - "line": 59, + "line": 62, "column": 9, - "endLine": 59, + "endLine": 62, "endColumn": 10, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 59, + "line": 62, "column": 10, - "endLine": 59, + "endLine": 62, "endColumn": 16, "problem": "LiteralAsPropertyName", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 59, + "line": 62, "column": 24, - "endLine": 59, + "endLine": 62, "endColumn": 25, "problem": "LiteralAsPropertyName", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 61, + "line": 64, "column": 13, - "endLine": 61, + "endLine": 64, "endColumn": 22, "problem": "PropertyAccessByIndex", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 62, + "line": 65, "column": 13, - "endLine": 62, + "endLine": 65, "endColumn": 17, "problem": "PropertyAccessByIndex", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 84, + "line": 87, "column": 7, - "endLine": 84, + "endLine": 87, "endColumn": 10, "problem": "InvalidIdentifier", "suggest": "", @@ -75,19 +75,9 @@ "severity": "ERROR" }, { - "line": 90, - "column": 12, - "endLine": 90, - "endColumn": 31, - "problem": "InteropDirectAccessToTSTypes", - "suggest": "", - "rule": "Cannot access typescript types directly (arkts-interop-ts2s-static-access-ts-type)", - "severity": "ERROR" - }, - { - "line": 90, + "line": 93, "column": 36, - "endLine": 90, + "endLine": 93, "endColumn": 37, "problem": "LiteralAsPropertyName", "suggest": "", @@ -95,9 +85,9 @@ "severity": "ERROR" }, { - "line": 92, + "line": 95, "column": 1, - "endLine": 92, + "endLine": 95, "endColumn": 33, "problem": "UnsupportPropNameFromValue", "suggest": "", @@ -105,9 +95,9 @@ "severity": "ERROR" }, { - "line": 141, + "line": 144, "column": 37, - "endLine": 141, + "endLine": 144, "endColumn": 38, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -115,9 +105,9 @@ "severity": "ERROR" }, { - "line": 142, + "line": 145, "column": 3, - "endLine": 142, + "endLine": 145, "endColumn": 12, "problem": "ComputedPropertyName", "suggest": "", @@ -125,9 +115,9 @@ "severity": "ERROR" }, { - "line": 147, + "line": 150, "column": 3, - "endLine": 147, + "endLine": 150, "endColumn": 15, "problem": "ComputedPropertyName", "suggest": "", @@ -135,9 +125,9 @@ "severity": "ERROR" }, { - "line": 148, + "line": 151, "column": 3, - "endLine": 148, + "endLine": 151, "endColumn": 8, "problem": "ComputedPropertyName", "suggest": "", @@ -145,9 +135,9 @@ "severity": "ERROR" }, { - "line": 149, + "line": 152, "column": 3, - "endLine": 149, + "endLine": 152, "endColumn": 34, "problem": "ComputedPropertyName", "suggest": "", @@ -155,9 +145,9 @@ "severity": "ERROR" }, { - "line": 152, + "line": 155, "column": 19, - "endLine": 152, + "endLine": 155, "endColumn": 20, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -165,9 +155,9 @@ "severity": "ERROR" }, { - "line": 153, + "line": 156, "column": 3, - "endLine": 153, + "endLine": 156, "endColumn": 15, "problem": "ComputedPropertyName", "suggest": "", @@ -175,9 +165,9 @@ "severity": "ERROR" }, { - "line": 154, + "line": 157, "column": 3, - "endLine": 154, + "endLine": 157, "endColumn": 8, "problem": "ComputedPropertyName", "suggest": "", @@ -185,9 +175,9 @@ "severity": "ERROR" }, { - "line": 155, + "line": 158, "column": 3, - "endLine": 155, + "endLine": 158, "endColumn": 34, "problem": "ComputedPropertyName", "suggest": "", @@ -195,9 +185,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 31, "column": 11, - "endLine": 28, + "endLine": 31, "endColumn": 14, "problem": "StrictDiagnostic", "suggest": "Property '__2' has no initializer and is not definitely assigned in the constructor.", @@ -205,9 +195,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 32, "column": 3, - "endLine": 29, + "endLine": 32, "endColumn": 6, "problem": "StrictDiagnostic", "suggest": "Property 'Two' has no initializer and is not definitely assigned in the constructor.", @@ -215,9 +205,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 47, "column": 11, - "endLine": 44, + "endLine": 47, "endColumn": 13, "problem": "StrictDiagnostic", "suggest": "Property '_2' has no initializer and is not definitely assigned in the constructor.", @@ -225,9 +215,9 @@ "severity": "ERROR" }, { - "line": 45, + "line": 48, "column": 3, - "endLine": 45, + "endLine": 48, "endColumn": 6, "problem": "StrictDiagnostic", "suggest": "Property 'Two' has no initializer and is not definitely assigned in the constructor.", @@ -235,9 +225,9 @@ "severity": "ERROR" }, { - "line": 65, + "line": 68, "column": 12, - "endLine": 65, + "endLine": 68, "endColumn": 16, "problem": "StrictDiagnostic", "suggest": "Property 'name' has no initializer and is not definitely assigned in the constructor.", @@ -245,9 +235,9 @@ "severity": "ERROR" }, { - "line": 66, + "line": 69, "column": 12, - "endLine": 66, + "endLine": 69, "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.autofix.json b/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json index 70cdea3625..2c776ac2ff 100644 --- a/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json +++ b/ets2panda/linter/test/main/localBuilder_1.ets.autofix.json @@ -45,7 +45,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n Column,\n} from '@kit.ArkUI';", "line": 29, "column": 5, "endLine": 29, @@ -66,7 +66,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n Column,\n} from '@kit.ArkUI';", "line": 29, "column": 5, "endLine": 29, @@ -87,7 +87,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n Column,\n} from '@kit.ArkUI';", "line": 29, "column": 5, "endLine": 29, @@ -108,7 +108,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n Column,\n} from '@kit.ArkUI';", "line": 29, "column": 5, "endLine": 29, @@ -129,7 +129,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n Column,\n} from '@kit.ArkUI';", "line": 29, "column": 5, "endLine": 29, @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n State,\n Row,\n Text,\n Column,\n} from '@kit.ArkUI';", "line": 29, "column": 5, "endLine": 29, diff --git a/ets2panda/linter/test/main/localBuilder_1.ets.migrate.ets b/ets2panda/linter/test/main/localBuilder_1.ets.migrate.ets index d9a2b55ebe..d3f6980a06 100644 --- a/ets2panda/linter/test/main/localBuilder_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/localBuilder_1.ets.migrate.ets @@ -15,7 +15,14 @@ import { Builder } from '@kit.ArkUI'; -import { Entry, Component, State, Row, Text, Column } from '@kit.ArkUI'; +import { + Entry, + Component, + State, + Row, + Text, + Column, +} from '@kit.ArkUI'; @Entry @Component diff --git a/ets2panda/linter/test/main/method_inheritance.ets b/ets2panda/linter/test/main/method_inheritance.ets index c92fa1f0d9..276a7c3aee 100644 --- a/ets2panda/linter/test/main/method_inheritance.ets +++ b/ets2panda/linter/test/main/method_inheritance.ets @@ -216,3 +216,39 @@ class Derived4 implements Base3 { return new A1(); } } + +class P { +} + +class PP extends P { + public static toString(result: number): string { // Legal + return ''; + } +} + +class RCP {} + +interface aa { + aa?: Function; +} +interface bb extends aa { + onError(res: RCP): void; +} +class CC implements bb { + onError(res: RCP): void {} // Legal + aa?: Function = () => {} +} +class Animal {} +class Dog extends Animal {} + +class Base6 { + public foo(): Animal { + console.log("base") + } +} +// extends +class Derived6 extends Base6 { + public foo(): Dog { // no error + console.log("Derived:") + } +} \ 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 index a543274d46..eb1ba59ca1 100644 --- a/ets2panda/linter/test/main/no_sparse_array.ets +++ b/ets2panda/linter/test/main/no_sparse_array.ets @@ -15,4 +15,28 @@ let a = [1, , , 3]; let b = []; -let c:number[] = []; \ No newline at end of file +let c: number[] = []; + +let d = Promise.race([]); +let e = Promise.all([]); +let f = Promise.allSettled([]); +let g = Promise.any([]); +let h = Promise.resolve([]); + +let d1 = Promise.race([]); +let e1 = Promise.all([]); +let f1 = Promise.allSettled([]); +let g1 = Promise.any([]); +let h1 = Promise.resolve([]); + +let i = Promise.race([1.0]); +let j = Promise.all([2.0]); +let k = Promise.allSettled([3.0]); +let l = Promise.any([4.0]); +let m = Promise.resolve([5.0]); + +let i1 = Promise.race([1]); +let j1 = Promise.all([2]); +let k1 = Promise.allSettled([3]); +let l1 = Promise.any([4]); +let m1 = Promise.resolve([5]); \ 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 index edf83e80e8..103a56a139 100644 --- a/ets2panda/linter/test/main/no_sparse_array.ets.arkts2.json +++ b/ets2panda/linter/test/main/no_sparse_array.ets.arkts2.json @@ -63,6 +63,156 @@ "suggest": "", "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", "severity": "ERROR" + }, + { + "line": 20, + "column": 30, + "endLine": 20, + "endColumn": 32, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 21, + "column": 29, + "endLine": 21, + "endColumn": 31, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 36, + "endLine": 22, + "endColumn": 38, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 23, + "column": 29, + "endLine": 23, + "endColumn": 31, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 35, + "endLine": 24, + "endColumn": 37, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 23, + "endLine": 26, + "endColumn": 25, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 27, + "column": 22, + "endLine": 27, + "endColumn": 24, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 29, + "endLine": 28, + "endColumn": 31, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 29, + "column": 22, + "endLine": 29, + "endColumn": 24, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 30, + "column": 26, + "endLine": 30, + "endColumn": 28, + "problem": "NosparseArray", + "suggest": "", + "rule": "Sparse array is not supported in ArkTS1.2 (arkts-no-sparse-array)", + "severity": "ERROR" + }, + { + "line": 38, + "column": 24, + "endLine": 38, + "endColumn": 25, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 23, + "endLine": 39, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 40, + "column": 30, + "endLine": 40, + "endColumn": 31, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 41, + "column": 23, + "endLine": 41, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 42, + "column": 27, + "endLine": 42, + "endColumn": 28, + "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/main/no_ts_like_smart_type.ets b/ets2panda/linter/test/main/no_ts_like_smart_type.ets index 65ad923c30..7a82e0fd5e 100755 --- a/ets2panda/linter/test/main/no_ts_like_smart_type.ets +++ b/ets2panda/linter/test/main/no_ts_like_smart_type.ets @@ -61,4 +61,61 @@ class AA3 { } return this.instance; // Error } +} + +function foo2(str:string){ +} +function foo22(str:number|string){ +} +function foo(spec :string|number){ + foo2(spec) // Error +} +function foo3(spec :string|number){ + if (typeof spec == "string") { + foo2(spec) // Error + } +} +function foo3(spec :string|number){ + if (typeof spec == "string") { + foo22(spec) + } +} + +const input = true; +if (typeof input === 'boolean') { +} else { + let result = input as string | number | null; // Error +} + +async function taskInfo():Promise {//nopass + for (let i:int = 0; i < 1000; i++) { + let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo(); + hilog.info(0x0000, 'testTag-----',`getTaskPoolInfo: , ${JSON.stringify(taskpoolInfo)}`) + let tid: number = 0; + let taskIds: number[] = []; + let priority: int = 0; + let taskId: number = 0; + let state: number = 0; + let duration: number = 0; + let name: string = ""; + let threadIS: Array = Array.from(taskpoolInfo.threadInfos) + for (let threadInfo of threadIS) { + tid = threadInfo.tid; + if (threadInfo.taskIds != undefined && threadInfo.priority != undefined) { + priority = threadInfo.priority; // Error + } + hilog.info(0x0000, 'testTag-----',"getTaskPoolInfo: --tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority); + } + let taskIS: Array = Array.from(taskpoolInfo.taskInfos) + for (let taskInfo of taskIS) { + taskId = taskInfo.taskId; + state = taskInfo.state; + if (taskInfo.duration != undefined) { + duration = taskInfo.duration as number; // Error + name = taskInfo.name; + } + hilog.info(0x0000, 'testTag-----',"getTaskPoolInfo: --taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration + + ", name is:" + name); + } + } } \ No newline at end of file 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 index d8dd2482a1..679e8a5d6f 100755 --- 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 @@ -103,6 +103,146 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 71, + "column": 8, + "endLine": 71, + "endColumn": 12, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 73, + "column": 1, + "endLine": 77, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 75, + "column": 10, + "endLine": 75, + "endColumn": 14, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 78, + "column": 1, + "endLine": 82, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 87, + "column": 16, + "endLine": 87, + "endColumn": 47, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 20, + "endLine": 91, + "endColumn": 21, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 91, + "column": 27, + "endLine": 91, + "endColumn": 31, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 94, + "column": 23, + "endLine": 94, + "endColumn": 24, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 96, + "column": 25, + "endLine": 96, + "endColumn": 26, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 97, + "column": 26, + "endLine": 97, + "endColumn": 27, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 98, + "column": 25, + "endLine": 98, + "endColumn": 26, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 99, + "column": 28, + "endLine": 99, + "endColumn": 29, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 105, + "column": 8, + "endLine": 105, + "endColumn": 38, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 114, + "column": 9, + "endLine": 114, + "endColumn": 47, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "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 2c6c4de6cf..58a67b8a66 100644 --- a/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.autofix.json @@ -2464,7 +2464,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, @@ -2485,7 +2485,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, @@ -2506,7 +2506,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, @@ -2527,7 +2527,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, @@ -2548,7 +2548,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, @@ -2569,7 +2569,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, @@ -2590,7 +2590,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, @@ -2611,7 +2611,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, @@ -2632,7 +2632,7 @@ { "start": 738, "end": 738, - "replacementText": "\r\n\r\nimport { Entry, Component, State, RelativeContainer, Text, AppStorage } from '@kit.ArkUI';\r\n", + "replacementText": "\r\n\r\nimport {\n Entry,\n Component,\n State,\n RelativeContainer,\n Text,\n AppStorage,\n} from '@kit.ArkUI';\r\n", "line": 155, "column": 34, "endLine": 155, diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets index ba4df96e9d..1013980b65 100644 --- a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets +++ b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.ets @@ -16,7 +16,14 @@ // 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'; +import { + Entry, + Component, + State, + RelativeContainer, + Text, + AppStorage, +} from '@kit.ArkUI'; let a: number = 1.0; diff --git a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json index 665c1dea05..29adb27a5c 100644 --- a/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json +++ b/ets2panda/linter/test/main/numeric_semantics.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 60, + "line": 67, "column": 5, - "endLine": 60, + "endLine": 67, "endColumn": 15, "problem": "DefiniteAssignmentError", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 110, + "line": 117, "column": 26, - "endLine": 110, + "endLine": 117, "endColumn": 26, "problem": "ArrayIndexExprType", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 149, + "line": 156, "column": 6, - "endLine": 149, + "endLine": 156, "endColumn": 7, "problem": "ObjectLiteralNoContextType", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 155, + "line": 162, "column": 9, - "endLine": 155, + "endLine": 162, "endColumn": 20, "problem": "ObjectLiteralProperty", "suggest": "", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 155, + "line": 162, "column": 9, - "endLine": 155, + "endLine": 162, "endColumn": 11, "problem": "InvalidIdentifier", "suggest": "", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 155, + "line": 162, "column": 12, - "endLine": 155, + "endLine": 162, "endColumn": 15, "problem": "AnyType", "suggest": "", @@ -75,9 +75,9 @@ "severity": "ERROR" }, { - "line": 189, + "line": 196, "column": 6, - "endLine": 189, + "endLine": 196, "endColumn": 13, "problem": "RuntimeArrayCheck", "suggest": "", @@ -85,9 +85,9 @@ "severity": "ERROR" }, { - "line": 203, + "line": 210, "column": 1, - "endLine": 203, + "endLine": 210, "endColumn": 40, "problem": "ImportAfterStatement", "suggest": "", @@ -95,9 +95,9 @@ "severity": "ERROR" }, { - "line": 205, + "line": 212, "column": 5, - "endLine": 205, + "endLine": 212, "endColumn": 34, "problem": "AnyType", "suggest": "", @@ -105,9 +105,9 @@ "severity": "ERROR" }, { - "line": 205, + "line": 212, "column": 15, - "endLine": 205, + "endLine": 212, "endColumn": 24, "problem": "DynamicCtorCall", "suggest": "", @@ -115,9 +115,9 @@ "severity": "ERROR" }, { - "line": 211, + "line": 218, "column": 42, - "endLine": 211, + "endLine": 218, "endColumn": 51, "problem": "DynamicCtorCall", "suggest": "", diff --git a/ets2panda/linter/test/main/object_literals_properties.ets b/ets2panda/linter/test/main/object_literals_properties.ets index 84c1d5db86..1944ed2ef9 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets +++ b/ets2panda/linter/test/main/object_literals_properties.ets @@ -264,22 +264,34 @@ namespace X { console.log("C - 1"); } } - + export interface I { m(a: number, b: string): void; } } - + function test() { let c: X.C = { m() { console.log("C - 2"); } } - + let i: X.I = { m(): void { console.log("I"); } } -} \ No newline at end of file +} + +class FooBarBaz { + foo?: Map + bar?: string +} + +function baz(fooBar: Map) { + baz2({fooBar}); +} + +function baz2(fooBarBaz: FooBarBaz) { +} 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 f9fc1047e8..0b296788ca 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.args.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.args.json @@ -1,21 +1,21 @@ { - "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." - ], - "mode": { - "arkts2": "", - "autofix": "--arkts-2", - "migrate": "--arkts-2" - } + "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." + ], + "mode": { + "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 4f42a0f593..b72ff900ba 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.arkts2.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.arkts2.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", @@ -1345,4 +1345,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json b/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json index 04eed5c407..ccf6076bdc 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.autofix.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 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", @@ -2326,8 +2326,8 @@ "problem": "ObjectLiteralProperty", "autofix": [ { - "start": 4958, - "end": 4958, + "start": 4956, + "end": 4956, "replacementText": "class GeneratedObjectLiteralClass_11 extends X.C {\n m() {\n console.log(\"C - 2\");\n }\n}\n\n", "line": 275, "column": 5, @@ -2335,8 +2335,8 @@ "endColumn": 6 }, { - "start": 4991, - "end": 5040, + "start": 4989, + "end": 5038, "replacementText": "new GeneratedObjectLiteralClass_11()", "line": 275, "column": 5, @@ -2366,8 +2366,8 @@ "problem": "ObjectLiteralProperty", "autofix": [ { - "start": 4958, - "end": 4958, + "start": 4956, + "end": 4956, "replacementText": "class GeneratedObjectLiteralClass_12 implements X.I {\n m(): void {\n console.log(\"I\");\n }\n}\n\n", "line": 281, "column": 5, @@ -2375,8 +2375,8 @@ "endColumn": 6 }, { - "start": 5058, - "end": 5109, + "start": 5055, + "end": 5106, "replacementText": "new GeneratedObjectLiteralClass_12()", "line": 281, "column": 5, @@ -2399,4 +2399,4 @@ "severity": "ERROR" } ] -} \ No newline at end of file +} diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets index c2c2429650..ef4628d62a 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets +++ b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.ets @@ -326,12 +326,12 @@ namespace X { console.log("C - 1"); } } - + export interface I { m(a: number, b: string): void; } } - + class GeneratedObjectLiteralClass_11 extends X.C { m() { console.log("C - 2"); @@ -346,6 +346,18 @@ class GeneratedObjectLiteralClass_12 implements X.I { function test() { let c: X.C = new GeneratedObjectLiteralClass_11() - + let i: X.I = new GeneratedObjectLiteralClass_12() -} \ No newline at end of file +} + +class FooBarBaz { + foo?: Map + bar?: string +} + +function baz(fooBar: Map) { + baz2({fooBar}); +} + +function baz2(fooBarBaz: FooBarBaz) { +} diff --git a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json index b652f8984b..cb49576162 100644 --- a/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json +++ b/ets2panda/linter/test/main/object_literals_properties.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 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", @@ -335,4 +335,4 @@ "severity": "ERROR" } ] -} \ 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 index df91841374..0e5d4e1ba8 100644 --- a/ets2panda/linter/test/main/oh_modules/@arkts.utils.d.ets +++ b/ets2panda/linter/test/main/oh_modules/@arkts.utils.d.ets @@ -19,4 +19,16 @@ export namespace utils { } } -export default utils; \ No newline at end of file +export default utils; + +export namespace ArkTSUtils { + export namespace locks { + export class AsyncLock { + constructor(); + } + } + + export namespace safeModule { + export function foo(): void; + } +} \ 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 index dd994ead62..fdb4d44008 100644 --- a/ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets +++ b/ets2panda/linter/test/main/oh_modules/@kit.ArkTS.d.ets @@ -16,4 +16,5 @@ 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 +export { taskpool } from '../oh_modules/@ohos.taskpool'; +export { ArkTSUtils } from '../oh_modules/@arkts.utils'; \ No newline at end of file diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.autofix.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.autofix.json index 7749390fd7..b96614d1d1 100644 --- a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.autofix.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.autofix.json @@ -108,7 +108,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n StorageLink,\n LocalStorageLink,\n} from '@kit.ArkUI';", "line": 32, "column": 2, "endLine": 32, @@ -129,7 +129,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n StorageLink,\n LocalStorageLink,\n} from '@kit.ArkUI';", "line": 32, "column": 2, "endLine": 32, @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n StorageLink,\n LocalStorageLink,\n} from '@kit.ArkUI';", "line": 32, "column": 2, "endLine": 32, @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n StorageLink,\n LocalStorageLink,\n} from '@kit.ArkUI';", "line": 32, "column": 2, "endLine": 32, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n StorageLink,\n LocalStorageLink,\n} from '@kit.ArkUI';", "line": 32, "column": 2, "endLine": 32, diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.ets b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.ets index 15f5527cbf..ca03196a93 100644 --- a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.ets @@ -13,9 +13,18 @@ * limitations under the License. */ -import { PropRef, StoragePropRef, LocalStoragePropRef } from '@kit.ArkUI'; +import { + PropRef, + StoragePropRef, + LocalStoragePropRef, +} from '@kit.ArkUI'; -import { Entry, Component, StorageLink, LocalStorageLink } from '@kit.ArkUI'; +import { + Entry, + Component, + StorageLink, + LocalStorageLink, +} from '@kit.ArkUI'; class User { name: string = "" diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.json index 671d92eb76..66e9c58bab 100644 --- a/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_1.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 28, + "line": 37, "column": 3, - "endLine": 28, + "endLine": 37, "endColumn": 11, "problem": "DecoratorsNotSupported", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 38, + "line": 47, "column": 3, - "endLine": 38, + "endLine": 47, "endColumn": 18, "problem": "DecoratorsNotSupported", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 39, + "line": 48, "column": 3, - "endLine": 39, + "endLine": 48, "endColumn": 23, "problem": "DecoratorsNotSupported", "suggest": "", diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.autofix.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.autofix.json index 2de9a369ef..9a56497197 100644 --- a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.autofix.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.autofix.json @@ -222,7 +222,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -243,7 +243,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -264,7 +264,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -285,7 +285,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -306,7 +306,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -327,7 +327,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -348,7 +348,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -369,7 +369,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -390,7 +390,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -411,7 +411,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -432,7 +432,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -453,7 +453,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -474,7 +474,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -495,7 +495,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -516,7 +516,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -537,7 +537,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -558,7 +558,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -579,7 +579,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -600,7 +600,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -621,7 +621,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -642,7 +642,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -663,7 +663,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -684,7 +684,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -705,7 +705,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -726,7 +726,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -747,7 +747,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -768,7 +768,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -789,7 +789,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -810,7 +810,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, @@ -831,7 +831,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n State,\n Column,\n Text,\n Row,\n Blank,\n Button,\n} from '@kit.ArkUI';", "line": 103, "column": 7, "endLine": 103, diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.ets b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.ets index 7183356197..0d8773c212 100644 --- a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.ets +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.ets @@ -15,7 +15,15 @@ import { PropRef } from '@kit.ArkUI'; -import { Component, State, Column, Text, Row, Blank, Button } from '@kit.ArkUI'; +import { + Component, + State, + Column, + Text, + Row, + Blank, + Button, +} from '@kit.ArkUI'; interface ChildComponentOptions { count: number; diff --git a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.json b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.json index e9031d32bc..21425e4ffe 100644 --- a/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.json +++ b/ets2panda/linter/test/main/prop_decorators_and_interfaces_4.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 62, + "line": 70, "column": 3, - "endLine": 62, + "endLine": 70, "endColumn": 11, "problem": "DecoratorsNotSupported", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 80, + "line": 88, "column": 3, - "endLine": 80, + "endLine": 88, "endColumn": 11, "problem": "DecoratorsNotSupported", "suggest": "", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 98, + "line": 106, "column": 3, - "endLine": 98, + "endLine": 106, "endColumn": 11, "problem": "DecoratorsNotSupported", "suggest": "", @@ -45,9 +45,9 @@ "severity": "ERROR" }, { - "line": 62, + "line": 70, "column": 12, - "endLine": 62, + "endLine": 70, "endColumn": 20, "problem": "StrictDiagnostic", "suggest": "Property 'options1' has no initializer and is not definitely assigned in the constructor.", @@ -55,9 +55,9 @@ "severity": "ERROR" }, { - "line": 80, + "line": 88, "column": 12, - "endLine": 80, + "endLine": 88, "endColumn": 20, "problem": "StrictDiagnostic", "suggest": "Property 'options2' has no initializer and is not definitely assigned in the constructor.", @@ -65,9 +65,9 @@ "severity": "ERROR" }, { - "line": 98, + "line": 106, "column": 12, - "endLine": 98, + "endLine": 106, "endColumn": 20, "problem": "StrictDiagnostic", "suggest": "Property 'options3' has no initializer and is not definitely assigned in the constructor.", 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 16e13e0bf2..67135c7a11 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) 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", @@ -66,7 +66,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -87,7 +87,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -108,7 +108,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -129,7 +129,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -213,7 +213,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -234,7 +234,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.ets b/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.ets index ba3e787752..c51f5678f7 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.ets @@ -13,7 +13,11 @@ * limitations under the License. */ -import { Component, Provide, Column } from '@kit.ArkUI'; +import { + Component, + Provide, + Column, +} from '@kit.ArkUI'; @Component struct Index { diff --git a/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.json b/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.json index 2817e72894..71463836c0 100644 --- a/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.json +++ b/ets2panda/linter/test/main/provide_annotation_1.ets.migrate.json @@ -1,6 +1,6 @@ { "copyright": [ - "Copyright (c) 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", @@ -15,9 +15,9 @@ ], "result": [ { - "line": 21, + "line": 25, "column": 3, - "endLine": 21, + "endLine": 25, "endColumn": 8, "problem": "StrictDiagnostic", "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 35, "column": 3, - "endLine": 31, + "endLine": 35, "endColumn": 8, "problem": "StrictDiagnostic", "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 45, "column": 3, - "endLine": 41, + "endLine": 45, "endColumn": 8, "problem": "StrictDiagnostic", "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", 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 8a98dfc2d8..249ef42308 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.autofix.json @@ -24,7 +24,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -45,7 +45,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -66,7 +66,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -87,7 +87,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -108,7 +108,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -129,7 +129,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, Provide, Column } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n Provide,\n Column,\n} from '@kit.ArkUI';", "line": 41, "column": 5, "endLine": 41, diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.ets b/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.ets index ba3e787752..c51f5678f7 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.ets +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.ets @@ -13,7 +13,11 @@ * limitations under the License. */ -import { Component, Provide, Column } from '@kit.ArkUI'; +import { + Component, + Provide, + Column, +} from '@kit.ArkUI'; @Component struct Index { diff --git a/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.json b/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.json index 2817e72894..4a6bd5efbe 100644 --- a/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.json +++ b/ets2panda/linter/test/main/provide_annotation_2.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 21, + "line": 25, "column": 3, - "endLine": 21, + "endLine": 25, "endColumn": 8, "problem": "StrictDiagnostic", "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 31, + "line": 35, "column": 3, - "endLine": 31, + "endLine": 35, "endColumn": 8, "problem": "StrictDiagnostic", "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", @@ -35,9 +35,9 @@ "severity": "ERROR" }, { - "line": 41, + "line": 45, "column": 3, - "endLine": 41, + "endLine": 45, "endColumn": 8, "problem": "StrictDiagnostic", "suggest": "Property 'value' has no initializer and is not definitely assigned in the constructor.", diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets b/ets2panda/linter/test/main/runtime_array_bound.ets index 5540265166..093c957d7b 100644 --- a/ets2panda/linter/test/main/runtime_array_bound.ets +++ b/ets2panda/linter/test/main/runtime_array_bound.ets @@ -165,3 +165,8 @@ enum TE{ } arr1[TE.AA] = 12; +let a: string[] = []; +let b: Array = new Array(a.length); +for (let i = 0; i < a.length; i++) { + b[i]; +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json b/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json index fb3f014d24..a42550c138 100644 --- a/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.arkts2.json @@ -1853,6 +1853,36 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" + }, + { + "line": 169, + "column": 24, + "endLine": 169, + "endColumn": 43, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 10, + "endLine": 170, + "endColumn": 15, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 170, + "column": 14, + "endLine": 170, + "endColumn": 15, + "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/main/runtime_array_bound.ets.migrate.ets b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets index 2d4beff418..b3691dd0dd 100644 --- a/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets +++ b/ets2panda/linter/test/main/runtime_array_bound.ets.migrate.ets @@ -165,3 +165,8 @@ enum TE{ } arr1[TE.AA] = 12.0; +let a: string[] = []; +let b: Array = new Array(a.length); +for (let i: number = 0.0; i < a.length; i++) { + b[i as int]; +} \ 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 89cd070221..9c75437ef7 100644 --- a/ets2panda/linter/test/main/structural_identity.ets.arkts2.json +++ b/ets2panda/linter/test/main/structural_identity.ets.arkts2.json @@ -1234,6 +1234,16 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, + { + "line": 574, + "column": 44, + "endLine": 574, + "endColumn": 49, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, { "line": 575, "column": 44, @@ -1244,6 +1254,36 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, + { + "line": 575, + "column": 44, + "endLine": 575, + "endColumn": 49, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 576, + "column": 38, + "endLine": 576, + "endColumn": 43, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 577, + "column": 38, + "endLine": 577, + "endColumn": 43, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, { "line": 578, "column": 38, @@ -1254,6 +1294,26 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, + { + "line": 578, + "column": 38, + "endLine": 578, + "endColumn": 43, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, + { + "line": 579, + "column": 44, + "endLine": 579, + "endColumn": 49, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, { "line": 580, "column": 44, @@ -1264,6 +1324,16 @@ "rule": "Structural typing is not supported (arkts-no-structural-typing)", "severity": "ERROR" }, + { + "line": 580, + "column": 44, + "endLine": 580, + "endColumn": 49, + "problem": "NoTsLikeSmartType", + "suggest": "", + "rule": "Smart type differences (arkts-no-ts-like-smart-type)", + "severity": "ERROR" + }, { "line": 590, "column": 10, @@ -1613,16 +1683,6 @@ "suggest": "", "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", "severity": "ERROR" - }, - { - "line": 699, - "column": 14, - "endLine": 699, - "endColumn": 21, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" } ] } \ 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 b63b7b7e89..5968dc36b9 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 @@ -19,9 +19,9 @@ "column": 18, "endLine": 40, "endColumn": 6, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "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 caa81eea0f..8dd9a34ccf 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 @@ -19,7 +19,7 @@ "column": 18, "endLine": 40, "endColumn": 6, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "autofix": [ { "start": 767, @@ -32,7 +32,7 @@ } ], "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "severity": "ERROR" }, { @@ -108,7 +108,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n CommonMethod,\n Color,\n} from '@kit.ArkUI';", "line": 33, "column": 26, "endLine": 33, @@ -129,7 +129,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n CommonMethod,\n Color,\n} from '@kit.ArkUI';", "line": 33, "column": 26, "endLine": 33, @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n CommonMethod,\n Color,\n} from '@kit.ArkUI';", "line": 33, "column": 26, "endLine": 33, @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n CommonMethod,\n Color,\n} from '@kit.ArkUI';", "line": 33, "column": 26, "endLine": 33, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n CommonMethod,\n Color,\n} from '@kit.ArkUI';", "line": 33, "column": 26, "endLine": 33, @@ -213,7 +213,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n CommonMethod,\n Color,\n} from '@kit.ArkUI';", "line": 33, "column": 26, "endLine": 33, 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 index a8c3964416..9df6448f87 100644 --- a/ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/styles_decorator_anon_1.ets.migrate.ets @@ -13,7 +13,15 @@ * limitations under the License. */ -import { Entry, Component, BuilderParam, Require, Button, CommonMethod, Color } from '@kit.ArkUI'; +import { + Entry, + Component, + BuilderParam, + Require, + Button, + CommonMethod, + Color, +} from '@kit.ArkUI'; @Entry @Component 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 bbd292d197..b17ed5a73a 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 @@ -189,7 +189,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, @@ -210,7 +210,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, @@ -231,7 +231,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, @@ -252,7 +252,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, @@ -273,7 +273,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, @@ -294,7 +294,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, @@ -315,7 +315,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, @@ -336,7 +336,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, @@ -357,7 +357,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Component,\n Column,\n Text,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 59, "column": 9, "endLine": 59, 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 index b98a8816ae..9a2edff121 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/styles_decorator_global_1.ets.migrate.ets @@ -13,7 +13,18 @@ * limitations under the License. */ -import { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI'; +import { applyStyles } from '@kit.ArkUI'; + +import { + CommonMethod, + Color, + Component, + Column, + Text, + BuilderParam, + Require, + Button, +} from '@kit.ArkUI'; const mycolor: string = "#ffff00" diff --git a/ets2panda/linter/test/main/styles_decorator_global_2.ets b/ets2panda/linter/test/main/styles_decorator_global_2.ets index fd272fd000..a6aa7a73dd 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 { applyStyles } from '@kit.ArkUI'; + import { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI'; const mycolor: string = "#ffff00" @@ -20,11 +22,11 @@ const mycolor: string = "#ffff00" function cardStyle1(instance: CommonMethod): void { instance.backgroundColor(mycolor); instance.borderColor(Color.Red); - instance.borderRadius(8); - instance.padding(8); + instance.borderRadius(8.0); + instance.padding(8.0); instance.backgroundImagePosition({ - x: 0, - y: 0 + x: 0.0, + y: 0.0 }); } 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 ad6581e89d..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,46 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 23, - "column": 27, - "endLine": 23, - "endColumn": 28, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 22, - "endLine": 24, - "endColumn": 23, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 12, - "endLine": 26, - "endColumn": 13, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 12, - "endLine": 27, - "endColumn": 13, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "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 f06d87b1b5..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,90 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 23, - "column": 27, - "endLine": 23, - "endColumn": 28, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 901, - "end": 902, - "replacementText": "8.0", - "line": 23, - "column": 27, - "endLine": 23, - "endColumn": 28 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 24, - "column": 22, - "endLine": 24, - "endColumn": 23, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 926, - "end": 927, - "replacementText": "8.0", - "line": 24, - "column": 22, - "endLine": 24, - "endColumn": 23 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 26, - "column": 12, - "endLine": 26, - "endColumn": 13, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 980, - "end": 981, - "replacementText": "0.0", - "line": 26, - "column": 12, - "endLine": 26, - "endColumn": 13 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 27, - "column": 12, - "endLine": 27, - "endColumn": 13, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 994, - "end": 995, - "replacementText": "0.0", - "line": 27, - "column": 12, - "endLine": 27, - "endColumn": 13 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - } - ] + "result": [] } \ 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 index b98a8816ae..a6aa7a73dd 100644 --- a/ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.ets +++ b/ets2panda/linter/test/main/styles_decorator_global_2.ets.migrate.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +import { applyStyles } from '@kit.ArkUI'; + import { CommonMethod, Color, Component, Column, Text, BuilderParam, Require, Button } from '@kit.ArkUI'; const mycolor: string = "#ffff00" diff --git a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json index 8879e846e8..41dee5dfe6 100644 --- a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.arkts2.json @@ -39,9 +39,9 @@ "column": 18, "endLine": 43, "endColumn": 6, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "severity": "ERROR" }, { @@ -49,9 +49,9 @@ "column": 18, "endLine": 62, "endColumn": 6, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "severity": "ERROR" }, { @@ -59,9 +59,9 @@ "column": 20, "endLine": 76, "endColumn": 8, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "severity": "ERROR" }, { @@ -69,9 +69,9 @@ "column": 20, "endLine": 90, "endColumn": 8, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "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 index bca7d3fc19..ed6bb9b66e 100644 --- a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.autofix.json +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.autofix.json @@ -45,7 +45,7 @@ { "start": 765, "end": 830, - "replacementText": "PressedStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Green);\n };", + "replacementText": "PressedStyles: CustomStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Green);\n };", "line": 28, "column": 3, "endLine": 31, @@ -61,7 +61,7 @@ "column": 18, "endLine": 43, "endColumn": 6, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "autofix": [ { "start": 912, @@ -74,7 +74,7 @@ } ], "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "severity": "ERROR" }, { @@ -82,7 +82,7 @@ "column": 18, "endLine": 62, "endColumn": 6, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "autofix": [ { "start": 1214, @@ -95,7 +95,7 @@ } ], "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "severity": "ERROR" }, { @@ -103,7 +103,7 @@ "column": 20, "endLine": 76, "endColumn": 8, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "autofix": [ { "start": 1407, @@ -116,7 +116,7 @@ } ], "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "severity": "ERROR" }, { @@ -124,7 +124,7 @@ "column": 20, "endLine": 90, "endColumn": 8, - "problem": "StylesDecoratorNotSupported", + "problem": "StateStylesBlockNeedArrowFunc", "autofix": [ { "start": 1609, @@ -137,7 +137,7 @@ } ], "suggest": "", - "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "rule": "The code block passed to stateStyles needs to be an arrow function (arkui-statestyles-block-need-arrow-func)", "severity": "ERROR" }, { @@ -150,7 +150,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -171,7 +171,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -192,7 +192,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -213,7 +213,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -234,7 +234,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -255,7 +255,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -276,7 +276,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -297,7 +297,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -318,7 +318,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -339,7 +339,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -360,7 +360,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -381,7 +381,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -402,7 +402,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -423,7 +423,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -444,7 +444,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -465,7 +465,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -486,7 +486,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -507,7 +507,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, @@ -528,7 +528,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n CommonMethod,\n Color,\n Entry,\n Component,\n BuilderParam,\n Require,\n Button,\n} from '@kit.ArkUI';", "line": 87, "column": 28, "endLine": 87, diff --git a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.ets index 4e9c2b35e0..0829910761 100644 --- a/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/styles_decorator_mix_1.ets.migrate.ets @@ -13,7 +13,17 @@ * limitations under the License. */ -import { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI'; +import { CustomStyles } from '@kit.ArkUI'; + +import { + CommonMethod, + Color, + Entry, + Component, + BuilderParam, + Require, + Button, +} from '@kit.ArkUI'; function NormalStyles(instance: CommonMethod): void { instance.backgroundColor(Color.Blue); @@ -26,7 +36,7 @@ struct MyButton1 { @Require content: () => void; - PressedStyles = (instance: CommonMethod): void => { + PressedStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Green); }; diff --git a/ets2panda/linter/test/main/styles_decorator_mix_2.ets b/ets2panda/linter/test/main/styles_decorator_mix_2.ets index 4e9c2b35e0..3980b18277 100644 --- a/ets2panda/linter/test/main/styles_decorator_mix_2.ets +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +import { CustomStyles } from '@kit.ArkUI'; + import { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI'; function NormalStyles(instance: CommonMethod): void { @@ -26,7 +28,7 @@ struct MyButton1 { @Require content: () => void; - PressedStyles = (instance: CommonMethod): void => { + PressedStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Green); }; 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 index 4e9c2b35e0..3980b18277 100644 --- a/ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.ets +++ b/ets2panda/linter/test/main/styles_decorator_mix_2.ets.migrate.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +import { CustomStyles } from '@kit.ArkUI'; + import { CommonMethod, Color, Entry, Component, BuilderParam, Require, Button } from '@kit.ArkUI'; function NormalStyles(instance: CommonMethod): void { @@ -26,7 +28,7 @@ struct MyButton1 { @Require content: () => void; - PressedStyles = (instance: CommonMethod): void => { + PressedStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Green); }; 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 9973d73974..e20cf62d15 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 @@ -24,7 +24,7 @@ { "start": 635, "end": 716, - "replacementText": "cardStyle1 = (instance: CommonMethod): void => {\n instance.backgroundColor('#ffffff');\n instance.borderRadius(8);\n };", + "replacementText": "cardStyle1: CustomStyles = (instance: CommonMethod): void => {\n instance.backgroundColor('#ffffff');\n instance.borderRadius(8);\n };", "line": 18, "column": 3, "endLine": 22, @@ -84,7 +84,7 @@ { "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 };", + "replacementText": "cardStyle2: CustomStyles = (instance: CommonMethod): void => {\n instance.border({\n color: this.getColor(),\n width: this.getWidth()\n });\n instance.backgroundColor('#ffffff');\n };", "line": 35, "column": 3, "endLine": 42, @@ -144,7 +144,7 @@ { "start": 1326, "end": 1388, - "replacementText": "NormalStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n };", + "replacementText": "NormalStyles: CustomStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Red);\n };", "line": 67, "column": 3, "endLine": 70, @@ -165,7 +165,7 @@ { "start": 1392, "end": 1457, - "replacementText": "PressedStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Green);\n };", + "replacementText": "PressedStyles: CustomStyles = (instance: CommonMethod): void => {\n instance.backgroundColor(Color.Green);\n };", "line": 72, "column": 3, "endLine": 75, @@ -196,7 +196,7 @@ { "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 };", + "replacementText": "imageStyle: CustomStyles = (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 };", "line": 105, "column": 3, "endLine": 118, @@ -227,7 +227,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -248,7 +248,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -269,7 +269,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -290,7 +290,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -311,7 +311,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -332,7 +332,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -353,7 +353,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -374,7 +374,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -395,7 +395,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -416,7 +416,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -437,7 +437,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -458,7 +458,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -479,7 +479,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -500,7 +500,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -521,7 +521,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -542,7 +542,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -563,7 +563,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, @@ -584,7 +584,7 @@ { "start": 603, "end": 603, - "replacementText": "\n\nimport { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI';", + "replacementText": "\n\nimport {\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n BuilderParam,\n Require,\n Button,\n CustomBuilder,\n} from '@kit.ArkUI';", "line": 103, "column": 24, "endLine": 103, 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 index 006f34c342..9740157644 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.ets +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.ets @@ -13,11 +13,26 @@ * limitations under the License. */ -import { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI'; +import { + CustomStyles, + applyStyles, +} from '@kit.ArkUI'; + +import { + Component, + CommonMethod, + Column, + Text, + Color, + BuilderParam, + Require, + Button, + CustomBuilder, +} from '@kit.ArkUI'; @Component struct MyCard1 { - cardStyle1 = (instance: CommonMethod): void => { + cardStyle1: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor('#ffffff'); instance.borderRadius(8.0); }; @@ -33,7 +48,7 @@ struct MyCard1 { @Component struct MyCard2 { - cardStyle2 = (instance: CommonMethod): void => { + cardStyle2: CustomStyles = (instance: CommonMethod): void => { instance.border({ color: this.getColor(), width: this.getWidth() @@ -64,11 +79,11 @@ struct MyButton { @Require content: () => void; - NormalStyles = (instance: CommonMethod): void => { + NormalStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Red); }; - PressedStyles = (instance: CommonMethod): void => { + PressedStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Green); }; @@ -100,7 +115,7 @@ struct imageTest { private previewUri: string | undefined; private DragBuilder: CustomBuilder | undefined; - imageStyle = (instance: CommonMethod): void => { + imageStyle: CustomStyles = (instance: CommonMethod): void => { instance.draggable(this.isShowLongPressMenu() && this.isPC()); instance.onDragStart(() => { console.info(TAG, 'onDragStart'); 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 index b0daffd23c..a860c9a7c7 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_1.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 101, + "line": 116, "column": 24, - "endLine": 101, + "endLine": 116, "endColumn": 37, "problem": "LimitedVoidTypeFromSdk", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 105, + "line": 120, "column": 26, - "endLine": 113, + "endLine": 128, "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 31fb825cee..18cbf48fc3 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets @@ -13,13 +13,15 @@ * limitations under the License. */ +import { CustomStyles, applyStyles } from '@kit.ArkUI'; + import { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI'; @Component struct MyCard1 { - cardStyle1 = (instance: CommonMethod): void => { + cardStyle1: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor('#ffffff'); - instance.borderRadius(8); + instance.borderRadius(8.0); }; build() { @@ -33,7 +35,7 @@ struct MyCard1 { @Component struct MyCard2 { - cardStyle2 = (instance: CommonMethod): void => { + cardStyle2: CustomStyles = (instance: CommonMethod): void => { instance.border({ color: this.getColor(), width: this.getWidth() @@ -46,7 +48,7 @@ struct MyCard2 { } private getWidth(): number { - return 10 + return 10.0 } build() { @@ -64,11 +66,11 @@ struct MyButton { @Require content: () => void; - NormalStyles = (instance: CommonMethod): void => { + NormalStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Red); }; - PressedStyles = (instance: CommonMethod): void => { + PressedStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Green); }; @@ -100,7 +102,7 @@ struct imageTest { private previewUri: string | undefined; private DragBuilder: CustomBuilder | undefined; - imageStyle = (instance: CommonMethod): void => { + imageStyle: CustomStyles = (instance: CommonMethod): void => { instance.draggable(this.isShowLongPressMenu() && this.isPC()); instance.onDragStart(() => { console.info(TAG, 'onDragStart'); 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 1e21ab6ed3..4eb3f7e164 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": 22, - "column": 27, - "endLine": 22, - "endColumn": 28, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 12, - "endLine": 49, - "endColumn": 14, - "problem": "NumericSemantics", - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 101, + "line": 103, "column": 24, - "endLine": 101, + "endLine": 103, "endColumn": 37, "problem": "LimitedVoidTypeFromSdk", "suggest": "", @@ -45,9 +25,9 @@ "severity": "ERROR" }, { - "line": 105, + "line": 107, "column": 26, - "endLine": 113, + "endLine": 115, "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 bfbd6bbec9..4eb3f7e164 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,51 +15,9 @@ ], "result": [ { - "line": 22, - "column": 27, - "endLine": 22, - "endColumn": 28, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 873, - "end": 874, - "replacementText": "8.0", - "line": 22, - "column": 27, - "endLine": 22, - "endColumn": 28 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 49, - "column": 12, - "endLine": 49, - "endColumn": 14, - "problem": "NumericSemantics", - "autofix": [ - { - "start": 1358, - "end": 1360, - "replacementText": "10.0", - "line": 49, - "column": 12, - "endLine": 49, - "endColumn": 14 - } - ], - "suggest": "", - "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", - "severity": "ERROR" - }, - { - "line": 101, + "line": 103, "column": 24, - "endLine": 101, + "endLine": 103, "endColumn": 37, "problem": "LimitedVoidTypeFromSdk", "suggest": "", @@ -67,9 +25,9 @@ "severity": "ERROR" }, { - "line": 105, + "line": 107, "column": 26, - "endLine": 113, + "endLine": 115, "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 0e17a7dad5..4e818a87e4 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": 105, + "line": 107, "column": 26, - "endLine": 113, + "endLine": 115, "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 index 006f34c342..18cbf48fc3 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.ets +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.ets @@ -13,11 +13,13 @@ * limitations under the License. */ +import { CustomStyles, applyStyles } from '@kit.ArkUI'; + import { Component, CommonMethod, Column, Text, Color, BuilderParam, Require, Button, CustomBuilder } from '@kit.ArkUI'; @Component struct MyCard1 { - cardStyle1 = (instance: CommonMethod): void => { + cardStyle1: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor('#ffffff'); instance.borderRadius(8.0); }; @@ -33,7 +35,7 @@ struct MyCard1 { @Component struct MyCard2 { - cardStyle2 = (instance: CommonMethod): void => { + cardStyle2: CustomStyles = (instance: CommonMethod): void => { instance.border({ color: this.getColor(), width: this.getWidth() @@ -64,11 +66,11 @@ struct MyButton { @Require content: () => void; - NormalStyles = (instance: CommonMethod): void => { + NormalStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Red); }; - PressedStyles = (instance: CommonMethod): void => { + PressedStyles: CustomStyles = (instance: CommonMethod): void => { instance.backgroundColor(Color.Green); }; @@ -100,7 +102,7 @@ struct imageTest { private previewUri: string | undefined; private DragBuilder: CustomBuilder | undefined; - imageStyle = (instance: CommonMethod): void => { + imageStyle: CustomStyles = (instance: CommonMethod): void => { instance.draggable(this.isShowLongPressMenu() && this.isPC()); instance.onDragStart(() => { console.info(TAG, 'onDragStart'); 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 index b0daffd23c..4eb3f7e164 100644 --- a/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.json +++ b/ets2panda/linter/test/main/styles_decorator_struct_2.ets.migrate.json @@ -15,9 +15,9 @@ ], "result": [ { - "line": 101, + "line": 103, "column": 24, - "endLine": 101, + "endLine": 103, "endColumn": 37, "problem": "LimitedVoidTypeFromSdk", "suggest": "", @@ -25,9 +25,9 @@ "severity": "ERROR" }, { - "line": 105, + "line": 107, "column": 26, - "endLine": 113, + "endLine": 115, "endColumn": 6, "problem": "LimitedReturnTypeInference", "suggest": "", diff --git a/ets2panda/linter/test/main/styles_decorator_struct_3.ets b/ets2panda/linter/test/main/styles_decorator_struct_3.ets new file mode 100644 index 0000000000..6fbf3a6408 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_3.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. + */ + +@Entry +@Component +struct MyCard { + @Styles + private cardStyle1() { + .backgroundColor('#ffffff') + .borderRadius(8) + } + + @Styles + public cardStyle2() { + .backgroundColor('#ffffff') + .borderRadius(8) + } + + build() { + Column() { + Text('Card').cardStyle1() + } + .cardStyle2() + .backgroundColor(Color.Red) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_3.ets.args.json b/ets2panda/linter/test/main/styles_decorator_struct_3.ets.args.json new file mode 100644 index 0000000000..ee0734c0fc --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_3.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_struct_3.ets.arkts2.json b/ets2panda/linter/test/main/styles_decorator_struct_3.ets.arkts2.json new file mode 100644 index 0000000000..fe9239c66e --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_3.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": 3, + "endLine": 23, + "endColumn": 4, + "problem": "StylesDecoratorNotSupported", + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 19, + "endLine": 22, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 29, + "endColumn": 4, + "problem": "StylesDecoratorNotSupported", + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 19, + "endLine": 28, + "endColumn": 20, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 7, + "endLine": 33, + "endColumn": 11, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 22, + "endLine": 36, + "endColumn": 27, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_3.ets.autofix.json b/ets2panda/linter/test/main/styles_decorator_struct_3.ets.autofix.json new file mode 100644 index 0000000000..63633712c0 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_3.ets.autofix.json @@ -0,0 +1,225 @@ +{ + "copyright": [ + "Copyright (c) 2025 Huawei Device Co., Ltd.", + "Licensed under the Apache License, Version 2.0 (the 'License');", + "you may not use this file except in compliance with the License.", + "You may obtain a copy of the License at", + "", + "http://www.apache.org/licenses/LICENSE-2.0", + "", + "Unless required by applicable law or agreed to in writing, software", + "distributed under the License is distributed on an 'AS IS' BASIS,", + "WITHOUT WARRANTIES OR 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": 23, + "endColumn": 4, + "problem": "StylesDecoratorNotSupported", + "autofix": [ + { + "start": 641, + "end": 730, + "replacementText": "private cardStyle1: CustomStyles = (instance: CommonMethod): void => {\n instance.backgroundColor('#ffffff');\n instance.borderRadius(8);\n };", + "line": 19, + "column": 3, + "endLine": 23, + "endColumn": 4 + }, + { + "start": 870, + "end": 882, + "replacementText": "applyStyles(this.cardStyle1)", + "line": 19, + "column": 3, + "endLine": 23, + "endColumn": 4 + } + ], + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 22, + "column": 19, + "endLine": 22, + "endColumn": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 724, + "end": 725, + "replacementText": "8.0", + "line": 22, + "column": 19, + "endLine": 22, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 3, + "endLine": 29, + "endColumn": 4, + "problem": "StylesDecoratorNotSupported", + "autofix": [ + { + "start": 734, + "end": 822, + "replacementText": "public cardStyle2: CustomStyles = (instance: CommonMethod): void => {\n instance.backgroundColor('#ffffff');\n instance.borderRadius(8);\n };", + "line": 25, + "column": 3, + "endLine": 29, + "endColumn": 4 + }, + { + "start": 894, + "end": 906, + "replacementText": "applyStyles(this.cardStyle2)", + "line": 25, + "column": 3, + "endLine": 29, + "endColumn": 4 + } + ], + "suggest": "", + "rule": "\"@Styles\" decorator is not supported (arkui-no-styles-decorator)", + "severity": "ERROR" + }, + { + "line": 28, + "column": 19, + "endLine": 28, + "endColumn": 20, + "problem": "NumericSemantics", + "autofix": [ + { + "start": 816, + "end": 817, + "replacementText": "8.0", + "line": 28, + "column": 19, + "endLine": 28, + "endColumn": 20 + } + ], + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 16, + "column": 2, + "endLine": 16, + "endColumn": 7, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport {\n Entry,\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n} from '@kit.ArkUI';", + "line": 36, + "column": 22, + "endLine": 36, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Entry\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 17, + "column": 2, + "endLine": 17, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport {\n Entry,\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n} from '@kit.ArkUI';", + "line": 36, + "column": 22, + "endLine": 36, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Component\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 5, + "endLine": 32, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport {\n Entry,\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n} from '@kit.ArkUI';", + "line": 36, + "column": 22, + "endLine": 36, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Column\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 33, + "column": 7, + "endLine": 33, + "endColumn": 11, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport {\n Entry,\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n} from '@kit.ArkUI';", + "line": 36, + "column": 22, + "endLine": 36, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Text\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 36, + "column": 22, + "endLine": 36, + "endColumn": 27, + "problem": "UIInterfaceImport", + "autofix": [ + { + "start": 603, + "end": 603, + "replacementText": "\n\nimport {\n Entry,\n Component,\n CommonMethod,\n Column,\n Text,\n Color,\n} from '@kit.ArkUI';", + "line": 36, + "column": 22, + "endLine": 36, + "endColumn": 27 + } + ], + "suggest": "", + "rule": "The ArkUI interface \"Color\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + } + ] +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_3.ets.json b/ets2panda/linter/test/main/styles_decorator_struct_3.ets.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_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/styles_decorator_struct_3.ets.migrate.ets b/ets2panda/linter/test/main/styles_decorator_struct_3.ets.migrate.ets new file mode 100644 index 0000000000..4226bfdc36 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_3.ets.migrate.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 { + CustomStyles, + applyStyles, +} from '@kit.ArkUI'; + +import { + Entry, + Component, + CommonMethod, + Column, + Text, + Color, +} from '@kit.ArkUI'; + +@Entry +@Component +struct MyCard { + private cardStyle1: CustomStyles = (instance: CommonMethod): void => { + instance.backgroundColor('#ffffff'); + instance.borderRadius(8.0); + }; + + public cardStyle2: CustomStyles = (instance: CommonMethod): void => { + instance.backgroundColor('#ffffff'); + instance.borderRadius(8.0); + }; + + build() { + Column() { + Text('Card').applyStyles(this.cardStyle1) + } + .applyStyles(this.cardStyle2) + .backgroundColor(Color.Red) + } +} \ No newline at end of file diff --git a/ets2panda/linter/test/main/styles_decorator_struct_3.ets.migrate.json b/ets2panda/linter/test/main/styles_decorator_struct_3.ets.migrate.json new file mode 100644 index 0000000000..ca88f857e9 --- /dev/null +++ b/ets2panda/linter/test/main/styles_decorator_struct_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/main/ts_overload.ets.arkts2.json b/ets2panda/linter/test/main/ts_overload.ets.arkts2.json index 625ed5b833..cf5dc0b7d0 100644 --- a/ets2panda/linter/test/main/ts_overload.ets.arkts2.json +++ b/ets2panda/linter/test/main/ts_overload.ets.arkts2.json @@ -44,26 +44,6 @@ "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", "severity": "ERROR" }, - { - "line": 20, - "column": 16, - "endLine": 20, - "endColumn": 20, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, - { - "line": 22, - "column": 16, - "endLine": 22, - "endColumn": 20, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 25, "column": 21, diff --git a/ets2panda/linter/test/rules/rule37.ets.migrate.json b/ets2panda/linter/test/rules/rule37.ets.migrate.json index 0a1c7ec097..ca88f857e9 100644 --- a/ets2panda/linter/test/rules/rule37.ets.migrate.json +++ b/ets2panda/linter/test/rules/rule37.ets.migrate.json @@ -13,16 +13,5 @@ "See the License for the specific language governing permissions and", "limitations under the License." ], - "result": [ - { - "line": 59, - "column": 21, - "endLine": 59, - "endColumn": 27, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - } - ] + "result": [] } \ No newline at end of file diff --git a/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets b/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets new file mode 100644 index 0000000000..71d8cd2396 --- /dev/null +++ b/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.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 { UIAbility } from '@kit.AbilityKit'; + +function sleep(ms: number): Promise { + return new Promise((resolve, reject) => { + setTimeout(resolve, ms) + }) +} +export default class MyUIAbility extends UIAbility { + async onDestroy(): Promise { // ❌ Error + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); + return sleep(1000); + } +} + + +function sleep(ms: number): Promise { + return new Promise((resolve, reject) => { + setTimeout(resolve, ms) + }) +} +export default class MyUIAbility extends UIAbility { + onDestroy() { // ❌ Error + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); + return sleep(1000); + } +} diff --git a/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.args.json b/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.args.json new file mode 100644 index 0000000000..66fb88f859 --- /dev/null +++ b/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.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/sdk_ability_asynchronous_lifecycle.ets.arkts2.json b/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.arkts2.json new file mode 100644 index 0000000000..6d09991800 --- /dev/null +++ b/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.arkts2.json @@ -0,0 +1,148 @@ +{ + "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": 18, + "column": 1, + "endLine": 22, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 14, + "endLine": 19, + "endColumn": 21, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 19, + "column": 10, + "endLine": 21, + "endColumn": 5, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 3, + "endLine": 27, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 24, + "column": 9, + "endLine": 24, + "endColumn": 18, + "problem": "SdkAbilityAsynchronousLifecycle", + "suggest": "", + "rule": "1.2 Void cannot be combined. OnDestroy/onDisconnect (The return type of the method is now void | Promise) needs to be split into two interfaces. (sdk-ability-asynchronous-lifecycle)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 12, + "endLine": 26, + "endColumn": 23, + "problem": "StructuralIdentity", + "suggest": "", + "rule": "Structural typing is not supported (arkts-no-structural-typing)", + "severity": "ERROR" + }, + { + "line": 26, + "column": 18, + "endLine": 26, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + }, + { + "line": 31, + "column": 1, + "endLine": 35, + "endColumn": 2, + "problem": "TsOverload", + "suggest": "", + "rule": "Class TS overloading is not supported(arkts-no-ts-overload)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 14, + "endLine": 32, + "endColumn": 21, + "problem": "ConstructorIfaceFromSdk", + "suggest": "", + "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", + "severity": "ERROR" + }, + { + "line": 32, + "column": 10, + "endLine": 34, + "endColumn": 5, + "problem": "GenericCallNoTypeArgs", + "suggest": "", + "rule": "Type inference in case of generic function calls is limited (arkts-no-inferred-generic-params)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 3, + "endLine": 40, + "endColumn": 4, + "problem": "LimitedVoidTypeFromSdk", + "suggest": "", + "rule": "Type \"void\" has no instances.(sdk-limited-void-type)", + "severity": "ERROR" + }, + { + "line": 37, + "column": 3, + "endLine": 37, + "endColumn": 12, + "problem": "SdkAbilityAsynchronousLifecycle", + "suggest": "", + "rule": "1.2 Void cannot be combined. OnDestroy/onDisconnect (The return type of the method is now void | Promise) needs to be split into two interfaces. (sdk-ability-asynchronous-lifecycle)", + "severity": "ERROR" + }, + { + "line": 39, + "column": 18, + "endLine": 39, + "endColumn": 22, + "problem": "NumericSemantics", + "suggest": "", + "rule": "Numeric semantics is different for integer values (arkts-numeric-semantic)", + "severity": "ERROR" + } + ] +} diff --git a/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.json b/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.ets.json new file mode 100644 index 0000000000..dd03fcf544 --- /dev/null +++ b/ets2panda/linter/test/sdk_ability_asynchronous_lifecycle.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/decl_with_duplicate_name_sdk.ets b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets index 4584cafa7b..43e59da7f5 100755 --- a/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets +++ b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets @@ -14,15 +14,11 @@ */ '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++) @@ -47,14 +43,26 @@ class TextStyleDemo2 extends TextStyle { // Error } } -let hyperlinkAttr1: HyperlinkAttribute = HyperlinkInterface; -let hyperlinkAttr2: HyperlinkAttribute = HyperlinkInterface.color(''); +let hyperlinkAttr1: HyperlinkAttribute = HyperlinkInterface; // Error +let hyperlinkAttr2: HyperlinkAttribute = HyperlinkInterface.color(''); // Error class HyperlinkTest { - prop1: HyperlinkAttribute = HyperlinkInterface; - prop2: HyperlinkAttribute = HyperlinkInterface.color(''); + prop1: HyperlinkAttribute = HyperlinkInterface; // Error + prop2: HyperlinkAttribute = HyperlinkInterface.color(''); // Error } let hyperlinkAttr3: HyperlinkAttribute; -hyperlinkAttr3 = HyperlinkInterface; -function func(x = HyperlinkInterface) { +hyperlinkAttr3 = HyperlinkInterface; // Error +function func(x = HyperlinkInterface) { // Error + +} +class A { + onBackPress: Function; + TextStyle: Function; + constructor(onBackPress: Function, TextStyle: Function) { + this.onBackPress = onBackPress; // no Error + this.TextStyle = TextStyle; // no Error + } +} +function tt(a: A) { + a.onBackPress(); } 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 index 64896441f0..d351a537bd 100644 --- 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 @@ -15,29 +15,9 @@ ], "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, + "line": 20, "column": 19, - "endLine": 23, + "endLine": 20, "endColumn": 28, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -45,9 +25,9 @@ "severity": "ERROR" }, { - "line": 23, + "line": 20, "column": 35, - "endLine": 23, + "endLine": 20, "endColumn": 44, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -55,9 +35,19 @@ "severity": "ERROR" }, { - "line": 24, + "line": 20, + "column": 35, + "endLine": 20, + "endColumn": 44, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 21, "column": 19, - "endLine": 24, + "endLine": 21, "endColumn": 28, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -65,9 +55,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 22, "column": 27, - "endLine": 26, + "endLine": 22, "endColumn": 36, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -75,9 +65,9 @@ "severity": "ERROR" }, { - "line": 26, + "line": 22, "column": 40, - "endLine": 26, + "endLine": 22, "endColumn": 51, "problem": "GenericCallNoTypeArgs", "suggest": "", @@ -85,9 +75,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 24, "column": 14, - "endLine": 28, + "endLine": 24, "endColumn": 20, "problem": "NumericSemantics", "suggest": "", @@ -95,9 +85,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 24, "column": 18, - "endLine": 28, + "endLine": 24, "endColumn": 20, "problem": "NumericSemantics", "suggest": "", @@ -105,9 +95,9 @@ "severity": "ERROR" }, { - "line": 28, + "line": 24, "column": 26, - "endLine": 28, + "endLine": 24, "endColumn": 28, "problem": "NumericSemantics", "suggest": "", @@ -115,9 +105,9 @@ "severity": "ERROR" }, { - "line": 29, + "line": 25, "column": 31, - "endLine": 29, + "endLine": 25, "endColumn": 40, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -125,9 +115,19 @@ "severity": "ERROR" }, { - "line": 34, + "line": 25, + "column": 31, + "endLine": 25, + "endColumn": 40, + "problem": "DynamicCtorCall", + "suggest": "", + "rule": "\"new\" expression with dynamic constructor type is not supported (arkts-no-dynamic-ctor-call)", + "severity": "ERROR" + }, + { + "line": 30, "column": 38, - "endLine": 34, + "endLine": 30, "endColumn": 47, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -135,9 +135,9 @@ "severity": "ERROR" }, { - "line": 44, + "line": 40, "column": 30, - "endLine": 44, + "endLine": 40, "endColumn": 39, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -145,9 +145,9 @@ "severity": "ERROR" }, { - "line": 50, + "line": 46, "column": 42, - "endLine": 50, + "endLine": 46, "endColumn": 60, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -155,9 +155,9 @@ "severity": "ERROR" }, { - "line": 51, + "line": 47, "column": 42, - "endLine": 51, + "endLine": 47, "endColumn": 60, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -165,9 +165,9 @@ "severity": "ERROR" }, { - "line": 53, + "line": 49, "column": 31, - "endLine": 53, + "endLine": 49, "endColumn": 49, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -175,9 +175,9 @@ "severity": "ERROR" }, { - "line": 54, + "line": 50, "column": 31, - "endLine": 54, + "endLine": 50, "endColumn": 49, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -185,9 +185,9 @@ "severity": "ERROR" }, { - "line": 57, + "line": 53, "column": 18, - "endLine": 57, + "endLine": 53, "endColumn": 36, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -195,9 +195,19 @@ "severity": "ERROR" }, { - "line": 58, + "line": 54, + "column": 15, + "endLine": 54, + "endColumn": 37, + "problem": "AnyType", + "suggest": "", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", + "severity": "ERROR" + }, + { + "line": 54, "column": 19, - "endLine": 58, + "endLine": 54, "endColumn": 37, "problem": "DuplicateDeclNameFromSdk", "suggest": "", @@ -205,9 +215,19 @@ "severity": "ERROR" }, { - "line": 20, + "line": 67, + "column": 3, + "endLine": 67, + "endColumn": 16, + "problem": "ExplicitFunctionType", + "suggest": "", + "rule": "The function type should be explicit (arkts-no-ts-like-function-call)", + "severity": "ERROR" + }, + { + "line": 17, "column": 2, - "endLine": 20, + "endLine": 17, "endColumn": 7, "problem": "UIInterfaceImport", "suggest": "", @@ -215,9 +235,9 @@ "severity": "ERROR" }, { - "line": 21, + "line": 18, "column": 2, - "endLine": 21, + "endLine": 18, "endColumn": 11, "problem": "UIInterfaceImport", "suggest": "", @@ -225,9 +245,29 @@ "severity": "ERROR" }, { - "line": 23, + "line": 20, + "column": 19, + "endLine": 20, + "endColumn": 28, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"TextStyle\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 20, + "column": 35, + "endLine": 20, + "endColumn": 44, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"TextStyle\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 20, "column": 57, - "endLine": 23, + "endLine": 20, "endColumn": 62, "problem": "UIInterfaceImport", "suggest": "", @@ -235,9 +275,19 @@ "severity": "ERROR" }, { - "line": 26, + "line": 21, + "column": 19, + "endLine": 21, + "endColumn": 28, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"TextStyle\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 22, "column": 4, - "endLine": 26, + "endLine": 22, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", @@ -245,9 +295,29 @@ "severity": "ERROR" }, { - "line": 33, + "line": 22, + "column": 27, + "endLine": 22, + "endColumn": 36, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"TextStyle\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 25, + "column": 31, + "endLine": 25, + "endColumn": 40, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"TextStyle\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 29, "column": 5, - "endLine": 33, + "endLine": 29, "endColumn": 9, "problem": "UIInterfaceImport", "suggest": "", @@ -255,9 +325,9 @@ "severity": "ERROR" }, { - "line": 34, + "line": 30, "column": 7, - "endLine": 34, + "endLine": 30, "endColumn": 14, "problem": "UIInterfaceImport", "suggest": "", @@ -265,9 +335,19 @@ "severity": "ERROR" }, { - "line": 35, + "line": 30, + "column": 38, + "endLine": 30, + "endColumn": 47, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"TextStyle\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 31, "column": 9, - "endLine": 35, + "endLine": 31, "endColumn": 17, "problem": "UIInterfaceImport", "suggest": "", @@ -275,9 +355,9 @@ "severity": "ERROR" }, { - "line": 36, + "line": 32, "column": 11, - "endLine": 36, + "endLine": 32, "endColumn": 15, "problem": "UIInterfaceImport", "suggest": "", @@ -285,13 +365,63 @@ "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.", + "line": 40, + "column": 30, + "endLine": 40, + "endColumn": 39, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"TextStyle\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 46, + "column": 21, + "endLine": 46, + "endColumn": 39, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"HyperlinkAttribute\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 47, + "column": 21, + "endLine": 47, + "endColumn": 39, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"HyperlinkAttribute\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 49, + "column": 10, + "endLine": 49, + "endColumn": 28, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"HyperlinkAttribute\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 50, + "column": 10, + "endLine": 50, + "endColumn": 28, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"HyperlinkAttribute\" should be imported before it is used (arkui-modular-interface)", + "severity": "ERROR" + }, + { + "line": 52, + "column": 21, + "endLine": 52, + "endColumn": 39, + "problem": "UIInterfaceImport", + "suggest": "", + "rule": "The ArkUI interface \"HyperlinkAttribute\" should be imported before it is used (arkui-modular-interface)", "severity": "ERROR" } ] 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 index 489a1474b5..4e18966ecf 100755 --- a/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.json +++ b/ets2panda/linter/test/sdkwhite/decl_with_duplicate_name_sdk.ets.json @@ -15,33 +15,13 @@ ], "result": [ { - "line": 17, - "column": 1, - "endLine": 17, - "endColumn": 61, - "problem": "ImportAfterStatement", + "line": 54, + "column": 15, + "endLine": 54, + "endColumn": 37, + "problem": "AnyType", "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.", + "rule": "Use explicit types instead of \"any\", \"unknown\" (arkts-no-any-unknown)", "severity": "ERROR" } ] diff --git a/ets2panda/linter/test/sdkwhite/return_new_interface.ets.arkts2.json b/ets2panda/linter/test/sdkwhite/return_new_interface.ets.arkts2.json index 7b974d3450..9245dba0a1 100644 --- a/ets2panda/linter/test/sdkwhite/return_new_interface.ets.arkts2.json +++ b/ets2panda/linter/test/sdkwhite/return_new_interface.ets.arkts2.json @@ -44,16 +44,6 @@ "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, - { - "line": 26, - "column": 14, - "endLine": 26, - "endColumn": 15, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 26, "column": 14, @@ -74,16 +64,6 @@ "rule": "Function return type inference is limited (arkts-no-implicit-return-types)", "severity": "ERROR" }, - { - "line": 30, - "column": 14, - "endLine": 30, - "endColumn": 15, - "problem": "ConstructorIfaceFromSdk", - "suggest": "", - "rule": "Construct signatures are not supported in interfaces.(sdk-ctor-signatures-iface)", - "severity": "ERROR" - }, { "line": 30, "column": 14, diff --git a/ets2panda/linter/webpack.config.js b/ets2panda/linter/webpack.config.js index 15ee37c29b..2a15b2bfd7 100644 --- a/ets2panda/linter/webpack.config.js +++ b/ets2panda/linter/webpack.config.js @@ -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 @@ -17,7 +17,7 @@ let path = require('path'); module.exports = { mode: 'development', - target: 'node', + target: 'node', entry: './build/cli/main.js', externalsType: 'commonjs', externals: { -- Gitee From 2b611e944cc4d1f686da8a471ec3d0d12e7dfe5c Mon Sep 17 00:00:00 2001 From: Torok Gergo Date: Tue, 3 Jun 2025 11:39:54 +0200 Subject: [PATCH 036/145] Fixing async assertion error Reason: Async methods with optional parameter emitted assertion error. Description: Replace SetAnnotations to AddAnnotations so the previous data doest'n get lost Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICC9SZ Signed-off-by: Torok Gergo --- ets2panda/compiler/core/ETSemitter.cpp | 2 +- .../test/runtime/ets/asyncWithDefaultParam.ets | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/runtime/ets/asyncWithDefaultParam.ets diff --git a/ets2panda/compiler/core/ETSemitter.cpp b/ets2panda/compiler/core/ETSemitter.cpp index 6eba5e1753..f8b73b206f 100644 --- a/ets2panda/compiler/core/ETSemitter.cpp +++ b/ets2panda/compiler/core/ETSemitter.cpp @@ -291,7 +291,7 @@ void ETSEmitter::GenAnnotation() if (scriptFunc->IsAsyncFunc()) { std::vector annotations; annotations.push_back(GenAnnotationAsync(scriptFunc)); - func.metadata->SetAnnotations(std::move(annotations)); + func.metadata->AddAnnotations(annotations); } Program()->AddToFunctionTable(std::move(func)); } diff --git a/ets2panda/test/runtime/ets/asyncWithDefaultParam.ets b/ets2panda/test/runtime/ets/asyncWithDefaultParam.ets new file mode 100644 index 0000000000..1082ea3a1a --- /dev/null +++ b/ets2panda/test/runtime/ets/asyncWithDefaultParam.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. + */ + +async function emitAsync1(args: int | undefined = 1): Promise {} +async function emitAsync2(args?: int): Promise {} -- Gitee From d58266d4e4c26ec2310c534f1490f9000567b191 Mon Sep 17 00:00:00 2001 From: yunusemrekarakaya Date: Thu, 19 Jun 2025 15:02:07 +0300 Subject: [PATCH 037/145] [Bug]: ErrorType Control Issue : https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGGBG Signed-off-by: yunusemrekarakaya --- ets2panda/checker/ets/utilityTypeHandlers.cpp | 3 ++ ...ility_type_can_not_found_etsobjecttype.ets | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/utility_type_can_not_found_etsobjecttype.ets diff --git a/ets2panda/checker/ets/utilityTypeHandlers.cpp b/ets2panda/checker/ets/utilityTypeHandlers.cpp index d9e630189d..6f74238afc 100644 --- a/ets2panda/checker/ets/utilityTypeHandlers.cpp +++ b/ets2panda/checker/ets/utilityTypeHandlers.cpp @@ -114,6 +114,9 @@ static T *CloneNodeIfNotNullptr(T *node, ArenaAllocator *allocator) Type *ETSChecker::CreatePartialType(Type *const typeToBePartial) { ES2PANDA_ASSERT(typeToBePartial->IsETSReferenceType()); + if (typeToBePartial->IsTypeError()) { + return typeToBePartial; + } if (typeToBePartial->IsETSTypeParameter()) { return CreatePartialTypeParameter(typeToBePartial->AsETSTypeParameter()); diff --git a/ets2panda/test/ast/compiler/ets/utility_type_can_not_found_etsobjecttype.ets b/ets2panda/test/ast/compiler/ets/utility_type_can_not_found_etsobjecttype.ets new file mode 100644 index 0000000000..f549a860b8 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/utility_type_can_not_found_etsobjecttype.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. + */ + +type BaseObject = Record; + +class X { + x: T; + + constructor(init?: Partial) { + + this.x = {} as T; + + } +} + +/* @@? 16:34 Error TypeError: Cannot find type 'any'. */ +/* @@? 23:14 Error TypeError: Target type for class composite needs to be an object type, found 'T' */ \ No newline at end of file -- Gitee From 14f8bbdb3ea261004f500e8a3243113046b8b71d Mon Sep 17 00:00:00 2001 From: lihao Date: Fri, 6 Jun 2025 14:48:31 +0800 Subject: [PATCH 038/145] load es2panda by absolute path Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIY4Q Signed-off-by: lihao Change-Id: Ief276c254487c188e70f6eb775b69072fb63bd3a --- ets2panda/driver/build_system/src/init/process_build_config.ts | 1 + ets2panda/driver/build_system/src/types.ts | 1 + 2 files changed, 2 insertions(+) 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 596b32486d..066eb65abf 100644 --- a/ets2panda/driver/build_system/src/init/process_build_config.ts +++ b/ets2panda/driver/build_system/src/init/process_build_config.ts @@ -139,4 +139,5 @@ function initKoalaWrapper(buildConfig: BuildConfig): void { const { arkts, arktsGlobal } = require(koalaWrapperPath); buildConfig.arkts = arkts; buildConfig.arktsGlobal = arktsGlobal; + buildConfig.arktsGlobal.es2panda._SetUpSoPath(buildConfig.pandaSdkPath); } diff --git a/ets2panda/driver/build_system/src/types.ts b/ets2panda/driver/build_system/src/types.ts index 0d0d0d38ac..fa82a48003 100644 --- a/ets2panda/driver/build_system/src/types.ts +++ b/ets2panda/driver/build_system/src/types.ts @@ -37,6 +37,7 @@ export interface ArkTSGlobal { }; es2panda: { _DestroyContext: Function; + _SetUpSoPath: Function; } } -- Gitee From ec84d6180eca9376b208219d4d66740b0943431b Mon Sep 17 00:00:00 2001 From: Vsevolod Pukhov Date: Mon, 19 May 2025 16:49:56 +0300 Subject: [PATCH 039/145] Any type * Add Any built-in type and type relations * Make Any a new top boundary type * Refactor TypeKind flag computer * Remove IsConditionalExprType concept * Simplify codegen for narrowings Issue: [cherry-pick 0603] Need to merge any type PR https://gitee.com/openharmony/arkcompiler_runtime_core/issues/ICIELO Signed-off-by: Vsevolod Pukhov --- ets2panda/BUILD.gn | 1 + ets2panda/CMakeLists.txt | 1 + .../invariants/identifierHasVariable.cpp | 17 ++- ets2panda/checker/ETSAnalyzer.cpp | 15 ++- ets2panda/checker/ETSAnalyzerHelpers.cpp | 3 +- ets2panda/checker/ETSchecker.cpp | 29 ++++- ets2panda/checker/ETSchecker.h | 14 +-- ets2panda/checker/ets/aliveAnalyzer.cpp | 6 +- ets2panda/checker/ets/arithmetic.cpp | 15 +-- ets2panda/checker/ets/helpers.cpp | 2 +- ets2panda/checker/ets/object.cpp | 4 +- ets2panda/checker/ets/typeCheckingHelpers.cpp | 38 +++--- ets2panda/checker/ets/typeConverter.h | 4 +- ets2panda/checker/ets/typeCreation.cpp | 4 +- ets2panda/checker/ets/utilityTypeHandlers.cpp | 8 ++ ets2panda/checker/types/ets/etsAnyType.cpp | 112 ++++++++++++++++++ ets2panda/checker/types/ets/etsAnyType.h | 49 ++++++++ .../checker/types/ets/etsFunctionType.cpp | 4 +- ets2panda/checker/types/ets/types.h | 1 + ets2panda/checker/types/globalTypesHolder.cpp | 16 ++- ets2panda/checker/types/globalTypesHolder.h | 10 +- ets2panda/checker/types/type.h | 5 - ets2panda/checker/types/typeFlag.h | 9 +- ets2panda/checker/types/typeMapping.h | 3 +- ets2panda/compiler/base/condition.cpp | 1 - ets2panda/compiler/core/ETSCompiler.cpp | 1 + ets2panda/compiler/core/ETSGen.cpp | 43 +++---- ets2panda/compiler/core/ETSGen.h | 16 +++ .../lowering/ets/arrayLiteralLowering.cpp | 2 +- .../lowering/ets/declareOverloadLowering.cpp | 6 +- .../lowering/ets/enumPostCheckLowering.cpp | 2 +- .../compiler/lowering/ets/lambdaLowering.cpp | 20 ++-- ets2panda/compiler/scripts/signatures.yaml | 2 + ets2panda/ir/ets/etsTypeReferencePart.cpp | 112 +++++++++--------- ets2panda/ir/ets/etsTypeReferencePart.h | 2 - ets2panda/lexer/scripts/keywords.yaml | 5 + .../FunctionalTypeAsArrayElement.ets | 2 +- .../ets/FunctionalTypeAsArrayElement.ets | 2 +- .../annotationDecl_bad_initializer03.ets | 4 +- .../annotationUsage_bad_param04.ets | 2 +- ...ment-on-nullish-type-undefined-invalid.ets | 1 - .../ast/parser/ets/type_from_utility_type.ets | 1 - ets2panda/test/runtime/ets/AnyType.ets | 41 +++++++ ets2panda/test/runtime/ets/Function.ets | 4 +- ets2panda/test/runtime/ets/NoConstraint.ets | 6 +- .../runtime/ets/defaultLocalInitializers.ets | 2 +- .../test/runtime/ets/stringComparision.ets | 2 +- ets2panda/util/diagnostic/semantic.yaml | 8 -- ets2panda/varbinder/ETSBinder.cpp | 7 +- 49 files changed, 456 insertions(+), 208 deletions(-) create mode 100644 ets2panda/checker/types/ets/etsAnyType.cpp create mode 100644 ets2panda/checker/types/ets/etsAnyType.h create mode 100644 ets2panda/test/runtime/ets/AnyType.ets diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index dec0dc9a48..5fd3853ad0 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -126,6 +126,7 @@ libes2panda_sources = [ "checker/types/ets/intType.cpp", "checker/types/ets/longType.cpp", "checker/types/ets/shortType.cpp", + "checker/types/ets/etsAnyType.cpp", "checker/types/ets/wildcardType.cpp", "checker/types/globalTypesHolder.cpp", "checker/types/signature.cpp", diff --git a/ets2panda/CMakeLists.txt b/ets2panda/CMakeLists.txt index 10cf792e94..03ff66845f 100644 --- a/ets2panda/CMakeLists.txt +++ b/ets2panda/CMakeLists.txt @@ -581,6 +581,7 @@ set(ES2PANDA_LIB_SRC checker/types/ets/intType.cpp checker/types/ets/longType.cpp checker/types/ets/shortType.cpp + checker/types/ets/etsAnyType.cpp checker/types/ets/etsArrayType.cpp checker/types/ets/etsBooleanType.cpp checker/types/ets/etsDynamicType.cpp diff --git a/ets2panda/ast_verifier/invariants/identifierHasVariable.cpp b/ets2panda/ast_verifier/invariants/identifierHasVariable.cpp index 930ac3249a..4eae5c316c 100644 --- a/ets2panda/ast_verifier/invariants/identifierHasVariable.cpp +++ b/ets2panda/ast_verifier/invariants/identifierHasVariable.cpp @@ -25,8 +25,8 @@ public: ExceptionsMatcher(const IdentifierHasVariable *inv, const ir::Identifier *ast) : inv_(inv), ast_(ast) {} bool Match() { - auto res = IsLengthProp() || IsEmptyName() || IsInObjectExpr() || IsInPackageDecl() || IsUtilityType() || - IsUnionMemberAccess() || IsFixedArrayType(); + auto res = IsLengthProp() || IsEmptyName() || IsInObjectExpr() || IsInPackageDecl() || IsBuiltinType() || + IsUnionMemberAccess(); return res; } @@ -69,16 +69,13 @@ private: return false; } - bool IsUtilityType() + bool IsBuiltinType() { + auto name = ast_->Name(); // NOTE(mmartin): find a better solution to handle utility type resolution - return ast_->Name().Is(Signatures::PARTIAL_TYPE_NAME) || ast_->Name().Is(Signatures::REQUIRED_TYPE_NAME) || - ast_->Name().Is(Signatures::READONLY_TYPE_NAME); - } - - bool IsFixedArrayType() - { - return ast_->Name().Is(Signatures::FIXED_ARRAY_TYPE_NAME); + return name.Is(Signatures::PARTIAL_TYPE_NAME) || name.Is(Signatures::REQUIRED_TYPE_NAME) || + name.Is(Signatures::READONLY_TYPE_NAME) || name.Is(Signatures::FIXED_ARRAY_TYPE_NAME) || + name.Is(compiler::Signatures::ANY_TYPE_NAME); } bool IsUnionMemberAccess() diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 9c5c1c1bdd..19596b2457 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -849,6 +849,11 @@ static bool CheckArrayExpressionElements(ETSChecker *checker, ir::ArrayExpressio return allElementsAssignable; } +static bool IsPossibleArrayExpressionType(Type const *type) +{ + return type->IsETSArrayType() || type->IsETSTupleType() || type->IsETSResizableArrayType(); +} + void ETSAnalyzer::GetUnionPreferredType(ir::Expression *expr, Type *originalType) const { if (originalType == nullptr || !originalType->IsETSUnionType()) { @@ -856,7 +861,7 @@ void ETSAnalyzer::GetUnionPreferredType(ir::Expression *expr, Type *originalType } checker::Type *preferredType = nullptr; for (auto &type : originalType->AsETSUnionType()->ConstituentTypes()) { - if (type->IsETSArrayType() || type->IsETSTupleType() || type->IsETSResizableArrayType()) { + if (IsPossibleArrayExpressionType(type)) { if (preferredType != nullptr) { preferredType = nullptr; break; @@ -890,6 +895,10 @@ checker::Type *ETSAnalyzer::Check(ir::ArrayExpression *expr) const if (expr->GetPreferredType()->IsETSUnionType()) { GetUnionPreferredType(expr, expr->GetPreferredType()); } + + if (expr->GetPreferredType() != nullptr && !IsPossibleArrayExpressionType(expr->GetPreferredType())) { + expr->SetPreferredType(nullptr); + } } if (!IsArrayExpressionValidInitializerForType(checker, expr->GetPreferredType())) { @@ -1564,7 +1573,7 @@ checker::Type *ETSAnalyzer::Check(ir::CallExpression *expr) const } if (calleeType->IsETSArrowType()) { expr->SetUncheckedType(checker->GuaranteedTypeForUncheckedCast( - checker->GlobalETSNullishObjectType(), checker->MaybeBoxType(expr->Signature()->ReturnType()))); + checker->GlobalETSAnyType(), checker->MaybeBoxType(expr->Signature()->ReturnType()))); } else { expr->SetUncheckedType(checker->GuaranteedTypeForUncheckedCallReturn(expr->Signature())); } @@ -1826,7 +1835,7 @@ checker::Type *ETSAnalyzer::Check(ir::MemberExpression *expr) const } if (!checker->CheckNonNullish(expr->Object())) { auto *invalidType = checker->HasStatus(checker::CheckerStatus::IN_EXTENSION_ACCESSOR_CHECK) - ? checker->GlobalETSNullishType() + ? checker->GlobalETSUnionUndefinedNull() : checker->InvalidateType(expr); return invalidType; } diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index f652f68e78..de15a13dd9 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -516,8 +516,7 @@ void ProcessExclamationMark(ETSChecker *checker, ir::UnaryExpression *expr, chec return; } - if (operandType == nullptr || !operandType->IsConditionalExprType()) { - checker->LogError(diagnostic::ASSERT_NOT_LOGICAL, {}, expr->Argument()->Start()); + if (operandType == nullptr || operandType->IsTypeError()) { expr->SetTsType(checker->GlobalTypeError()); return; } diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index 227ef17874..9255b39ae7 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -411,6 +411,22 @@ bool ETSChecker::IsClassStaticMethod(checker::ETSObjectType *objType, checker::S signature->HasSignatureFlag(checker::SignatureFlags::STATIC); } +[[nodiscard]] TypeFlag ETSChecker::TypeKind(const Type *const type) noexcept +{ + // These types were not present in the ETS_TYPE list. Some of them are omited intentionally, other are just bugs + static constexpr auto TO_CLEAR = TypeFlag::CONSTANT | TypeFlag::GENERIC | TypeFlag::ETS_INT_ENUM | + TypeFlag::ETS_STRING_ENUM | TypeFlag::READONLY | TypeFlag::BIGINT_LITERAL | + TypeFlag::ETS_TYPE_ALIAS | TypeFlag::TYPE_ERROR; + + // Bugs: these types do not appear as a valid TypeKind, as the TypeKind has more then one bit set + [[maybe_unused]] static constexpr auto NOT_A_TYPE_KIND = TypeFlag::ETS_DYNAMIC_FLAG; + + auto res = static_cast(type->TypeFlags() & ~(TO_CLEAR)); + ES2PANDA_ASSERT_POS(res == TypeFlag::NONE || helpers::math::IsPowerOfTwo(res & ~(NOT_A_TYPE_KIND)), + ark::es2panda::GetPositionForDiagnostic()); + return res; +} + template ETSObjectType *ETSChecker::AsETSObjectType(Type *(GlobalTypesHolder::*typeFunctor)(Args...), Args... args) const { @@ -512,6 +528,11 @@ Type *ETSChecker::GlobalETSUndefinedType() const return GetGlobalTypesHolder()->GlobalETSUndefinedType(); } +Type *ETSChecker::GlobalETSAnyType() const +{ + return GetGlobalTypesHolder()->GlobalETSAnyType(); +} + Type *ETSChecker::GlobalETSNeverType() const { return GetGlobalTypesHolder()->GlobalETSNeverType(); @@ -537,15 +558,15 @@ ETSObjectType *ETSChecker::GlobalETSObjectType() const return AsETSObjectType(&GlobalTypesHolder::GlobalETSObjectType); } -ETSUnionType *ETSChecker::GlobalETSNullishType() const +ETSUnionType *ETSChecker::GlobalETSUnionUndefinedNull() const { - auto *ret = (GetGlobalTypesHolder()->*&GlobalTypesHolder::GlobalETSNullishType)(); + auto *ret = (GetGlobalTypesHolder()->*&GlobalTypesHolder::GlobalETSUnionUndefinedNull)(); return ret != nullptr ? ret->AsETSUnionType() : nullptr; } -ETSUnionType *ETSChecker::GlobalETSNullishObjectType() const +ETSUnionType *ETSChecker::GlobalETSUnionUndefinedNullObject() const { - auto *ret = (GetGlobalTypesHolder()->*&GlobalTypesHolder::GlobalETSNullishObjectType)(); + auto *ret = (GetGlobalTypesHolder()->*&GlobalTypesHolder::GlobalETSUnionUndefinedNullObject)(); return ret != nullptr ? ret->AsETSUnionType() : nullptr; } diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 06de9f47df..da0dc43789 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -88,15 +88,12 @@ public: NO_COPY_SEMANTIC(ETSChecker); NO_MOVE_SEMANTIC(ETSChecker); - [[nodiscard]] static inline TypeFlag ETSType(const Type *const type) noexcept + [[nodiscard]] static TypeFlag ETSType(const Type *const type) noexcept { - return static_cast(type->TypeFlags() & TypeFlag::ETS_TYPE); + return ETSChecker::TypeKind(type); } - [[nodiscard]] static inline TypeFlag TypeKind(const Type *const type) noexcept - { - return static_cast(type->TypeFlags() & checker::TypeFlag::ETS_TYPE); - } + [[nodiscard]] static TypeFlag TypeKind(const Type *const type) noexcept; Type *GlobalByteType() const; Type *GlobalShortType() const; @@ -109,6 +106,7 @@ public: Type *GlobalVoidType() const; Type *GlobalETSNullType() const; Type *GlobalETSUndefinedType() const; + Type *GlobalETSAnyType() const; Type *GlobalETSNeverType() const; Type *GlobalETSStringLiteralType() const; Type *GlobalETSBigIntType() const; @@ -124,8 +122,8 @@ public: Type *GlobalETSBooleanBuiltinType() const; ETSObjectType *GlobalETSObjectType() const; - ETSUnionType *GlobalETSNullishType() const; - ETSUnionType *GlobalETSNullishObjectType() const; + ETSUnionType *GlobalETSUnionUndefinedNull() const; + ETSUnionType *GlobalETSUnionUndefinedNullObject() const; ETSObjectType *GlobalBuiltinETSResizableArrayType() const; ETSObjectType *GlobalBuiltinETSStringType() const; ETSObjectType *GlobalBuiltinETSBigIntType() const; diff --git a/ets2panda/checker/ets/aliveAnalyzer.cpp b/ets2panda/checker/ets/aliveAnalyzer.cpp index ff2ba27302..5714edf7ca 100644 --- a/ets2panda/checker/ets/aliveAnalyzer.cpp +++ b/ets2panda/checker/ets/aliveAnalyzer.cpp @@ -281,7 +281,7 @@ void AliveAnalyzer::AnalyzeDoLoop(const ir::DoWhileStatement *doWhile) AnalyzeStat(doWhile->Body()); status_ = Or(status_, ResolveContinues(doWhile)); AnalyzeNode(doWhile->Test()); - ES2PANDA_ASSERT(doWhile->Test()->TsType() && doWhile->Test()->TsType()->IsConditionalExprType()); + ES2PANDA_ASSERT(doWhile->Test()->TsType()); const auto exprRes = doWhile->Test()->TsType()->ResolveConditionExpr(); status_ = And(status_, static_cast(!std::get<0>(exprRes) || !std::get<1>(exprRes))); status_ = Or(status_, ResolveBreaks(doWhile)); @@ -291,7 +291,7 @@ void AliveAnalyzer::AnalyzeWhileLoop(const ir::WhileStatement *whileStmt) { SetOldPendingExits(PendingExits()); AnalyzeNode(whileStmt->Test()); - ES2PANDA_ASSERT(whileStmt->Test()->TsType() && whileStmt->Test()->TsType()->IsConditionalExprType()); + ES2PANDA_ASSERT(whileStmt->Test()->TsType()); const auto exprRes = whileStmt->Test()->TsType()->ResolveConditionExpr(); status_ = And(status_, static_cast(!std::get<0>(exprRes) || std::get<1>(exprRes))); AnalyzeStat(whileStmt->Body()); @@ -309,7 +309,7 @@ void AliveAnalyzer::AnalyzeForLoop(const ir::ForUpdateStatement *forStmt) if (forStmt->Test() != nullptr) { AnalyzeNode(forStmt->Test()); - ES2PANDA_ASSERT(forStmt->Test()->TsType() && forStmt->Test()->TsType()->IsConditionalExprType()); + ES2PANDA_ASSERT(forStmt->Test()->TsType()); condType = forStmt->Test()->TsType(); std::tie(resolveType, res) = forStmt->Test()->TsType()->ResolveConditionExpr(); status_ = From(!resolveType || res); diff --git a/ets2panda/checker/ets/arithmetic.cpp b/ets2panda/checker/ets/arithmetic.cpp index 7f9007daec..9fe9eee1e4 100644 --- a/ets2panda/checker/ets/arithmetic.cpp +++ b/ets2panda/checker/ets/arithmetic.cpp @@ -556,15 +556,16 @@ checker::Type *ETSChecker::CheckBinaryOperatorLogical(ir::Expression *left, ir:: return CreateETSUnionType({MaybeBoxExpression(left), MaybeBoxExpression(right)}); } +// NOTE: code inside this function follows the broken logic bool ETSChecker::CheckValidEqualReferenceType(checker::Type *const leftType, checker::Type *const rightType) { - auto isGlobalObjectType {[](checker::Type *const type) -> bool { - return type->IsETSObjectType() && type->AsETSObjectType()->IsGlobalETSObjectType(); + auto isRelaxedType {[](checker::Type *const type) -> bool { + return (type->IsETSObjectType() && type->AsETSObjectType()->IsGlobalETSObjectType()) || type->IsETSAnyType() || + type->IsETSNullType() || type->IsETSUndefinedType(); }}; - // Equality expression is always allowed for Object, undefined and null - if (isGlobalObjectType(leftType) || isGlobalObjectType(rightType) || leftType->IsETSUndefinedType() || - rightType->IsETSUndefinedType() || leftType->IsETSNullType() || rightType->IsETSNullType()) { + // Equality expression is always allowed for *magic types* + if (isRelaxedType(leftType) || isRelaxedType(rightType)) { return true; } @@ -651,10 +652,10 @@ static Type *CheckOperatorEqualDynamic(ETSChecker *checker, BinaryArithmOperands } if (otherExp->TsType()->IsETSReferenceType()) { // have to prevent casting dyn_exp via ApplyCast without nullish flag - return checker->GlobalETSNullishObjectType(); + return checker->GlobalETSAnyType(); } checker->LogError(diagnostic::BINOP_DYN_UNIMPLEMENTED, {}, ops.expr->Start()); - return checker->GlobalETSNullishObjectType(); + return checker->GlobalETSAnyType(); } static Type *HandelReferenceBinaryEquality(ETSChecker *checker, BinaryArithmOperands const &ops) diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index a9b83658ec..43db915edd 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -1093,7 +1093,7 @@ std::pair ETSChecker::CheckTestNullishCondition(Type *testedType return {GlobalETSUndefinedType(), RemoveUndefinedType(actualType)}; } - return {GlobalETSNullishType(), GetNonNullishType(actualType)}; + return {GlobalETSUnionUndefinedNull(), GetNonNullishType(actualType)}; } // Auxiliary method to reduce the size of common 'CheckTestSmartCastConditions' function. diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index c5724a9d7e..4fc956301c 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -374,7 +374,7 @@ void ETSChecker::SetUpTypeParameterConstraint(ir::TSTypeParameter *const param) traverseReferenced(param->Constraint()); paramType->SetConstraintType(param->Constraint()->GetType(this)); } else { - paramType->SetConstraintType(GlobalETSNullishObjectType()); + paramType->SetConstraintType(GlobalETSAnyType()); } if (param->DefaultType() != nullptr) { @@ -399,7 +399,7 @@ ETSTypeParameter *ETSChecker::SetUpParameterType(ir::TSTypeParameter *const para paramType->SetDeclNode(param); paramType->SetVariable(param->Variable()); // NOTE: #15026 recursive type parameter workaround - paramType->SetConstraintType(GlobalETSNullishObjectType()); + paramType->SetConstraintType(GlobalETSAnyType()); var->SetTsType(paramType); return paramType; diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 2848d1fa2b..2f70b2d7b0 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -55,8 +55,7 @@ void ETSChecker::CheckTruthinessOfType(ir::Expression *expr) expr->SetTsType(conditionType); - if (conditionType == nullptr || (!conditionType->IsTypeError() && !conditionType->IsConditionalExprType())) { - LogError(diagnostic::NOT_COND_TYPE, {}, expr->Start()); + if (conditionType == nullptr) { return; } @@ -94,6 +93,9 @@ Type *ETSChecker::GetNonNullishType(Type *type) if (type->DefinitelyNotETSNullish()) { return type; } + if (type->IsETSAnyType()) { + return type; + } if (type->IsETSTypeParameter()) { return ProgramAllocator()->New(type->AsETSTypeParameter()); } @@ -116,7 +118,7 @@ Type *ETSChecker::GetNonNullishType(Type *type) Type *ETSChecker::RemoveNullType(Type *const type) { - if (type->DefinitelyNotETSNullish() || type->IsETSUndefinedType()) { + if (type->IsETSAnyType() || type->DefinitelyNotETSNullish() || type->IsETSUndefinedType()) { return type; } @@ -144,7 +146,7 @@ Type *ETSChecker::RemoveNullType(Type *const type) Type *ETSChecker::RemoveUndefinedType(Type *const type) { - if (type->DefinitelyNotETSNullish() || type->IsETSNullType()) { + if (type->IsETSAnyType() || type->DefinitelyNotETSNullish() || type->IsETSNullType()) { return type; } @@ -176,8 +178,12 @@ std::pair ETSChecker::RemoveNullishTypes(Type *type) return {GetGlobalTypesHolder()->GlobalETSNeverType(), type}; } + if (type->IsETSAnyType()) { + return {type, type}; + } + if (type->IsETSTypeParameter()) { - return {GetGlobalTypesHolder()->GlobalETSNullishType(), + return {GetGlobalTypesHolder()->GlobalETSUnionUndefinedNull(), ProgramAllocator()->New(type->AsETSTypeParameter())}; } @@ -251,21 +257,21 @@ static bool MatchConstituentOrConstraint(const Type *type, Pred const &pred) bool Type::PossiblyETSNull() const { return MatchConstituentOrConstraint( - this, [](const Type *t) { return t->IsETSNullType(); }, + this, [](const Type *t) { return t->IsETSAnyType() || t->IsETSNullType(); }, [](const Type *t) { return !t->IsETSNonNullishType(); }); } bool Type::PossiblyETSUndefined() const { return MatchConstituentOrConstraint( - this, [](const Type *t) { return t->IsETSUndefinedType(); }, + this, [](const Type *t) { return t->IsETSAnyType() || t->IsETSUndefinedType(); }, [](const Type *t) { return !t->IsETSNonNullishType(); }); } bool Type::PossiblyETSNullish() const { return MatchConstituentOrConstraint( - this, [](const Type *t) { return t->IsETSNullType() || t->IsETSUndefinedType(); }, + this, [](const Type *t) { return t->IsETSAnyType() || t->IsETSNullType() || t->IsETSUndefinedType(); }, [](const Type *t) { return !t->IsETSNonNullishType(); }); } @@ -287,7 +293,8 @@ bool Type::DefinitelyNotETSNullish() const bool Type::PossiblyETSString() const { return MatchConstituentOrConstraint(this, [](const Type *t) { - return t->IsETSStringType() || (t->IsETSObjectType() && t->AsETSObjectType()->IsGlobalETSObjectType()); + return t->IsETSAnyType() || t->IsETSStringType() || + (t->IsETSObjectType() && t->AsETSObjectType()->IsGlobalETSObjectType()); }); } @@ -308,7 +315,8 @@ bool Type::PossiblyETSValueTyped() const bool Type::PossiblyETSValueTypedExceptNullish() const { return MatchConstituentOrConstraint(this, [](const Type *t) { - return t->IsETSFunctionType() || (t->IsETSObjectType() && IsValueTypedObjectType(t->AsETSObjectType())); + return t->IsETSAnyType() || t->IsETSFunctionType() || + (t->IsETSObjectType() && IsValueTypedObjectType(t->AsETSObjectType())); }); } @@ -328,9 +336,9 @@ bool Type::IsETSMethodType() const static constexpr TypeFlag ETS_SANE_REFERENCE_TYPE = TypeFlag::TYPE_ERROR | TypeFlag::ETS_NULL | TypeFlag::ETS_UNDEFINED | TypeFlag::ETS_OBJECT | TypeFlag::ETS_TYPE_PARAMETER | TypeFlag::WILDCARD | TypeFlag::ETS_NONNULLISH | - TypeFlag::ETS_REQUIRED_TYPE_PARAMETER | TypeFlag::ETS_NEVER | TypeFlag::ETS_UNION | TypeFlag::ETS_ARRAY | - TypeFlag::FUNCTION | TypeFlag::ETS_PARTIAL_TYPE_PARAMETER | TypeFlag::ETS_TUPLE | TypeFlag::ETS_ENUM | - TypeFlag::ETS_READONLY; + TypeFlag::ETS_REQUIRED_TYPE_PARAMETER | TypeFlag::ETS_ANY | TypeFlag::ETS_NEVER | TypeFlag::ETS_UNION | + TypeFlag::ETS_ARRAY | TypeFlag::FUNCTION | TypeFlag::ETS_PARTIAL_TYPE_PARAMETER | TypeFlag::ETS_TUPLE | + TypeFlag::ETS_ENUM | TypeFlag::ETS_READONLY; // Issues if (type->IsETSVoidType()) { // NOTE(vpukhov): #19701 void refactoring @@ -340,7 +348,7 @@ bool Type::IsETSMethodType() const return true; } if (type->IsNeverType()) { // NOTE(vpukhov): #20562 We use ets/never and ts/never simultaneously - return true; + ES2PANDA_UNREACHABLE(); } return type->HasTypeFlag(ETS_SANE_REFERENCE_TYPE); } @@ -1184,7 +1192,7 @@ Type *ETSChecker::MaybeUnboxConditionalInRelation(Type *const objectType) return objectType; } - if ((objectType == nullptr) || !objectType->IsConditionalExprType()) { + if (objectType == nullptr) { return nullptr; } diff --git a/ets2panda/checker/ets/typeConverter.h b/ets2panda/checker/ets/typeConverter.h index 2d0bd3db6c..46635fdc5d 100644 --- a/ets2panda/checker/ets/typeConverter.h +++ b/ets2panda/checker/ets/typeConverter.h @@ -62,7 +62,7 @@ public: template static Type *ConvertConstantType(Type *source, ArenaAllocator *allocator) { - switch (static_cast(source->TypeFlags() & TypeFlag::ETS_TYPE)) { + switch (static_cast(source->TypeFlags() & (TypeFlag::ETS_NUMERIC | TypeFlag::CHAR))) { case TypeFlag::INT: return ConvertConstant(source->AsIntType(), allocator); @@ -95,7 +95,7 @@ public: { ES2PANDA_ASSERT(source->IsETSPrimitiveType() && target->IsETSPrimitiveType() && source->IsConstantType()); - switch (static_cast(target->TypeFlags() & TypeFlag::ETS_TYPE)) { + switch (static_cast(target->TypeFlags() & (TypeFlag::ETS_NUMERIC | TypeFlag::CHAR))) { case TypeFlag::INT: return ConvertConstantType(source, allocator); diff --git a/ets2panda/checker/ets/typeCreation.cpp b/ets2panda/checker/ets/typeCreation.cpp index 4c35d829af..509630ade7 100644 --- a/ets2panda/checker/ets/typeCreation.cpp +++ b/ets2panda/checker/ets/typeCreation.cpp @@ -305,8 +305,8 @@ static ETSObjectType *InitializeGlobalBuiltinObjectType(ETSChecker *checker, Glo auto *objType = setType(GlobalTypeId::ETS_OBJECT_BUILTIN, create())->AsETSObjectType(); auto null = checker->GlobalETSNullType(); auto undef = checker->GlobalETSUndefinedType(); - setType(GlobalTypeId::ETS_NULLISH_OBJECT, checker->CreateETSUnionType({objType, null, undef})); - setType(GlobalTypeId::ETS_NULLISH_TYPE, checker->CreateETSUnionType({null, undef})); + setType(GlobalTypeId::ETS_UNION_UNDEFINED_NULL_OBJECT, checker->CreateETSUnionType({objType, null, undef})); + setType(GlobalTypeId::ETS_UNION_UNDEFINED_NULL, checker->CreateETSUnionType({null, undef})); return objType; } case GlobalTypeId::ETS_STRING_BUILTIN: { diff --git a/ets2panda/checker/ets/utilityTypeHandlers.cpp b/ets2panda/checker/ets/utilityTypeHandlers.cpp index d9e630189d..11d256dedb 100644 --- a/ets2panda/checker/ets/utilityTypeHandlers.cpp +++ b/ets2panda/checker/ets/utilityTypeHandlers.cpp @@ -59,6 +59,10 @@ Type *ETSChecker::HandleUtilityTypeParameterNode(const ir::TSTypeParameterInstan return GlobalTypeError(); } + if (baseType->IsETSAnyType()) { + return baseType; + } + if (utilityType == compiler::Signatures::PARTIAL_TYPE_NAME) { // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) return CreatePartialType(baseType); @@ -115,6 +119,10 @@ Type *ETSChecker::CreatePartialType(Type *const typeToBePartial) { ES2PANDA_ASSERT(typeToBePartial->IsETSReferenceType()); + if (typeToBePartial->IsETSAnyType()) { + return typeToBePartial; + } + if (typeToBePartial->IsETSTypeParameter()) { return CreatePartialTypeParameter(typeToBePartial->AsETSTypeParameter()); } diff --git a/ets2panda/checker/types/ets/etsAnyType.cpp b/ets2panda/checker/types/ets/etsAnyType.cpp new file mode 100644 index 0000000000..811705455b --- /dev/null +++ b/ets2panda/checker/types/ets/etsAnyType.cpp @@ -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. + */ + +#include "etsAnyType.h" + +#include "checker/ETSchecker.h" +#include "checker/ets/conversion.h" +#include "etsTypeParameter.h" + +namespace ark::es2panda::checker { +void ETSAnyType::Identical(TypeRelation *relation, Type *other) +{ + relation->Result(other->IsAnyType()); +} + +void ETSAnyType::AssignmentTarget(TypeRelation *relation, Type *source) +{ + if (!source->IsETSPrimitiveType()) { + relation->Result(true); + return; + } + + if (relation->ApplyBoxing()) { + auto checker = relation->GetChecker()->AsETSChecker(); + relation->GetNode()->AddBoxingUnboxingFlags(checker->GetBoxingFlag(checker->MaybeBoxType(source))); + relation->Result(true); + } +} + +bool ETSAnyType::AssignmentSource(TypeRelation *relation, Type *target) +{ + Identical(relation, target); + return relation->IsTrue(); +} + +void ETSAnyType::Compare([[maybe_unused]] TypeRelation *relation, [[maybe_unused]] Type *other) +{ + ES2PANDA_UNREACHABLE(); +} + +void ETSAnyType::Cast(TypeRelation *relation, Type *target) +{ + if (!relation->InCastingContext()) { + Identical(relation, target); + return; + } + + if (!target->IsETSPrimitiveType()) { + relation->Result(true); + return; + } + + if (relation->ApplyUnboxing()) { + auto *const boxedTarget = relation->GetChecker()->AsETSChecker()->MaybeBoxInRelation(target); + conversion::Unboxing(relation, boxedTarget->AsETSObjectType()); + relation->Result(true); + } +} + +void ETSAnyType::CastTarget(TypeRelation *relation, [[maybe_unused]] Type *source) +{ + AssignmentTarget(relation, source); +} + +void ETSAnyType::IsSubtypeOf(TypeRelation *relation, Type *target) +{ + Identical(relation, target); +} + +void ETSAnyType::IsSupertypeOf(TypeRelation *relation, Type *source) +{ + relation->Result(!source->IsETSPrimitiveType()); +} + +void ETSAnyType::ToString(std::stringstream &ss, [[maybe_unused]] bool precise) const +{ + ss << compiler::Signatures::ANY_TYPE_NAME; +} + +void ETSAnyType::ToAssemblerType(std::stringstream &ss) const +{ + ss << compiler::Signatures::BUILTIN_OBJECT; +} + +TypeFacts ETSAnyType::GetTypeFacts() const +{ + return TypeFacts::NONE; +} + +void ETSAnyType::ToDebugInfoType(std::stringstream &ss) const +{ + ss << ETSObjectType::NameToDescriptor(compiler::Signatures::BUILTIN_OBJECT); +} + +Type *ETSAnyType::Instantiate(ArenaAllocator *allocator, [[maybe_unused]] TypeRelation *relation, + [[maybe_unused]] GlobalTypesHolder *globalTypes) +{ + return allocator->New(); +} +} // namespace ark::es2panda::checker \ No newline at end of file diff --git a/ets2panda/checker/types/ets/etsAnyType.h b/ets2panda/checker/types/ets/etsAnyType.h new file mode 100644 index 0000000000..3dbca0c808 --- /dev/null +++ b/ets2panda/checker/types/ets/etsAnyType.h @@ -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. + */ +#ifndef ES2PANDA_COMPILER_CHECKER_TYPES_ETS_ANY_TYPE_H +#define ES2PANDA_COMPILER_CHECKER_TYPES_ETS_ANY_TYPE_H + +#include "checker/types/type.h" +#include "ir/astNode.h" + +namespace ark::es2panda::checker { +class ETSAnyType : public Type { +public: + ETSAnyType() : Type(TypeFlag::ETS_ANY) {} + + void Identical(TypeRelation *relation, Type *other) override; + void AssignmentTarget(TypeRelation *relation, Type *source) override; + bool AssignmentSource(TypeRelation *relation, Type *target) override; + void Compare(TypeRelation *relation, Type *other) override; + void Cast(TypeRelation *relation, Type *target) override; + void CastTarget(TypeRelation *relation, Type *source) override; + void IsSubtypeOf(TypeRelation *relation, Type *target) override; + void IsSupertypeOf(TypeRelation *relation, Type *source) override; + void ToString(std::stringstream &ss, bool precise) const override; + void ToAssemblerType(std::stringstream &ss) const override; + void ToDebugInfoType([[maybe_unused]] std::stringstream &ss) const override; + + TypeFacts GetTypeFacts() const override; + + Type *Instantiate(ArenaAllocator *allocator, TypeRelation *relation, GlobalTypesHolder *globalTypes) override; + + std::tuple ResolveConditionExpr() const override + { + return {IsConstantType(), false}; + } +}; +} // namespace ark::es2panda::checker + +#endif diff --git a/ets2panda/checker/types/ets/etsFunctionType.cpp b/ets2panda/checker/types/ets/etsFunctionType.cpp index 1df9fd28ea..288967ac2a 100644 --- a/ets2panda/checker/types/ets/etsFunctionType.cpp +++ b/ets2panda/checker/types/ets/etsFunctionType.cpp @@ -73,7 +73,9 @@ static ETSObjectType *FunctionTypeToFunctionalInterfaceType(ETSChecker *checker, if (signature->RestVar() != nullptr) { auto *functionN = checker->GlobalBuiltinFunctionType(arity, true)->AsETSObjectType(); auto *substitution = checker->NewSubstitution(); - auto *elementType = checker->GetElementTypeOfArray(signature->RestVar()->TsType()); + auto *elementType = !signature->RestVar()->TsType()->IsETSTupleType() + ? checker->GetElementTypeOfArray(signature->RestVar()->TsType()) + : checker->GlobalETSAnyType(); substitution->emplace(functionN->TypeArguments()[0]->AsETSTypeParameter(), checker->MaybeBoxType(elementType)); return functionN->Substitute(checker->Relation(), substitution, true, isExtensionHack); } diff --git a/ets2panda/checker/types/ets/types.h b/ets2panda/checker/types/ets/types.h index 89d59b801e..68b9f0079e 100644 --- a/ets2panda/checker/types/ets/types.h +++ b/ets2panda/checker/types/ets/types.h @@ -40,6 +40,7 @@ #include "etsNullishTypes.h" #include "checker/types/signature.h" #include "etsReadonlyType.h" +#include "etsAnyType.h" #include "etsNeverType.h" #endif /* TYPES_H */ diff --git a/ets2panda/checker/types/globalTypesHolder.cpp b/ets2panda/checker/types/globalTypesHolder.cpp index 784aa977a4..300e9b3fbf 100644 --- a/ets2panda/checker/types/globalTypesHolder.cpp +++ b/ets2panda/checker/types/globalTypesHolder.cpp @@ -48,6 +48,7 @@ #include "checker/types/ets/etsNullishTypes.h" #include "checker/types/ets/etsObjectType.h" #include "checker/types/ets/wildcardType.h" +#include "checker/types/ets/etsAnyType.h" #include "checker/types/ets/etsNeverType.h" #include "util/helpers.h" @@ -148,11 +149,13 @@ void GlobalTypesHolder::AddEtsSpecificTypes(ArenaAllocator *allocator) globalTypes_[static_cast(GlobalTypeId::ETS_UNDEFINED)] = allocator->New(); globalTypes_[static_cast(GlobalTypeId::ETS_WILDCARD)] = allocator->New(); globalTypes_[static_cast(GlobalTypeId::TYPE_ERROR)] = allocator->New(); + globalTypes_[static_cast(GlobalTypeId::ETS_ANY)] = allocator->New(); globalTypes_[static_cast(GlobalTypeId::ETS_NEVER)] = allocator->New(); } void GlobalTypesHolder::AddEtsSpecificBuiltinTypes() { + builtinNameMappings_.emplace("Any", GlobalTypeId::ETS_ANY); builtinNameMappings_.emplace("Boolean", GlobalTypeId::ETS_BOOLEAN_BUILTIN); builtinNameMappings_.emplace("Byte", GlobalTypeId::ETS_BYTE_BUILTIN); builtinNameMappings_.emplace("Char", GlobalTypeId::ETS_CHAR_BUILTIN); @@ -403,19 +406,24 @@ Type *GlobalTypesHolder::GlobalETSUndefinedType() return globalTypes_.at(static_cast(GlobalTypeId::ETS_UNDEFINED)); } +Type *GlobalTypesHolder::GlobalETSAnyType() +{ + return globalTypes_.at(static_cast(GlobalTypeId::ETS_ANY)); +} + Type *GlobalTypesHolder::GlobalETSNeverType() { return globalTypes_.at(static_cast(GlobalTypeId::ETS_NEVER)); } -Type *GlobalTypesHolder::GlobalETSNullishObjectType() +Type *GlobalTypesHolder::GlobalETSUnionUndefinedNullObject() { - return globalTypes_.at(static_cast(GlobalTypeId::ETS_NULLISH_OBJECT)); + return globalTypes_.at(static_cast(GlobalTypeId::ETS_UNION_UNDEFINED_NULL_OBJECT)); } -Type *GlobalTypesHolder::GlobalETSNullishType() +Type *GlobalTypesHolder::GlobalETSUnionUndefinedNull() { - return globalTypes_.at(static_cast(GlobalTypeId::ETS_NULLISH_TYPE)); + return globalTypes_.at(static_cast(GlobalTypeId::ETS_UNION_UNDEFINED_NULL)); } Type *GlobalTypesHolder::GlobalWildcardType() diff --git a/ets2panda/checker/types/globalTypesHolder.h b/ets2panda/checker/types/globalTypesHolder.h index 2242097f8d..635c8b080e 100644 --- a/ets2panda/checker/types/globalTypesHolder.h +++ b/ets2panda/checker/types/globalTypesHolder.h @@ -57,9 +57,10 @@ enum class GlobalTypeId : std::size_t { ETS_OBJECT_BUILTIN, ETS_NULL, ETS_UNDEFINED, - ETS_NULLISH_TYPE, + ETS_UNION_UNDEFINED_NULL, + ETS_ANY, ETS_NEVER, - ETS_NULLISH_OBJECT, + ETS_UNION_UNDEFINED_NULL_OBJECT, ETS_WILDCARD, ETS_BOOLEAN_BUILTIN, ETS_BYTE_BUILTIN, @@ -267,9 +268,10 @@ public: Type *GlobalETSObjectType(); Type *GlobalETSNullType(); Type *GlobalETSUndefinedType(); + Type *GlobalETSAnyType(); Type *GlobalETSNeverType(); - Type *GlobalETSNullishType(); - Type *GlobalETSNullishObjectType(); + Type *GlobalETSUnionUndefinedNull(); + Type *GlobalETSUnionUndefinedNullObject(); Type *GlobalWildcardType(); Type *GlobalETSBooleanBuiltinType(); Type *GlobalByteBuiltinType(); diff --git a/ets2panda/checker/types/type.h b/ets2panda/checker/types/type.h index 1a0895b37a..d6d1fb2f7d 100644 --- a/ets2panda/checker/types/type.h +++ b/ets2panda/checker/types/type.h @@ -186,11 +186,6 @@ public: return reinterpret_cast(this); } - bool IsConditionalExprType() const - { - return HasTypeFlag(TypeFlag::CONDITION_EXPRESSION_TYPE); - } - bool IsConstantType() const { return HasTypeFlag(checker::TypeFlag::CONSTANT); diff --git a/ets2panda/checker/types/typeFlag.h b/ets2panda/checker/types/typeFlag.h index 86e149f3a3..feea58ce12 100644 --- a/ets2panda/checker/types/typeFlag.h +++ b/ets2panda/checker/types/typeFlag.h @@ -48,7 +48,6 @@ enum class TypeFlag : uint64_t { INTERSECTION = 1ULL << 19ULL, // x: a & b INDEX = 1ULL << 20ULL, // keyof x INDEX_ACCESS = 1ULL << 21ULL, // x[a] - CONDITIONAL = 1ULL << 22ULL, // x extends a ? b : c TEMPLATE_LITERAL = 1ULL << 23ULL, // x: `hello ${World}` ANY = 1ULL << 24ULL, // x: any ARRAY = 1ULL << 25ULL, // x: number[] @@ -88,14 +87,11 @@ enum class TypeFlag : uint64_t { ETS_PARTIAL_TYPE_PARAMETER = 1ULL << 59ULL, // ETS Partial type parameter TYPE_ERROR = 1ULL << 60ULL, // type error ETS_TYPE_ALIAS = 1ULL << 61ULL, // ETS Type alias + ETS_ANY = 1ULL << 22ULL, // ETS any, the value was *stolen* from the CONDITIONAL type kind ETS_NEVER = 1ULL << 62ULL, // ETS never ETS_METHOD = 1ULL << 63ULL, // ETS method (or function in module) (possibly overloaded) ETS_DYNAMIC_TYPE = ETS_OBJECT | ETS_DYNAMIC_FLAG, ETS_DYNAMIC_FUNCTION_TYPE = FUNCTION | ETS_DYNAMIC_FLAG, - ETS_TYPE = BYTE | SHORT | INT | LONG | FLOAT | DOUBLE | CHAR | ETS_BOOLEAN | ETS_VOID | ETS_OBJECT | ETS_ARRAY | - FUNCTION | WILDCARD | ETS_TYPE_PARAMETER | ETS_DYNAMIC_TYPE | ETS_UNION | ETS_NULL | ETS_UNDEFINED | - ETS_NONNULLISH | ETS_READONLY | ETS_REQUIRED_TYPE_PARAMETER | ETS_PARTIAL_TYPE_PARAMETER | ETS_NEVER | - ETS_TUPLE, ETS_INTEGRAL_NUMERIC = BYTE | SHORT | INT | LONG, ETS_FLOATING_POINT = FLOAT | DOUBLE, ETS_NUMERIC = ETS_INTEGRAL_NUMERIC | ETS_FLOATING_POINT, @@ -123,9 +119,6 @@ enum class TypeFlag : uint64_t { VALID_ARITHMETIC_TYPE = ANY | NUMBER_LIKE | BIGINT_LIKE | ENUM, UNIT = LITERAL | UNDEFINED | NULL_TYPE, GETTER_SETTER = GETTER | SETTER, - CONDITION_EXPRESSION_TYPE = ETS_NULL | ETS_UNDEFINED | ETS_OBJECT | ETS_ARRAY | ETS_UNION | CONSTANT | BYTE | CHAR | - SHORT | INT | LONG | FLOAT | DOUBLE | ETS_BOOLEAN | ETS_INT_ENUM | ETS_STRING_ENUM | - FUNCTION | ETS_TUPLE, }; } // namespace ark::es2panda::checker diff --git a/ets2panda/checker/types/typeMapping.h b/ets2panda/checker/types/typeMapping.h index 4964190828..a856a49bdb 100644 --- a/ets2panda/checker/types/typeMapping.h +++ b/ets2panda/checker/types/typeMapping.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 @@ -53,6 +53,7 @@ _(TypeFlag::ETS_VOID, ETSVoidType) \ _(TypeFlag::ETS_NULL, ETSNullType) \ _(TypeFlag::ETS_UNDEFINED, ETSUndefinedType) \ + _(TypeFlag::ETS_ANY, ETSAnyType) \ _(TypeFlag::ETS_NEVER, ETSNeverType) \ _(TypeFlag::FUNCTION, ETSFunctionType) \ _(TypeFlag::ETS_OBJECT, ETSObjectType) \ diff --git a/ets2panda/compiler/base/condition.cpp b/ets2panda/compiler/base/condition.cpp index c8a7d0de4d..dc0b40e8dc 100644 --- a/ets2panda/compiler/base/condition.cpp +++ b/ets2panda/compiler/base/condition.cpp @@ -235,7 +235,6 @@ void Condition::Compile(ETSGen *etsg, const ir::Expression *expr, Label *falseLa etsg->BranchIfTrue(expr, falseLabel); return; } - ES2PANDA_ASSERT(expr->TsType()->IsConditionalExprType()); expr->Compile(etsg); etsg->ApplyConversion(expr, etsg->Checker()->GlobalETSBooleanType()); etsg->ResolveConditionalResultIfFalse(expr, falseLabel); diff --git a/ets2panda/compiler/core/ETSCompiler.cpp b/ets2panda/compiler/core/ETSCompiler.cpp index 76dc7e8bdf..c7bf4dca5f 100644 --- a/ets2panda/compiler/core/ETSCompiler.cpp +++ b/ets2panda/compiler/core/ETSCompiler.cpp @@ -1665,6 +1665,7 @@ void ETSCompiler::CompileCast(const ir::TSAsExpression *expr) const case checker::TypeFlag::ETS_NONNULLISH: case checker::TypeFlag::ETS_PARTIAL_TYPE_PARAMETER: case checker::TypeFlag::ETS_UNION: + case checker::TypeFlag::ETS_ANY: case checker::TypeFlag::ETS_NULL: case checker::TypeFlag::ETS_UNDEFINED: { etsg->CastToReftype(expr, targetType, expr->isUncheckedCast_); diff --git a/ets2panda/compiler/core/ETSGen.cpp b/ets2panda/compiler/core/ETSGen.cpp index e539dffc83..84960c75e6 100644 --- a/ets2panda/compiler/core/ETSGen.cpp +++ b/ets2panda/compiler/core/ETSGen.cpp @@ -692,18 +692,6 @@ void ETSGen::ReturnAcc(const ir::AstNode *node) } } -static bool IsAnyReferenceSupertype(checker::Type const *type) -{ - if (!type->IsETSUnionType()) { - return false; - } - auto const &constituent = type->AsETSUnionType()->ConstituentTypes(); - return constituent.size() == 3U && std::all_of(constituent.begin(), constituent.end(), [](checker::Type *t) { - return t->IsETSUndefinedType() || t->IsETSNullType() || - (t->IsETSObjectType() && t->AsETSObjectType()->IsGlobalETSObjectType()); - }); // CC-OFF(G.FMT.02) project code style -} - static bool IsNullUnsafeObjectType(checker::Type const *type) { return type->IsETSObjectType() && type->AsETSObjectType()->IsGlobalETSObjectType(); @@ -741,10 +729,10 @@ void ETSGen::IsInstanceDynamic(const ir::BinaryExpression *const node, const VRe Language lang = rhsType->AsETSDynamicType()->Language(); VReg dynTypeReg = MoveAccToReg(node); LoadAccumulator(node, srcReg); - Sa().Emit(node, Checker()->GlobalBuiltinDynamicType(lang)->AssemblerName()); + EmitIsInstance(node, Checker()->GlobalBuiltinDynamicType(lang)->AssemblerName()); BranchIfFalse(node, ifFalse); LoadAccumulator(node, srcReg); - Sa().Emit(node, Checker()->GlobalBuiltinDynamicType(lang)->AssemblerName()); + EmitCheckCast(node, Checker()->GlobalBuiltinDynamicType(lang)->AssemblerName()); CallExact(node, Signatures::BUILTIN_JSRUNTIME_INSTANCE_OF_DYNAMIC, srcReg, dynTypeReg); SetLabel(node, ifFalse); } else { @@ -798,7 +786,7 @@ void ETSGen::TestIsInstanceConstituent(const ir::AstNode *const node, std::tuple break; case checker::TypeFlag::ETS_OBJECT: if (!IsNullUnsafeObjectType(target)) { - Sa().Emit(node, ToAssemblerType(target)); + EmitIsInstance(node, ToAssemblerType(target)); BranchIfTrue(node, ifTrue); break; } @@ -810,7 +798,7 @@ void ETSGen::TestIsInstanceConstituent(const ir::AstNode *const node, std::tuple case checker::TypeFlag::ETS_ARRAY: case checker::TypeFlag::ETS_TUPLE: case checker::TypeFlag::FUNCTION: { - Sa().Emit(node, ToAssemblerType(target)); + EmitIsInstance(node, ToAssemblerType(target)); BranchIfTrue(node, ifTrue); break; } @@ -858,7 +846,7 @@ void ETSGen::IsInstance(const ir::AstNode *const node, const VReg srcReg, const target = Checker()->GetApparentType(target); ES2PANDA_ASSERT(target->IsETSReferenceType()); - if (IsAnyReferenceSupertype(target)) { // should be IsSupertypeOf(target, source) + if (target->IsETSAnyType()) { // should be IsSupertypeOf(target, source) LoadAccumulatorBoolean(node, true); return; } @@ -885,7 +873,7 @@ void ETSGen::InternalIsInstance(const ir::AstNode *node, const es2panda::checker { ES2PANDA_ASSERT(target->IsETSObjectType() || target->IsETSArrayType()); if (!IsNullUnsafeObjectType(target)) { - Sa().Emit(node, ToAssemblerType(target)); + EmitIsInstance(node, ToAssemblerType(target)); SetAccumulatorType(Checker()->GlobalETSBooleanType()); } else { LoadAccumulatorBoolean(node, true); @@ -897,7 +885,7 @@ void ETSGen::InternalCheckCast(const ir::AstNode *node, const es2panda::checker: { ES2PANDA_ASSERT(target->IsETSObjectType() || target->IsETSArrayType() || target->IsETSTupleType()); if (!IsNullUnsafeObjectType(target)) { - Sa().Emit(node, ToAssemblerType(target)); + EmitCheckCast(node, ToAssemblerType(target)); } SetAccumulatorType(target); } @@ -951,7 +939,7 @@ void ETSGen::CheckedReferenceNarrowing(const ir::AstNode *node, const checker::T target = Checker()->GetApparentType(target); ES2PANDA_ASSERT(target->IsETSReferenceType()); - if (IsAnyReferenceSupertype(target)) { // should be IsSupertypeOf(target, source) + if (target->IsETSAnyType()) { // should be IsSupertypeOf(target, source) SetAccumulatorType(target); return; } @@ -973,7 +961,7 @@ void ETSGen::CheckedReferenceNarrowing(const ir::AstNode *node, const checker::T SetLabel(node, ifTrue); LoadAccumulator(node, srcReg); // Verifier can't infer type if isinstance met, help him - Sa().Emit(node, ToAssemblerType(target)); + EmitCheckCast(node, ToAssemblerType(target)); SetAccumulatorType(target); } @@ -1734,7 +1722,7 @@ void ETSGen::CastDynamicToObject(const ir::AstNode *node, const checker::Type *t // and this function will need to be refactored in the future. if (targetType->IsETSArrayType() || targetType->IsETSObjectType() || targetType->IsETSTypeParameter() || targetType->IsETSUnionType() || targetType->IsETSFunctionType() || targetType->DefinitelyETSNullish() || - targetType->IsETSTupleType()) { + targetType->IsETSTupleType() || targetType->IsETSAnyType()) { auto lang = GetAccumulatorType()->AsETSDynamicType()->Language(); auto methodName = compiler::Signatures::Dynamic::GetObjectBuiltin(lang); @@ -1749,7 +1737,7 @@ void ETSGen::CastDynamicToObject(const ir::AstNode *node, const checker::Type *t StoreAccumulator(node, typeReg); Ra().Emit(node, methodName, dynObjReg, typeReg); - Sa().Emit(node, assemblerType); // trick verifier + EmitCheckCast(node, assemblerType); // trick verifier SetAccumulatorType(targetType); return; } @@ -1794,6 +1782,7 @@ void ETSGen::CastToDynamic(const ir::AstNode *node, const checker::ETSDynamicTyp case checker::TypeFlag::ETS_NONNULLISH: case checker::TypeFlag::ETS_PARTIAL_TYPE_PARAMETER: case checker::TypeFlag::ETS_UNION: // NOTE(vpukhov): refine dynamic type cast rules + case checker::TypeFlag::ETS_ANY: if (GetAccumulatorType()->IsETSStringType()) { methodName = compiler::Signatures::Dynamic::NewStringBuiltin(type->Language()); break; @@ -2129,7 +2118,7 @@ void ETSGen::ResolveConditionalResultReference(const ir::AstNode *node) compiler::VReg objReg = AllocReg(); StoreAccumulator(node, objReg); - Sa().Emit(node, Checker()->GlobalBuiltinETSStringType()->AssemblerName()); + EmitIsInstance(node, Checker()->GlobalBuiltinETSStringType()->AssemblerName()); BranchIfTrue(node, isString); Sa().Emit(node, 1); Branch(node, end); @@ -2305,10 +2294,9 @@ void ETSGen::BranchIfNotNullish(const ir::AstNode *node, Label *ifNotNullish) void ETSGen::AssumeNonNullish(const ir::AstNode *node, checker::Type const *targetType) { auto const *nullishType = GetAccumulatorType(); - if (nullishType->PossiblyETSNull() && - ToAssemblerType(targetType) != ToAssemblerType(Checker()->GlobalETSObjectType())) { + if (nullishType->PossiblyETSNull()) { // clear 'null' dataflow - Sa().Emit(node, ToAssemblerType(targetType)); + EmitCheckCast(node, ToAssemblerType(targetType)); } SetAccumulatorType(targetType); } @@ -2683,7 +2671,6 @@ void ETSGen::Negate(const ir::AstNode *node) void ETSGen::LogicalNot(const ir::AstNode *node) { - ES2PANDA_ASSERT(GetAccumulatorType()->IsConditionalExprType()); ResolveConditionalResultIfFalse(node); Sa().Emit(node, 1); SetAccumulatorType(Checker()->GlobalETSBooleanType()); diff --git a/ets2panda/compiler/core/ETSGen.h b/ets2panda/compiler/core/ETSGen.h index dcc6d78ab1..6b3400e02c 100644 --- a/ets2panda/compiler/core/ETSGen.h +++ b/ets2panda/compiler/core/ETSGen.h @@ -477,6 +477,22 @@ private: #endif // PANDA_WITH_ETS } + void EmitCheckCast(const ir::AstNode *node, util::StringView target) + { + if (target != Signatures::BUILTIN_OBJECT) { + Sa().Emit(node, target); + } + } + + void EmitIsInstance(const ir::AstNode *node, util::StringView target) + { + if (target != Signatures::BUILTIN_OBJECT) { + Sa().Emit(node, target); + } else { + LoadAccumulatorBoolean(node, true); + } + } + template void EmitEtsEquals([[maybe_unused]] const ir::AstNode *node, [[maybe_unused]] const VReg lhs, [[maybe_unused]] const VReg rhs) diff --git a/ets2panda/compiler/lowering/ets/arrayLiteralLowering.cpp b/ets2panda/compiler/lowering/ets/arrayLiteralLowering.cpp index a9aa187de8..a933800ade 100644 --- a/ets2panda/compiler/lowering/ets/arrayLiteralLowering.cpp +++ b/ets2panda/compiler/lowering/ets/arrayLiteralLowering.cpp @@ -40,7 +40,7 @@ ArenaVector ArrayLiteralLowering::GenerateDefaultCallToConstruc { std::stringstream ss; std::vector newStmts; - if (!eleType->IsETSUnionType()) { + if (!eleType->IsETSUnionType() && !eleType->IsETSAnyType()) { auto *indexSymbol = Gensym(Allocator()); auto *lengthSymbol = Gensym(Allocator()); auto *typeNode = checker_->AllocNode(eleType, Allocator()); diff --git a/ets2panda/compiler/lowering/ets/declareOverloadLowering.cpp b/ets2panda/compiler/lowering/ets/declareOverloadLowering.cpp index 613fcf10d2..b9679b253f 100644 --- a/ets2panda/compiler/lowering/ets/declareOverloadLowering.cpp +++ b/ets2panda/compiler/lowering/ets/declareOverloadLowering.cpp @@ -30,7 +30,7 @@ void GenerateOverloadHelperParams(public_lib::Context *ctx, uint32_t minArg, siz if (!hasRestVar) { for (size_t idx = 0; idx < maxArg; ++idx) { auto *id = Gensym(allocator); - auto *typeAnnotation = ctx->AllocNode(checker->GlobalETSNullishObjectType(), allocator); + auto *typeAnnotation = ctx->AllocNode(checker->GlobalETSAnyType(), allocator); id->SetTsTypeAnnotation(typeAnnotation); typeAnnotation->SetParent(id); auto *param = ctx->AllocNode(id, false, allocator); @@ -42,7 +42,7 @@ void GenerateOverloadHelperParams(public_lib::Context *ctx, uint32_t minArg, siz auto *restIdent = Gensym(allocator); auto *spread = ctx->AllocNode(ir::AstNodeType::REST_ELEMENT, allocator, restIdent); - auto *arr = checker->CreateETSArrayType(checker->GlobalETSNullishObjectType(), false); + auto *arr = checker->CreateETSArrayType(checker->GlobalETSAnyType(), false); auto *typeAnnotation = ctx->AllocNode(arr, allocator); spread->SetTsTypeAnnotation(typeAnnotation); @@ -68,7 +68,7 @@ void BuildOverloadHelperFunction(public_lib::Context *ctx, ir::MethodDefinition auto params = ArenaVector(allocator->Adapter()); GenerateOverloadHelperParams(ctx, minArg, maxArg, hasRestVar, params); - auto *returnType = returnVoid ? checker->GlobalVoidType() : checker->GlobalETSNullishObjectType(); + auto *returnType = returnVoid ? checker->GlobalVoidType() : checker->GlobalETSAnyType(); auto *returnAnno = ctx->AllocNode(returnType, allocator); ir::ScriptFunctionFlags functionFlag = method->Function()->Flags(); diff --git a/ets2panda/compiler/lowering/ets/enumPostCheckLowering.cpp b/ets2panda/compiler/lowering/ets/enumPostCheckLowering.cpp index 6e555c258c..c210549955 100644 --- a/ets2panda/compiler/lowering/ets/enumPostCheckLowering.cpp +++ b/ets2panda/compiler/lowering/ets/enumPostCheckLowering.cpp @@ -209,7 +209,7 @@ ir::Expression *EnumPostCheckLoweringPhase::HandleEnumTypeCasting(checker::Type // Generate fromValue call; if (type->IsETSEnumType()) { auto exprType = expr->TsType(); - if (exprType->IsETSEnumType() || + if (exprType->IsETSEnumType() || exprType->IsETSAnyType() || (exprType->IsETSObjectType() && exprType->AsETSObjectType()->IsGlobalETSObjectType())) { return expr; } diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index df7f1a1a0b..b34f08ab1c 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -387,7 +387,7 @@ static ir::MethodDefinition *CreateCallee(public_lib::Context *ctx, ir::ArrowFun auto calleeName = lambda->Function()->IsAsyncFunc() ? (util::UString {checker::ETSChecker::GetAsyncImplName(info->name), allocator}).View() : info->name; - auto *forcedReturnType = lambda->Function()->IsAsyncFunc() ? checker->GlobalETSNullishObjectType() : nullptr; + auto *forcedReturnType = lambda->Function()->IsAsyncFunc() ? checker->GlobalETSAnyType() : nullptr; CalleeMethodInfo cmInfo; cmInfo.calleeName = calleeName; @@ -536,10 +536,9 @@ static ArenaVector CreateRestArgumentsArrayReall << "}"; args = parser->CreateFormattedStatement( statements.str(), restParameterIndex, tmpArray, elementType, elementType, lciInfo->restParameterIdentifier, - lciInfo->restArgumentIdentifier, tmpArray, elementType, spreadArrIterator, - checker->GlobalETSNullishObjectType(), lciInfo->restParameterIdentifier, lciInfo->restArgumentIdentifier, - restParameterIndex, spreadArrIterator, checker->MaybeBoxType(elementType), elementType, restParameterIndex, - restParameterIndex); + lciInfo->restArgumentIdentifier, tmpArray, elementType, spreadArrIterator, checker->GlobalETSAnyType(), + lciInfo->restParameterIdentifier, lciInfo->restArgumentIdentifier, restParameterIndex, spreadArrIterator, + checker->MaybeBoxType(elementType), elementType, restParameterIndex, restParameterIndex); } else { auto *typeNode = allocator->New( checker->GetElementTypeOfArray(lciInfo->lambdaSignature->RestVar()->TsType()), allocator); @@ -556,7 +555,7 @@ static ArenaVector CreateRestArgumentsArrayReall << "}"; args = parser->CreateFormattedStatement( statements.str(), restParameterIndex, lciInfo->restArgumentIdentifier, typeNode, - lciInfo->restParameterIdentifier, spreadArrIterator, checker->GlobalETSNullishObjectType(), + lciInfo->restParameterIdentifier, spreadArrIterator, checker->GlobalETSAnyType(), lciInfo->restParameterIdentifier, lciInfo->restArgumentIdentifier, restParameterIndex, spreadArrIterator, checker->MaybeBoxType(elementType), restParameterIndex, restParameterIndex); } @@ -569,13 +568,14 @@ static void CreateInvokeMethodRestParameter(public_lib::Context *ctx, LambdaClas { auto *allocator = ctx->allocator; auto *checker = ctx->checker->AsETSChecker(); - auto *anyType = checker->GlobalETSNullishObjectType(); auto *restIdent = Gensym(allocator); lciInfo->restParameterIdentifier = restIdent->Name(); lciInfo->restArgumentIdentifier = GenName(allocator).View(); auto *spread = allocator->New(ir::AstNodeType::REST_ELEMENT, allocator, restIdent); - auto *arr = checker->CreateETSArrayType(anyType); + auto *arr = lciInfo->lambdaSignature->RestVar()->TsType()->IsETSTupleType() + ? lciInfo->lambdaSignature->RestVar()->TsType() + : checker->CreateETSArrayType(checker->GlobalETSAnyType()); auto *typeAnnotation = allocator->New(arr, allocator); spread->SetTsTypeAnnotation(typeAnnotation); @@ -672,7 +672,7 @@ static ir::BlockStatement *CreateLambdaClassInvokeBody(public_lib::Context *ctx, auto *allocator = ctx->allocator; auto *parser = ctx->parser->AsETSParser(); auto *checker = ctx->checker->AsETSChecker(); - auto *anyType = checker->GlobalETSNullishObjectType(); + auto *anyType = checker->GlobalETSAnyType(); auto *call = CreateCallForLambdaClassInvoke(ctx, info, lciInfo, wrapToObject); auto bodyStmts = CreateRestArgumentsArrayReallocation(ctx, lciInfo); @@ -700,7 +700,7 @@ static void CreateLambdaClassInvokeMethod(public_lib::Context *ctx, LambdaInfo c { auto *allocator = ctx->allocator; auto *checker = ctx->checker->AsETSChecker(); - auto *anyType = checker->GlobalETSNullishObjectType(); + auto *anyType = checker->GlobalETSAnyType(); auto params = ArenaVector(allocator->Adapter()); for (size_t idx = 0; idx < lciInfo->arity; ++idx) { diff --git a/ets2panda/compiler/scripts/signatures.yaml b/ets2panda/compiler/scripts/signatures.yaml index 496aa8e961..c6bfa42dbc 100644 --- a/ets2panda/compiler/scripts/signatures.yaml +++ b/ets2panda/compiler/scripts/signatures.yaml @@ -159,6 +159,8 @@ defines: ref: ARRAY - name: '' ref: PROPERTY + - name: 'Any' + ref: ANY_TYPE_NAME - name: 'never' ref: NEVER_TYPE_NAME - name: 'SOURCE' diff --git a/ets2panda/ir/ets/etsTypeReferencePart.cpp b/ets2panda/ir/ets/etsTypeReferencePart.cpp index 3c7089b10f..5c951356de 100644 --- a/ets2panda/ir/ets/etsTypeReferencePart.cpp +++ b/ets2panda/ir/ets/etsTypeReferencePart.cpp @@ -93,6 +93,62 @@ checker::VerifiedType ETSTypeReferencePart::Check(checker::ETSChecker *checker) return {this, checker->GetAnalyzer()->Check(this)}; } +static checker::Type *HandleFixedArrayType(checker::ETSChecker *const checker, ETSTypeReferencePart *ref) +{ + auto typeParams = ref->TypeParams(); + if (typeParams == nullptr || typeParams->Params().size() != 1) { + checker->LogError(diagnostic::FIXED_ARRAY_PARAM_ERROR, {}, ref->Start()); + return checker->GlobalTypeError(); + } + return checker->CreateETSArrayType(typeParams->Params()[0]->GetType(checker), ref->IsReadonlyType()); +} + +static checker::Type *HandlePartialType(checker::ETSChecker *const checker, ETSTypeReferencePart *ref) +{ + auto *baseType = checker->HandleUtilityTypeParameterNode(ref->TypeParams(), ref->GetIdent()); + if (baseType != nullptr && baseType->IsETSObjectType() && !baseType->AsETSObjectType()->TypeArguments().empty()) { + // we treat Partial> class as a different copy from A now, + // but not a generic type param for Partial<> + if (ref->TypeParams() != nullptr) { + for (auto &typeRef : ref->TypeParams()->Params()) { + checker::InstantiationContext ctx(checker, baseType->AsETSObjectType(), + typeRef->AsETSTypeReference()->Part()->TypeParams(), ref->Start()); + baseType = ctx.Result(); + } + } + } + return baseType; +} + +static checker::Type *CheckPredefinedBuiltinTypes(checker::ETSChecker *const checker, ETSTypeReferencePart *ref) +{ + auto const ident = ref->GetIdent(); + if (ident->Name() == compiler::Signatures::ANY_TYPE_NAME) { + return checker->GlobalETSAnyType(); + } + if (ident->Name() == compiler::Signatures::UNDEFINED) { + return checker->GlobalETSUndefinedType(); + } + if (ident->Name() == compiler::Signatures::NULL_LITERAL) { + return checker->GlobalETSNullType(); + } + if (ident->Name() == compiler::Signatures::NEVER_TYPE_NAME) { + return checker->GlobalETSNeverType(); + } + + if (ident->Name() == compiler::Signatures::READONLY_TYPE_NAME || + ident->Name() == compiler::Signatures::REQUIRED_TYPE_NAME) { + return checker->HandleUtilityTypeParameterNode(ref->TypeParams(), ident); + } + if (ident->Name() == compiler::Signatures::PARTIAL_TYPE_NAME) { + return HandlePartialType(checker, ref); + } + if (ident->Name() == compiler::Signatures::FIXED_ARRAY_TYPE_NAME) { + return HandleFixedArrayType(checker, ref); + } + return nullptr; +} + [[maybe_unused]] static bool CheckTypeAliaLoop(ETSTypeReferencePart *ref, varbinder::Variable *variable) { auto typeAliasDecl = variable->Declaration()->Node()->AsTSTypeAliasDeclaration(); @@ -120,7 +176,7 @@ checker::Type *ETSTypeReferencePart::HandleInternalTypes(checker::ETSChecker *co { ES2PANDA_ASSERT(name_->IsIdentifier() || name_->IsTSQualifiedName()); - Identifier *ident = GetIdent(); + Identifier *const ident = GetIdent(); varbinder::Variable *variable = nullptr; if (name_->IsIdentifier()) { @@ -143,29 +199,8 @@ checker::Type *ETSTypeReferencePart::HandleInternalTypes(checker::ETSChecker *co variable->Declaration()->AsTypeAliasDecl()->Node()->AsTSTypeAliasDeclaration()); } - if (ident->Name() == compiler::Signatures::UNDEFINED) { - return checker->GlobalETSUndefinedType(); - } - - if (ident->Name() == compiler::Signatures::NULL_LITERAL) { - return checker->GlobalETSNullType(); - } - - if (ident->Name() == compiler::Signatures::NEVER_TYPE_NAME) { - return checker->GlobalETSNeverType(); - } - - if (ident->Name() == compiler::Signatures::READONLY_TYPE_NAME || - ident->Name() == compiler::Signatures::REQUIRED_TYPE_NAME) { - return checker->HandleUtilityTypeParameterNode(typeParams_, ident); - } - - if (ident->Name() == compiler::Signatures::PARTIAL_TYPE_NAME) { - return HandlePartialType(checker, ident); - } - - if (ident->Name() == compiler::Signatures::FIXED_ARRAY_TYPE_NAME) { - return HandleFixedArrayType(checker); + if (auto res = CheckPredefinedBuiltinTypes(checker, this); res != nullptr) { + return res; } if (ident->IsErrorPlaceHolder()) { @@ -175,35 +210,6 @@ checker::Type *ETSTypeReferencePart::HandleInternalTypes(checker::ETSChecker *co return nullptr; } -checker::Type *ETSTypeReferencePart::HandleFixedArrayType(checker::ETSChecker *const checker) -{ - if (typeParams_ == nullptr || typeParams_->Params().size() != 1) { - checker->LogError(diagnostic::FIXED_ARRAY_PARAM_ERROR, {}, Start()); - return checker->GlobalTypeError(); - } - checker::Type *type = checker->CreateETSArrayType(typeParams_->Params()[0]->GetType(checker), IsReadonlyType()); - SetTsType(type); - return type; -} - -checker::Type *ETSTypeReferencePart::HandlePartialType(checker::ETSChecker *const checker, - const Identifier *const ident) -{ - auto *baseType = checker->HandleUtilityTypeParameterNode(typeParams_, ident); - if (baseType != nullptr && baseType->IsETSObjectType() && !baseType->AsETSObjectType()->TypeArguments().empty()) { - // we treat Partial> class as a different copy from A now, - // but not a generic type param for Partial<> - if (typeParams_ != nullptr) { - for (auto &typeRef : typeParams_->Params()) { - checker::InstantiationContext ctx(checker, baseType->AsETSObjectType(), - typeRef->AsETSTypeReference()->Part()->typeParams_, Start()); - baseType = ctx.Result(); - } - } - } - return baseType; -} - checker::Type *ETSTypeReferencePart::GetType(checker::ETSChecker *checker) { if (TypeParams() != nullptr) { diff --git a/ets2panda/ir/ets/etsTypeReferencePart.h b/ets2panda/ir/ets/etsTypeReferencePart.h index 4b1e6aba37..8286b312fc 100644 --- a/ets2panda/ir/ets/etsTypeReferencePart.h +++ b/ets2panda/ir/ets/etsTypeReferencePart.h @@ -80,9 +80,7 @@ public: void CopyTo(AstNode *other) const override; private: - checker::Type *HandlePartialType(checker::ETSChecker *const checker, const Identifier *const ident); checker::Type *HandleInternalTypes(checker::ETSChecker *checker); - checker::Type *HandleFixedArrayType(checker::ETSChecker *const checker); friend class SizeOfNodeTest; ir::Expression *name_; diff --git a/ets2panda/lexer/scripts/keywords.yaml b/ets2panda/lexer/scripts/keywords.yaml index a3dc0855ad..3ed7f5ff79 100644 --- a/ets2panda/lexer/scripts/keywords.yaml +++ b/ets2panda/lexer/scripts/keywords.yaml @@ -32,6 +32,11 @@ keywords: keyword_like: [ts] flags: [reserved_type_name] + - name: 'Any' + token: KEYW_BUILTIN_ANY + keyword_like: [ets] + flags: [predefined_type] + - name: 'anyref' token: KEYW_ANYREF keyword_like: [as] diff --git a/ets2panda/test/ast/parser/ets/FixedArray/FunctionalTypeAsArrayElement.ets b/ets2panda/test/ast/parser/ets/FixedArray/FunctionalTypeAsArrayElement.ets index e6559e42e9..5a026a6288 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/FunctionalTypeAsArrayElement.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/FunctionalTypeAsArrayElement.ets @@ -19,4 +19,4 @@ function main(){ ] } -/* @@? 17:48 Error TypeError: Expected type for array literal should be an array type, got () => FixedArray */ +/* @@? 17:48 Error TypeError: Type 'Array<() => Int>' cannot be assigned to type '() => FixedArray' */ diff --git a/ets2panda/test/ast/parser/ets/FunctionalTypeAsArrayElement.ets b/ets2panda/test/ast/parser/ets/FunctionalTypeAsArrayElement.ets index 4e6298318b..d31642e769 100644 --- a/ets2panda/test/ast/parser/ets/FunctionalTypeAsArrayElement.ets +++ b/ets2panda/test/ast/parser/ets/FunctionalTypeAsArrayElement.ets @@ -19,4 +19,4 @@ function main(){ ] } -/* @@? 17:38 Error TypeError: Expected type for array literal should be an array type, got () => Array */ +/* @@? 17:38 Error TypeError: Type 'Array<() => Int>' cannot be assigned to type '() => Array' */ diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_bad_initializer03.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_bad_initializer03.ets index 956e26b9c6..6d9b6522bd 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_bad_initializer03.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationDecl_bad_initializer03.ets @@ -14,8 +14,8 @@ */ @interface MyAnno { - testProperty1: string = /* @@ label */[1,2,a] + testProperty1: string = [1,2,/* @@ label */a] } -/* @@@ label Error TypeError: Expected type for array literal should be an array type, got String */ +/* @@@ label Error TypeError: Unresolved reference a */ diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param04.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param04.ets index cd104710cf..8dd647720d 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param04.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param04.ets @@ -21,4 +21,4 @@ @MyAnno({testProperty1: "1", testProperty2: [1, 2, a]}) class B{} -/* @@? 21:45 Error TypeError: Expected type for array literal should be an array type, got double */ +/* @@? 21:52 Error TypeError: Unresolved reference a */ diff --git a/ets2panda/test/ast/parser/ets/increment-on-nullish-type-undefined-invalid.ets b/ets2panda/test/ast/parser/ets/increment-on-nullish-type-undefined-invalid.ets index e3b52ed7ae..4fd228987d 100644 --- a/ets2panda/test/ast/parser/ets/increment-on-nullish-type-undefined-invalid.ets +++ b/ets2panda/test/ast/parser/ets/increment-on-nullish-type-undefined-invalid.ets @@ -19,4 +19,3 @@ /* @@@ label Error SyntaxError: Unexpected token '~'. */ /* @@@ label1 Error TypeError: Bad operand type, the type of the operand must be numeric type. */ /* @@@ label2 Error SyntaxError: Unexpected token ';'. */ -/* @@@ label2 Error TypeError: Bad operand type, the type of the operand must be boolean type. */ diff --git a/ets2panda/test/ast/parser/ets/type_from_utility_type.ets b/ets2panda/test/ast/parser/ets/type_from_utility_type.ets index f36c443a76..a41765f81a 100644 --- a/ets2panda/test/ast/parser/ets/type_from_utility_type.ets +++ b/ets2panda/test/ast/parser/ets/type_from_utility_type.ets @@ -31,7 +31,6 @@ let recordarrA = Type.from,Array>>(); let recordarrT = Type.from,Array>>(); } - /* @@? 17:20 Error TypeError: No matching call signature */ /* @@? 30:19 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ /* @@? 30:29 Error TypeError: No static $_invoke method and static $_instantiate method in Record. Record() is not allowed. */ /* @@? 30:29 Error TypeError: Type 'Record' has no call signatures. */ diff --git a/ets2panda/test/runtime/ets/AnyType.ets b/ets2panda/test/runtime/ets/AnyType.ets new file mode 100644 index 0000000000..5b84855f12 --- /dev/null +++ b/ets2panda/test/runtime/ets/AnyType.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. + */ + +let a: Any + +a = undefined +a = new Object() +a = null +a = 1 + +a = undefined as Any +a = new Object() as Any +a = null as Any +a = 1 as Any + +function asgn(a: T): Any { return a } + +assertTrue(asgn(null) === null) +assertTrue(asgn(undefined) === undefined) +assertTrue(asgn("a") === "a") +assertTrue(asgn(1) === 1) + +class C {} + +asgn>(new C()) +asgn>(new C()) +asgn>(new C()) +asgn>(new C()) +asgn>(new C()) diff --git a/ets2panda/test/runtime/ets/Function.ets b/ets2panda/test/runtime/ets/Function.ets index 45406aca33..5889ad5f60 100644 --- a/ets2panda/test/runtime/ets/Function.ets +++ b/ets2panda/test/runtime/ets/Function.ets @@ -24,9 +24,7 @@ class B extends A { } } -type __T = object | null | undefined - -function test(f: Function, action: (f: Function) => __T, v: __T) { +function test(f: Function, action: (f: Function) => Any, v: Any) { assertEQ(action(f), v) } diff --git a/ets2panda/test/runtime/ets/NoConstraint.ets b/ets2panda/test/runtime/ets/NoConstraint.ets index 16189c1b13..e0736e7696 100644 --- a/ets2panda/test/runtime/ets/NoConstraint.ets +++ b/ets2panda/test/runtime/ets/NoConstraint.ets @@ -13,13 +13,11 @@ * limitations under the License. */ -type NullishFoo = Object | null | undefined; - -function foo(x: T): NullishFoo { +function foo(x: T): Any { return x; } -function bar(x: T): NullishFoo { +function bar(x: T): Any { return x; } diff --git a/ets2panda/test/runtime/ets/defaultLocalInitializers.ets b/ets2panda/test/runtime/ets/defaultLocalInitializers.ets index 9aa08962a2..96cb2300f1 100644 --- a/ets2panda/test/runtime/ets/defaultLocalInitializers.ets +++ b/ets2panda/test/runtime/ets/defaultLocalInitializers.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -function erase(v: T): object | null | undefined { return v } +function erase(v: T): Any { return v } assertTrue(erase((() => { let r: boolean | undefined; diff --git a/ets2panda/test/runtime/ets/stringComparision.ets b/ets2panda/test/runtime/ets/stringComparision.ets index e1d40eabf1..0af50e17f8 100644 --- a/ets2panda/test/runtime/ets/stringComparision.ets +++ b/ets2panda/test/runtime/ets/stringComparision.ets @@ -14,7 +14,7 @@ */ function foo(p: T, q: U): T|U { - return p!.toString() > q!.toString() ? p : q + return (p! as object).toString() > (q! as object).toString() ? p : q } function main() { diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index ba0191e4ad..f78c0aaa83 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -40,10 +40,6 @@ semantic: id: 7 message: Cannot use array creation expression with type parameter. -- name: NOT_COND_TYPE - id: 8 - message: "Condition must be of possible condition type" - - name: VOID_IN_LOGIC id: 9 message: "An expression of type 'void' cannot be tested for truthiness" @@ -124,10 +120,6 @@ semantic: id: 28 message: "Invalid string template expression" -- name: ASSERT_NOT_LOGICAL - id: 29 - message: "Bad operand type, the type of the operand must be boolean type." - - name: ASSERT_MESSAGE_NOT_STRING id: 30 message: "Assert message must be string" diff --git a/ets2panda/varbinder/ETSBinder.cpp b/ets2panda/varbinder/ETSBinder.cpp index 0f9ae6db10..a57a93f26d 100644 --- a/ets2panda/varbinder/ETSBinder.cpp +++ b/ets2panda/varbinder/ETSBinder.cpp @@ -56,9 +56,10 @@ void ETSBinder::LookupTypeArgumentReferences(ir::ETSTypeReference *typeRef) static bool IsSpecialName(const util::StringView &name) { - return name == compiler::Signatures::UNDEFINED || name == compiler::Signatures::NULL_LITERAL || - name == compiler::Signatures::READONLY_TYPE_NAME || name == compiler::Signatures::PARTIAL_TYPE_NAME || - name == compiler::Signatures::REQUIRED_TYPE_NAME || name == compiler::Signatures::FIXED_ARRAY_TYPE_NAME; + return name == compiler::Signatures::ANY_TYPE_NAME || name == compiler::Signatures::UNDEFINED || + name == compiler::Signatures::NULL_LITERAL || name == compiler::Signatures::READONLY_TYPE_NAME || + name == compiler::Signatures::PARTIAL_TYPE_NAME || name == compiler::Signatures::REQUIRED_TYPE_NAME || + name == compiler::Signatures::FIXED_ARRAY_TYPE_NAME; } bool ETSBinder::HandleDynamicVariables(ir::Identifier *ident, Variable *variable, bool allowDynamicNamespaces) -- Gitee From 90349074aa7acfdcd1515eac2719ccb5b33b5fbf Mon Sep 17 00:00:00 2001 From: Amosov Alexey Date: Tue, 1 Jul 2025 01:32:51 +0300 Subject: [PATCH 040/145] Codecheck deckgen fix Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIYW8 Description: codecheck fix Signed-off-by: Amosov Alexey --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 36 ++++++++++++++++------ 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 01d16758d4..d1bd8f87c0 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -202,7 +202,11 @@ void TSDeclGen::ProcessClassMethodDependencies(const ir::MethodDefinition *metho if (!methodDef->IsExported() && !methodDef->IsExportedType() && !methodDef->IsDefaultExported()) { return; } - auto sig = methodDef->Function()->Signature(); + auto methDefFunc = methodDef->Function(); + if (methDefFunc == nullptr) { + return; + } + auto sig = methDefFunc->Signature(); GenSeparated( sig->Params(), [this](varbinder::LocalVariable *param) { AddSuperType(param->TsType()); }, ""); @@ -539,7 +543,8 @@ const checker::Signature *TSDeclGen::GetFuncSignature(const checker::ETSFunction return etsFunctionType->ArrowSignature(); } if (methodDef != nullptr) { - return methodDef->Function()->Signature(); + auto methDefFunc = methodDef->Function(); + return methDefFunc != nullptr ? methDefFunc->Signature() : nullptr; } if (etsFunctionType->CallSignatures().size() != 1) { const auto loc = methodDef != nullptr ? methodDef->Start() : lexer::SourcePosition(); @@ -736,7 +741,11 @@ std::vector TSDeclGen::FilterUnionTypes(const ArenaVectorGetType(checker_)->ToString(); + auto type = originType->GetType(checker_); + if (type == nullptr) { + continue; + } + typeStr = type->ToString(); typeStr[0] = std::toupper(typeStr[0]); } if (stringTypes_.count(typeStr) != 0U) { @@ -958,6 +967,9 @@ std::string TSDeclGen::RemoveModuleExtensionName(const std::string &filepath) template void TSDeclGen::GenAnnotations(const T *node) { + if (node == nullptr) { + return; + } GenSeparated( node->Annotations(), [this](ir::AnnotationUsage *anno) { @@ -982,7 +994,8 @@ void TSDeclGen::GenAnnotationProperties(const ir::AnnotationUsage *anno) } const auto &properties = anno->Properties(); - if (properties.size() == 1 && + if (properties.size() == 1 && properties.at(0)->IsClassProperty() && + properties.at(0)->AsClassProperty()->Id() != nullptr && properties.at(0)->AsClassProperty()->Id()->Name() == compiler::Signatures::ANNOTATION_KEY_VALUE) { OutDts("("); if (properties.at(0)->AsClassProperty()->Value() != nullptr) { @@ -1283,7 +1296,7 @@ void TSDeclGen::ProcessTypeAnnotationType(const ir::TypeNode *typeAnnotation, co OutDts("void"); return; } - if (typeAnnotation->IsETSStringLiteralType()) { + if (typeAnnotation->IsETSStringLiteralType() && aliasedType != nullptr) { importSet_.insert(aliasedType->ToString()); OutDts(aliasedType->ToString()); return; @@ -1350,6 +1363,9 @@ void TSDeclGen::ProcessTSArrayType(const ir::TSArrayType *tsArrayType) { auto *elementType = tsArrayType->ElementType(); auto *elementCheckerType = const_cast(elementType)->GetType(checker_); + if (elementCheckerType == nullptr) { + return; + } bool needParentheses = !elementType->IsETSTypeReference() && elementCheckerType->IsETSUnionType(); OutDts(needParentheses ? "(" : ""); ProcessTypeAnnotationType(elementType, elementCheckerType); @@ -1869,8 +1885,9 @@ bool TSDeclGen::GenMethodDeclarationPrefix(const ir::MethodDefinition *methodDef !ShouldEmitDeclarationSymbol(methodIdent) && !methodDef->IsConstructor()) { return true; } - if (!methodDef->Function()->Annotations().empty()) { - GenAnnotations(methodDef->Function()); + auto methDefFunc = methodDef->Function(); + if (methDefFunc != nullptr && !methDefFunc->Annotations().empty()) { + GenAnnotations(methDefFunc); } ProcessIndent(); GenModifier(methodDef); @@ -1951,7 +1968,8 @@ void TSDeclGen::ProcessClassPropertyType(const ir::ClassProperty *classProp) ProcessTypeAnnotationType(classProp->TypeAnnotation(), classProp->TsType()); return; } - if (value->IsArrowFunctionExpression() && value->AsArrowFunctionExpression()->Function() != nullptr && + if (value != nullptr && value->IsArrowFunctionExpression() && + value->AsArrowFunctionExpression()->Function() != nullptr && value->AsArrowFunctionExpression()->Function()->TypeParams() != nullptr) { GenTypeParameters(value->AsArrowFunctionExpression()->Function()->TypeParams()); } @@ -2071,7 +2089,7 @@ void TSDeclGen::GenGlobalVarDeclaration(const ir::ClassProperty *globalVar) bool WriteToFile(const std::string &path, const std::string &content, checker::ETSChecker *checker) { - std::ofstream outStream(path); + std::ofstream outStream(path); // ark::os::GetAbsolutePath(*pathValue) if (outStream.fail()) { checker->DiagnosticEngine().LogDiagnostic(diagnostic::OPEN_FAILED, util::DiagnosticMessageParams {path}); return false; -- Gitee From a300a29d6cf15ecf08d5f58a407bc7ac82a4b722 Mon Sep 17 00:00:00 2001 From: dongchao Date: Sun, 8 Jun 2025 18:57:19 +0800 Subject: [PATCH 041/145] Print all error messages in build_system Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIODU Signed-off-by: dongchao Change-Id: Idecd716de616d368f5e18d8aca1879b21ca9d15b --- ets2panda/bindings/native/src/bridges.cpp | 7 +++ .../bindings/src/Es2pandaNativeModule.ts | 4 ++ .../build_system/src/build/base_mode.ts | 16 ++++++- .../build_system/src/build/compile_worker.ts | 31 ++++--------- .../build_system/src/build/declgen_worker.ts | 20 +++----- ets2panda/public/es2panda_lib.cpp | 18 ++++++++ ets2panda/public/es2panda_lib.h | 1 + ets2panda/public/es2panda_lib.idl.erb | 1 + ets2panda/util/diagnosticEngine.cpp | 46 +++++++++++++++++-- ets2panda/util/diagnosticEngine.h | 6 ++- 10 files changed, 106 insertions(+), 44 deletions(-) diff --git a/ets2panda/bindings/native/src/bridges.cpp b/ets2panda/bindings/native/src/bridges.cpp index 2757d4b9ef..ebb915d98f 100644 --- a/ets2panda/bindings/native/src/bridges.cpp +++ b/ets2panda/bindings/native/src/bridges.cpp @@ -66,3 +66,10 @@ KNativePointer impl_ContextErrorMessage(KNativePointer contextPtr) return new std::string(GetPublicImpl()->ContextErrorMessage(context)); } TS_INTEROP_1(ContextErrorMessage, KNativePointer, KNativePointer) + +KNativePointer impl_GetAllErrorMessages(KNativePointer contextPtr) +{ + auto context = reinterpret_cast(contextPtr); + return new std::string(GetPublicImpl()->GetAllErrorMessages(context)); +} +TS_INTEROP_1(GetAllErrorMessages, KNativePointer, KNativePointer) diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts index 210ad83e1c..72ef3873b9 100644 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/Es2pandaNativeModule.ts @@ -45,6 +45,10 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _GetAllErrorMessages(context: KPtr): KPtr { + throw new Error('Not implemented'); + } + _AstNodeDumpModifiers(context: KPtr, node: KPtr): KPtr { throw new Error('Not implemented'); } diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index c5282cded0..289cc947a6 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -183,7 +183,8 @@ export abstract class BaseMode { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_DECLGEN_FAIL, 'Generate declaration files failed.', - error.message + error.message, + fileInfo.filePath ); this.logger.printError(logData); } @@ -247,7 +248,8 @@ export abstract class BaseMode { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_COMPILE_ABC_FAIL, 'Compile abc files failed.', - error.message + error.message, + fileInfo.filePath ); this.logger.printError(logData); } @@ -790,10 +792,20 @@ export abstract class BaseMode { success: boolean; filePath?: string; error?: string; + isDeclFile?: boolean; }) => { if (message.success) { return; } + if (message.isDeclFile) { + this.logger.printError(LogDataFactory.newInstance( + ErrorCode.BUILDSYSTEM_DECLGEN_FAIL, + 'Generate declaration files failed in worker.', + message.error || 'Unknown error', + message.filePath + )); + return; + } this.logger.printError(LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_COMPILE_ABC_FAIL, 'Compile abc files failed in worker.', diff --git a/ets2panda/driver/build_system/src/build/compile_worker.ts b/ets2panda/driver/build_system/src/build/compile_worker.ts index 38a1fcdb59..bccf1d8142 100644 --- a/ets2panda/driver/build_system/src/build/compile_worker.ts +++ b/ets2panda/driver/build_system/src/build/compile_worker.ts @@ -19,18 +19,9 @@ import * as path from 'path'; import { ensurePathExists } from '../utils'; import { KOALA_WRAPPER_PATH_FROM_SDK } from '../pre_define'; import { PluginDriver, PluginHook } from '../plugins/plugins_driver'; -import { - BuildConfig, -} from '../types'; -import { - BUILD_MODE -} from '../pre_define'; -import { - LogData, - LogDataFactory, - Logger -} from '../logger'; -import { ErrorCode } from '../error_code'; +import { BuildConfig } from '../types'; +import { BUILD_MODE } from '../pre_define'; +import { Logger } from '../logger'; process.on('message', (message: { taskList: CompileFileInfo[]; @@ -80,18 +71,12 @@ process.on('message', (message: { } catch (error) { errorStatus = true; if (error instanceof Error) { - const logData: LogData = LogDataFactory.newInstance( - ErrorCode.BUILDSYSTEM_COMPILE_ABC_FAIL, - 'Compile abc files failed.', - error.message - ); - Logger.getInstance().printError(logData); + process.send({ + success: false, + filePath: fileInfo.filePath, + error: 'Compile abc files failed.\n' + error.message + }); } - process.send({ - success: false, - filePath: fileInfo.filePath, - error: 'Compile abc files failed.' - }); } finally { if (!errorStatus) { // when error occur,wrapper will destroy context. diff --git a/ets2panda/driver/build_system/src/build/declgen_worker.ts b/ets2panda/driver/build_system/src/build/declgen_worker.ts index 2d25e9704d..135acab0dd 100644 --- a/ets2panda/driver/build_system/src/build/declgen_worker.ts +++ b/ets2panda/driver/build_system/src/build/declgen_worker.ts @@ -15,8 +15,7 @@ import { CompileFileInfo, ModuleInfo } from '../types'; import { BuildConfig } from '../types'; -import { LogData, LogDataFactory, Logger } from '../logger'; -import { ErrorCode } from '../error_code'; +import { Logger } from '../logger'; import * as fs from 'fs'; import * as path from 'path'; import { changeFileExtension, ensurePathExists } from '../utils'; @@ -102,18 +101,13 @@ process.on('message', (message: { } 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, + isDeclFile: true, + filePath: fileInfo.filePath, + error: 'Generate declaration files failed.\n' + error.message + }); } - process.send({ - success: false, - filePath: fileInfo.filePath, - error: 'Generate declaration files failed in worker.' - }); } finally { if (!errorStatus) { // when error occur,wrapper will destroy context. diff --git a/ets2panda/public/es2panda_lib.cpp b/ets2panda/public/es2panda_lib.cpp index 68c404993f..968ce30073 100644 --- a/ets2panda/public/es2panda_lib.cpp +++ b/ets2panda/public/es2panda_lib.cpp @@ -277,6 +277,23 @@ extern "C" void DestroyConfig(es2panda_Config *config) delete cfg; } +extern "C" __attribute__((unused)) char const *GetAllErrorMessages(es2panda_Context *context) +{ + auto *ctx = reinterpret_cast(context); + ES2PANDA_ASSERT(ctx != nullptr); + ES2PANDA_ASSERT(ctx->config != nullptr); + ES2PANDA_ASSERT(ctx->allocator != nullptr); + auto *cfg = reinterpret_cast(ctx->config); + ES2PANDA_ASSERT(cfg != nullptr); + ES2PANDA_ASSERT(cfg->diagnosticEngine != nullptr); + auto allMessages = cfg->diagnosticEngine->PrintAndFlushErrorDiagnostic(); + size_t bufferSize = allMessages.length() + 1; + char *cStringMessages = reinterpret_cast(ctx->allocator->Alloc(bufferSize)); + [[maybe_unused]] auto err = memcpy_s(cStringMessages, bufferSize, allMessages.c_str(), bufferSize); + ES2PANDA_ASSERT(err == EOK); + return cStringMessages; +} + extern "C" const es2panda_Options *ConfigGetOptions(es2panda_Config *config) { auto options = reinterpret_cast(config)->options; @@ -1047,6 +1064,7 @@ es2panda_Impl g_impl = { CreateConfig, DestroyConfig, + GetAllErrorMessages, ConfigGetOptions, CreateContextFromFile, CreateContextFromString, diff --git a/ets2panda/public/es2panda_lib.h b/ets2panda/public/es2panda_lib.h index b331f56829..2c4e3fc202 100644 --- a/ets2panda/public/es2panda_lib.h +++ b/ets2panda/public/es2panda_lib.h @@ -177,6 +177,7 @@ struct CAPI_EXPORT es2panda_Impl { es2panda_Config *(*CreateConfig)(int argc, char const *const *argv); void (*DestroyConfig)(es2panda_Config *config); + char const *(*GetAllErrorMessages)(es2panda_Context *context); const es2panda_Options *(*ConfigGetOptions)(es2panda_Config *config); es2panda_Context *(*CreateContextFromFile)(es2panda_Config *config, char const *source_file_name); diff --git a/ets2panda/public/es2panda_lib.idl.erb b/ets2panda/public/es2panda_lib.idl.erb index c884938c36..e4a957106d 100644 --- a/ets2panda/public/es2panda_lib.idl.erb +++ b/ets2panda/public/es2panda_lib.idl.erb @@ -168,6 +168,7 @@ typedef u64 Es2panda<%= name %>; interface es2panda_Impl { es2panda_Config CreateConfig(i32 argc, sequence argv); void DestroyConfig(es2panda_Config config); + String GetAllErrorMessages(es2panda_Context context); es2panda_Options ConfigGetOptions(es2panda_Config config); es2panda_Context CreateContextFromFile(es2panda_Config config, String source_file_name); diff --git a/ets2panda/util/diagnosticEngine.cpp b/ets2panda/util/diagnosticEngine.cpp index 131ca76cf8..16edf9a6f9 100644 --- a/ets2panda/util/diagnosticEngine.cpp +++ b/ets2panda/util/diagnosticEngine.cpp @@ -22,14 +22,19 @@ namespace ark::es2panda::util { -void CLIDiagnosticPrinter::Print(const DiagnosticBase &diagnostic) const +void CLIDiagnosticPrinter::Print(const DiagnosticBase &diagnostic, std::ostream &out) const { - std::cout << DiagnosticTypeToString(diagnostic.Type()) << ": " << diagnostic.Message(); + out << DiagnosticTypeToString(diagnostic.Type()) << ": " << diagnostic.Message(); if (!diagnostic.File().empty()) { - std::cout << " [" << util::BaseName(diagnostic.File()) << ":" << diagnostic.Line() << ":" << diagnostic.Offset() - << "]"; + out << " [" << util::BaseName(diagnostic.File()) << ":" << diagnostic.Line() << ":" << diagnostic.Offset() + << "]"; } - std::cout << std::endl; + out << std::endl; +} + +void CLIDiagnosticPrinter::Print(const DiagnosticBase &diagnostic) const +{ + Print(diagnostic, std::cout); } const DiagnosticStorage &DiagnosticEngine::GetDiagnosticStorage(DiagnosticType type) @@ -59,6 +64,37 @@ DiagnosticStorage DiagnosticEngine::GetAllDiagnostic() return merged; } +DiagnosticStorage DiagnosticEngine::GetErrorDiagnostic() +{ + size_t errorCount = 0; + for (const auto &vec : diagnostics_) { + if (!vec.empty() && IsError(vec.front()->Type())) { + errorCount += vec.size(); + } + } + + DiagnosticStorage merged; + merged.reserve(errorCount); + for (const auto &vec : diagnostics_) { + if (!vec.empty() && IsError(vec.front()->Type())) { + merged.insert(merged.end(), vec.begin(), vec.end()); + } + } + return merged; +} + +std::string DiagnosticEngine::PrintAndFlushErrorDiagnostic() +{ + auto log = GetErrorDiagnostic(); + std::sort(log.begin(), log.end(), [](const auto &lhs, const auto &rhs) { return *lhs < *rhs; }); + auto last = std::unique(log.begin(), log.end(), [](const auto &lhs, const auto &rhs) { return *lhs == *rhs; }); + std::ostringstream oss; + for (auto it = log.begin(); it != last; ++it) { + printer_->Print(**it, oss); + } + return oss.str(); +} + void DiagnosticEngine::FlushDiagnostic() { auto log = GetAllDiagnostic(); diff --git a/ets2panda/util/diagnosticEngine.h b/ets2panda/util/diagnosticEngine.h index 0562a1cb45..cd900a730e 100644 --- a/ets2panda/util/diagnosticEngine.h +++ b/ets2panda/util/diagnosticEngine.h @@ -34,6 +34,7 @@ public: virtual ~DiagnosticPrinter() = default; virtual void Print(const DiagnosticBase &diagnostic) const = 0; + virtual void Print(const DiagnosticBase &diagnostic, std::ostream &out) const = 0; }; class CLIDiagnosticPrinter : public DiagnosticPrinter { @@ -44,9 +45,10 @@ public: ~CLIDiagnosticPrinter() override = default; void Print(const DiagnosticBase &diagnostic) const override; + void Print(const DiagnosticBase &diagnostic, std::ostream &out) const override; }; -using DiagnosticStorage = std::vector>; +using DiagnosticStorage = std::vector>; class DiagnosticEngine { public: @@ -119,6 +121,7 @@ public: } void FlushDiagnostic(); + std::string PrintAndFlushErrorDiagnostic(); void SetWError(bool wError) { wError_ = wError; @@ -159,6 +162,7 @@ private: bool IsError(DiagnosticType type) const; DiagnosticStorage GetAllDiagnostic(); + DiagnosticStorage GetErrorDiagnostic(); void WriteLog(const DiagnosticBase &error); private: -- Gitee From 4aef047f0bc34f91a205daa7a7ad8917d9f2e29b Mon Sep 17 00:00:00 2001 From: dongchao Date: Wed, 25 Jun 2025 09:43:36 +0800 Subject: [PATCH 042/145] Fix restparam scene in declgen_ets2ts Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIE5U Signed-off-by: dongchao Change-Id: I58c707e3a95e8438a763fbeceeeccaf4a17573df --- ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 222 +++++++++++++++------ ets2panda/declgen_ets2ts/declgenEts2Ts.h | 20 +- ets2panda/parser/ETSparserClasses.cpp | 1 + 3 files changed, 180 insertions(+), 63 deletions(-) diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index 01d16758d4..37051e45a9 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -1036,13 +1036,13 @@ 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 " : ""; + bool isTypeKind = importDeclaration->IsTypeKind(); if (specifierFirst->IsImportNamespaceSpecifier()) { GenNamespaceImport(specifierFirst, source); } else if (specifierFirst->IsImportDefaultSpecifier()) { - GenDefaultImport(specifierFirst, source, typeStr); + GenDefaultImport(specifierFirst, source, isTypeKind); } else if (specifierFirst->IsImportSpecifier()) { - GenNamedImports(importDeclaration, specifiers, source, typeStr); + GenNamedImports(importDeclaration, specifiers, isTypeKind); } } @@ -1058,45 +1058,78 @@ void TSDeclGen::GenNamespaceImport(const ir::AstNode *specifier, const std::stri OutEndlDts(); } -void TSDeclGen::GenDefaultImport(const ir::AstNode *specifier, const std::string &source, const std::string &typeStr) +void TSDeclGen::GenDefaultImport(const ir::AstNode *specifier, const std::string &source, bool isTypeKind) { const auto local = specifier->AsImportDefaultSpecifier()->Local()->Name(); - OutTs("import ", typeStr, local, " from \"", source, "\";"); + if (specifier->AsImportDefaultSpecifier()->Local()->Variable() && + specifier->AsImportDefaultSpecifier()->Local()->Variable()->Declaration() && + specifier->AsImportDefaultSpecifier()->Local()->Variable()->Declaration()->Node() && + specifier->AsImportDefaultSpecifier()->Local()->Variable()->Declaration()->Node()->IsTSInterfaceDeclaration()) { + OutTs("import type ", local, " from \"", source, "\";"); + } else { + OutTs(isTypeKind ? "import type " : "import ", local, " from \"", source, "\";"); + } OutEndlTs(); if (importSet_.find(local.Mutf8()) == importSet_.end()) { return; } - OutDts("import ", typeStr, local, " from \"", source, "\";"); + OutDts(isTypeKind ? "import type " : "import ", local, " from \"", source, "\";"); OutEndlDts(); } void TSDeclGen::GenNamedImports(const ir::ETSImportDeclaration *importDeclaration, - const ArenaVector &specifiers, const std::string &source, - const std::string &typeStr) + const ArenaVector &specifiers, bool isTypeKind) +{ + if (specifiers.empty()) { + return; + } + std::vector interfaceSpecifiers; + std::vector normalSpecifiers; + SeparateInterfaceSpecifiers(specifiers, interfaceSpecifiers, normalSpecifiers); + + GenTsImportStatement(interfaceSpecifiers, importDeclaration, true); + GenTsImportStatement(normalSpecifiers, importDeclaration); + + auto importSpecifiers = FilterValidImportSpecifiers(specifiers); + GenDtsImportStatement(importSpecifiers, importDeclaration, isTypeKind); +} + +void TSDeclGen::GenTsImportStatement(std::vector &specifiers, + const ir::ETSImportDeclaration *importDeclaration, bool isInterface) { if (specifiers.empty()) { return; } - OutTs("import ", typeStr, "{ "); + + auto source = importDeclaration->Source()->Str().Mutf8(); + source = RemoveModuleExtensionName(source); + OutTs(isInterface ? "import type" : "import", " { "); + GenSeparated( specifiers, - [this, &importDeclaration](ir::AstNode *specifier) { - GenSingleNamedImport(specifier, importDeclaration, true); - }, + [this, importDeclaration](ir::AstNode *specifier) { GenSingleNamedImport(specifier, importDeclaration, true); }, ", ", true, false); - OutTs(" } from \"", source, "\";"); - OutEndlTs(); - auto importSpecifiers = FilterValidImportSpecifiers(specifiers); - if (importSpecifiers.empty()) { + + OutTs(" } from \"", source, "\";\n"); +} + +void TSDeclGen::GenDtsImportStatement(std::vector &specifiers, + const ir::ETSImportDeclaration *importDeclaration, bool isTypeKind) +{ + if (specifiers.empty()) { return; } - OutDts("import ", typeStr, "{ "); + + auto source = importDeclaration->Source()->Str().Mutf8(); + source = RemoveModuleExtensionName(source); + OutDts(isTypeKind ? "import type" : "import", " { "); + GenSeparated( - importSpecifiers, - [this, &importDeclaration](ir::AstNode *specifier) { GenSingleNamedImport(specifier, importDeclaration); }, + specifiers, + [this, importDeclaration](ir::AstNode *specifier) { GenSingleNamedImport(specifier, importDeclaration); }, ", "); - OutDts(" } from \"", source, "\";"); - OutEndlDts(); + + OutDts(" } from \"", source, "\";\n"); } void TSDeclGen::GenSingleNamedImport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration, @@ -1137,48 +1170,115 @@ void TSDeclGen::GenReExportDeclaration(const ir::ETSReExportDeclaration *reExpor return; } const auto &specifiers = importDeclaration->Specifiers(); - if (specifiers.size() == 1 && specifiers[0]->IsImportNamespaceSpecifier()) { - const auto local = specifiers[0]->AsImportNamespaceSpecifier()->Local()->Name(); + + if (specifiers.size() == 1 && GenNamespaceReExportDeclaration(specifiers[0], importDeclaration)) { + return; + } + + bool isTypeKind = reExportDeclaration->IsExportedType(); + std::vector interfaceSpecifiers; + std::vector normalSpecifiers; + SeparateInterfaceSpecifiers(specifiers, interfaceSpecifiers, normalSpecifiers); + + GenDtsReExportStatement(specifiers, importDeclaration, isTypeKind); + + GenTsReExportStatement(interfaceSpecifiers, importDeclaration, true); + GenTsReExportStatement(normalSpecifiers, importDeclaration); +} + +bool TSDeclGen::GenNamespaceReExportDeclaration(const ir::AstNode *specifier, + const ir::ETSImportDeclaration *importDeclaration) +{ + if (specifier->IsImportNamespaceSpecifier()) { + const auto local = specifier->AsImportNamespaceSpecifier()->Local()->Name(); if (local.Empty()) { - OutDts("export * from \"", importDeclaration->Source()->Str().Mutf8(), "\";"); - OutEndlDts(); - OutTs("export * from \"", importDeclaration->Source()->Str().Mutf8(), "\";"); - OutEndlTs(); - return; + auto source = importDeclaration->Source()->Str().Mutf8(); + source = RemoveModuleExtensionName(source); + OutDts("export * from \"", source, "\";\n"); + OutTs("export * from \"", source, "\";\n"); + return true; + } + } + return false; +} + +void TSDeclGen::SeparateInterfaceSpecifiers(const ArenaVector &specifiers, + std::vector &interfaceSpecifiers, + std::vector &normalSpecifiers) +{ + for (auto *specifier : specifiers) { + if (!specifier->IsImportSpecifier()) { + continue; + } + if (specifier->AsImportSpecifier()->Imported()->Variable() && + specifier->AsImportSpecifier()->Imported()->Variable()->Declaration() && + specifier->AsImportSpecifier()->Imported()->Variable()->Declaration()->Node() && + specifier->AsImportSpecifier()->Imported()->Variable()->Declaration()->Node()->IsTSInterfaceDeclaration()) { + interfaceSpecifiers.push_back(specifier); + } else { + normalSpecifiers.push_back(specifier); } } - OutDts("export { "); - OutTs("export { "); +} + +void TSDeclGen::GenSingleNamedReExport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration, + bool isGlueCode) +{ + if (specifier->IsImportSpecifier()) { + const auto local = specifier->AsImportSpecifier()->Local()->Name().Mutf8(); + const auto imported = specifier->AsImportSpecifier()->Imported()->Name().Mutf8(); + importSet_.insert(local); + if (local != imported) { + isGlueCode ? OutTs(imported, " as ", local) : OutDts(imported, " as ", local); + } else { + isGlueCode ? OutTs(local) : OutDts(local); + } + } else if (specifier->IsImportNamespaceSpecifier()) { + const auto local = specifier->AsImportNamespaceSpecifier()->Local()->Name().Mutf8(); + importSet_.insert(local); + isGlueCode ? OutTs(local) : OutDts(local); + } else { + LogError(diagnostic::IMPORT_SPECIFIERS_SUPPORT, {}, importDeclaration->Start()); + } +} + +void TSDeclGen::GenDtsReExportStatement(const ArenaVector &specifiers, + const ir::ETSImportDeclaration *importDeclaration, bool isTypeKind) +{ + if (specifiers.empty()) { + return; + } + + auto source = importDeclaration->Source()->Str().Mutf8(); + source = RemoveModuleExtensionName(source); + OutDts(isTypeKind ? "export type" : "export", " { "); + GenSeparated( specifiers, - [this, &importDeclaration](ir::AstNode *specifier) { - if (specifier->IsImportSpecifier()) { - const auto local = specifier->AsImportSpecifier()->Local()->Name().Mutf8(); - const auto imported = specifier->AsImportSpecifier()->Imported()->Name().Mutf8(); - importSet_.insert(local); - if (local != imported) { - OutDts(imported, " as ", local); - OutTs(imported, " as ", local); - } else { - OutDts(local); - OutTs(local); - } - } else if (specifier->IsImportNamespaceSpecifier()) { - const auto local = specifier->AsImportNamespaceSpecifier()->Local()->Name(); - importSet_.insert(local.Mutf8()); - OutDts(local); - OutTs(local); - } else { - LogError(diagnostic::IMPORT_SPECIFIERS_SUPPORT, {}, importDeclaration->Start()); - } - }, - ", ", true); + [this, importDeclaration](ir::AstNode *specifier) { GenSingleNamedReExport(specifier, importDeclaration); }, + ", "); + + OutDts(" } from \"", source, "\";\n"); +} +void TSDeclGen::GenTsReExportStatement(const std::vector &specifiers, + const ir::ETSImportDeclaration *importDeclaration, bool isInterface) +{ + if (specifiers.empty()) { + return; + } auto source = importDeclaration->Source()->Str().Mutf8(); - OutDts(" } from \"", source, "\";"); - OutEndlDts(); - OutTs(" } from \"", source, "\";"); - OutEndlTs(); + source = RemoveModuleExtensionName(source); + OutTs(isInterface ? "export type" : "export", " { "); + + GenSeparated( + specifiers, + [this, importDeclaration](ir::AstNode *specifier) { + GenSingleNamedReExport(specifier, importDeclaration, true); + }, + ", ", true, false); + + OutTs(" } from \"", source, "\";\n"); } std::string TSDeclGen::ReplaceETSGLOBAL(const std::string &typeName) @@ -1365,10 +1465,12 @@ void TSDeclGen::ProcessETSFunctionType(const ir::ETSFunctionType *etsFunction) bool inUnionBody = !state_.inUnionBodyStack.empty() && state_.inUnionBodyStack.top(); OutDts(inUnionBody ? "((" : "("); GenSeparated(etsFunction->Params(), [this](ir::Expression *param) { - const auto paramName = param->AsETSParameterExpression()->Name(); - OutDts(paramName.Is("=t") ? "this" : paramName, ": "); - ProcessTypeAnnotationType(param->AsETSParameterExpression()->TypeAnnotation(), - param->AsETSParameterExpression()->TypeAnnotation()->TsType()); + const auto paramExpr = param->AsETSParameterExpression(); + const auto paramName = paramExpr->Name(); + const bool isRestParam = paramExpr->IsRestParameter(); + const bool isOptional = paramExpr->IsOptional(); + OutDts(isRestParam ? "..." : "", paramName.Is("=t") ? "this" : paramName, isOptional ? "?: " : ": "); + ProcessTypeAnnotationType(paramExpr->TypeAnnotation(), paramExpr->TypeAnnotation()->TsType()); }); OutDts(") => "); ProcessTypeAnnotationType(etsFunction->ReturnType(), etsFunction->ReturnType()->TsType()); diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index fc580114db..ccd20774e5 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -119,13 +119,27 @@ private: 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 GenDefaultImport(const ir::AstNode *specifier, const std::string &source, bool isTypeKind = false); void GenNamedImports(const ir::ETSImportDeclaration *importDeclaration, - const ArenaVector &specifiers, const std::string &source, - const std::string &typeStr); + const ArenaVector &specifiers, bool isTypeKind = false); + void GenDtsImportStatement(std::vector &specifiers, + const ir::ETSImportDeclaration *importDeclaration, bool isTypeKind = false); + void GenTsImportStatement(std::vector &specifiers, const ir::ETSImportDeclaration *importDeclaration, + bool isInterface = false); void GenSingleNamedImport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration, bool isGlueCode = false); void GenReExportDeclaration(const ir::ETSReExportDeclaration *reExportDeclaration); + bool GenNamespaceReExportDeclaration(const ir::AstNode *specifier, + const ir::ETSImportDeclaration *importDeclaration); + void SeparateInterfaceSpecifiers(const ArenaVector &specifiers, + std::vector &interfaceSpecifiers, + std::vector &normalSpecifiers); + void GenDtsReExportStatement(const ArenaVector &specifiers, + const ir::ETSImportDeclaration *importDeclaration, bool isTypeKind = false); + void GenTsReExportStatement(const std::vector &specifiers, + const ir::ETSImportDeclaration *importDeclaration, bool isInterface = false); + void GenSingleNamedReExport(ir::AstNode *specifier, const ir::ETSImportDeclaration *importDeclaration, + bool isGlueCode = false); void GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAlias); void GenEnumDeclaration(const ir::ClassProperty *enumMember); void GenInterfaceDeclaration(const ir::TSInterfaceDeclaration *interfaceDecl); diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index fcfad7919b..ed1e1bc050 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -1343,6 +1343,7 @@ std::pair ETSParser::ParseMemberModifi Lexer()->Rewind(savedPos); } memberModifiers |= ir::ModifierFlags::EXPORT; + memberModifiers |= ir::ModifierFlags::EXPORT_TYPE; } else { memberModifiers |= ir::ModifierFlags::EXPORT; } -- Gitee From 7071cf9bd18e57f327bad459ffd8c4e8c0ee96e8 Mon Sep 17 00:00:00 2001 From: Chernykh Sergey Date: Mon, 30 Jun 2025 19:21:51 +0300 Subject: [PATCH 043/145] Fix codecheck in DiagnosticEngine Description: * Move out FlushDiagnostic out of DiagnosticEngine destructor Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIYR9 Signed-off-by: Sergey Chernykh --- ets2panda/aot/main.cpp | 8 +++++++- ets2panda/public/es2panda_lib.cpp | 1 + ets2panda/util/diagnosticEngine.cpp | 3 +++ ets2panda/util/diagnosticEngine.h | 1 - 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/ets2panda/aot/main.cpp b/ets2panda/aot/main.cpp index 411df8364a..b8f59a420f 100644 --- a/ets2panda/aot/main.cpp +++ b/ets2panda/aot/main.cpp @@ -165,6 +165,7 @@ static int Run(Span args) auto diagnosticEngine = util::DiagnosticEngine(); auto options = std::make_unique(args[0], diagnosticEngine); if (!options->Parse(args)) { + diagnosticEngine.FlushDiagnostic(); return 1; } diagnosticEngine.SetWError(options->IsEtsWarningsWerror()); @@ -175,6 +176,7 @@ static int Run(Span args) auto pluginsOpt = InitializePlugins(options->GetPlugins(), diagnosticEngine); if (!pluginsOpt.has_value()) { + diagnosticEngine.FlushDiagnostic(); return 1; } @@ -182,10 +184,12 @@ static int Run(Span args) if (options->IsListPhases()) { std::cerr << "Available phases:" << std::endl; std::cerr << compiler.GetPhasesList(); + diagnosticEngine.FlushDiagnostic(); return 1; } if (options->GetCompilationMode() == CompilationMode::PROJECT) { + diagnosticEngine.FlushDiagnostic(); return CompileFromConfig(compiler, options.get(), diagnosticEngine); } @@ -200,7 +204,9 @@ static int Run(Span args) parserInput = std::string_view(buf, size); } es2panda::SourceFile input(sourceFile, parserInput, options->IsModule(), options->GetOutput()); - return CompileFromSource(compiler, input, *options.get(), diagnosticEngine); + auto res = CompileFromSource(compiler, input, *options.get(), diagnosticEngine); + diagnosticEngine.FlushDiagnostic(); + return res; } } // namespace ark::es2panda::aot diff --git a/ets2panda/public/es2panda_lib.cpp b/ets2panda/public/es2panda_lib.cpp index 68c404993f..f10f45292b 100644 --- a/ets2panda/public/es2panda_lib.cpp +++ b/ets2panda/public/es2panda_lib.cpp @@ -273,6 +273,7 @@ extern "C" void DestroyConfig(es2panda_Config *config) } delete cfg->options; + cfg->diagnosticEngine->FlushDiagnostic(); delete cfg->diagnosticEngine; delete cfg; } diff --git a/ets2panda/util/diagnosticEngine.cpp b/ets2panda/util/diagnosticEngine.cpp index 131ca76cf8..84a00213a7 100644 --- a/ets2panda/util/diagnosticEngine.cpp +++ b/ets2panda/util/diagnosticEngine.cpp @@ -68,6 +68,9 @@ void DiagnosticEngine::FlushDiagnostic() for (auto it = log.begin(); it != last; it++) { printer_->Print(**it); } + for (auto &vec : diagnostics_) { + vec.clear(); + } } #ifndef FUZZING_EXIT_ON_FAILED_ASSERT static void SigSegvHandler([[maybe_unused]] int sig) diff --git a/ets2panda/util/diagnosticEngine.h b/ets2panda/util/diagnosticEngine.h index 0562a1cb45..a10f4e2aea 100644 --- a/ets2panda/util/diagnosticEngine.h +++ b/ets2panda/util/diagnosticEngine.h @@ -58,7 +58,6 @@ public: NO_MOVE_SEMANTIC(DiagnosticEngine); ~DiagnosticEngine() { - FlushDiagnostic(); g_diagnosticEngine = nullptr; } -- Gitee From b126894636e3e5426858afccdfe1346638707254 Mon Sep 17 00:00:00 2001 From: dongchao Date: Fri, 13 Jun 2025 00:04:47 +0800 Subject: [PATCH 044/145] Fix driver codecheck Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICEUHH Signed-off-by: dongchao Change-Id: I0ad334d2a64931bcb2802fd29a7a93a4474c2250 --- .../build_system/src/build/base_mode.ts | 137 +++++++++--------- 1 file changed, 67 insertions(+), 70 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 6eacaa83bc..2b5e6213d6 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -33,7 +33,6 @@ import { MERGED_ABC_FILE, TS_SUFFIX, DEPENDENCY_INPUT_FILE, - PROJECT_BUILD_CONFIG_FILE } from '../pre_define'; import { changeDeclgenFileExtension, @@ -63,40 +62,42 @@ import { } from '../types'; import { ArkTSConfigGenerator } from './generate_arktsconfig'; import { SetupClusterOptions } from '../types'; + export abstract class BaseMode { - buildConfig: BuildConfig; - entryFiles: Set; - compileFiles: Map; - outputDir: string; - cacheDir: string; - pandaSdkPath: string; - buildSdkPath: string; - packageName: string; - sourceRoots: string[]; - moduleRootPath: string; - moduleType: string; - dependentModuleList: DependentModuleConfig[]; - moduleInfos: Map; - mergedAbcFile: string; - dependencyJsonFile: string; - abcLinkerCmd: string[]; - dependencyAnalyzerCmd: string[]; - logger: Logger; - isDebug: boolean; - enableDeclgenEts2Ts: boolean; - declgenV1OutPath: string | undefined; - declgenBridgeCodePath: string | undefined; - hasMainModule: boolean; - abcFiles: Set; - hashCache: Record; - hashCacheFile: string; - isCacheFileExists: boolean; - dependencyFileMap: DependencyFileConfig | null; - isBuildConfigModified: boolean | undefined; + public buildConfig: BuildConfig; + public entryFiles: Set; + public compileFiles: Map; + public outputDir: string; + public cacheDir: string; + public pandaSdkPath: string; + public buildSdkPath: string; + public packageName: string; + public sourceRoots: string[]; + public moduleRootPath: string; + public moduleType: string; + public dependentModuleList: DependentModuleConfig[]; + public moduleInfos: Map; + public mergedAbcFile: string; + public dependencyJsonFile: string; + public abcLinkerCmd: string[]; + public dependencyAnalyzerCmd: string[]; + public logger: Logger; + public isDebug: boolean; + public enableDeclgenEts2Ts: boolean; + public declgenV1OutPath: string | undefined; + public declgenBridgeCodePath: string | undefined; + public hasMainModule: boolean; + public abcFiles: Set; + public hashCacheFile: string; + public hashCache: Record; + public isCacheFileExists: boolean; + public dependencyFileMap: DependencyFileConfig | null; + public isBuildConfigModified: boolean | undefined; constructor(buildConfig: BuildConfig) { this.buildConfig = buildConfig; this.entryFiles = new Set(buildConfig.compileFiles as string[]); + this.compileFiles = new Map(); this.outputDir = buildConfig.loaderOutPath as string; this.cacheDir = buildConfig.cachePath as string; this.pandaSdkPath = buildConfig.pandaSdkPath as string; @@ -106,7 +107,16 @@ export abstract class BaseMode { this.moduleRootPath = buildConfig.moduleRootPath as string; this.moduleType = buildConfig.moduleType as string; this.dependentModuleList = buildConfig.dependentModuleList; + this.moduleInfos = new Map(); + this.mergedAbcFile = path.resolve(this.outputDir, MERGED_ABC_FILE); + this.dependencyJsonFile = path.resolve(this.cacheDir, DEPENDENCY_JSON_FILE); + this.abcLinkerCmd = ['"' + this.buildConfig.abcLinkerPath + '"']; + this.dependencyAnalyzerCmd = ['"' + this.buildConfig.dependencyAnalyzerPath + '"']; + this.logger = Logger.getInstance(); this.isDebug = buildConfig.buildMode as string === BUILD_MODE.DEBUG; + this.enableDeclgenEts2Ts = buildConfig.enableDeclgenEts2Ts as boolean; + this.declgenV1OutPath = buildConfig.declgenV1OutPath as string | undefined; + this.declgenBridgeCodePath = buildConfig.declgenBridgeCodePath as string | undefined; this.hasMainModule = buildConfig.hasMainModule; this.abcFiles = new Set(); this.hashCacheFile = path.join(this.cacheDir, 'hash_cache.json'); @@ -114,37 +124,24 @@ export abstract class BaseMode { this.isCacheFileExists = fs.existsSync(this.hashCacheFile); this.dependencyFileMap = null; this.isBuildConfigModified = buildConfig.isBuildConfigModified as boolean | undefined; - - this.enableDeclgenEts2Ts = buildConfig.enableDeclgenEts2Ts as boolean; - this.declgenV1OutPath = buildConfig.declgenV1OutPath as string | undefined; - this.declgenBridgeCodePath = buildConfig.declgenBridgeCodePath as string | undefined; - - this.moduleInfos = new Map(); - this.compileFiles = new Map(); - this.mergedAbcFile = path.resolve(this.outputDir, MERGED_ABC_FILE); - this.dependencyJsonFile = path.resolve(this.cacheDir, DEPENDENCY_JSON_FILE); - this.abcLinkerCmd = ['"' + this.buildConfig.abcLinkerPath + '"']; - this.dependencyAnalyzerCmd = ['"' + this.buildConfig.dependencyAnalyzerPath + '"']; - - this.logger = Logger.getInstance(); } public declgen(fileInfo: CompileFileInfo): void { const source = fs.readFileSync(fileInfo.filePath, 'utf8'); - let moduleInfo: ModuleInfo = this.moduleInfos.get(fileInfo.packageName)!; - let filePathFromModuleRoot: string = path.relative(moduleInfo.moduleRootPath, fileInfo.filePath); - let declEtsOutputPath: string = changeDeclgenFileExtension( + const moduleInfo: ModuleInfo = this.moduleInfos.get(fileInfo.packageName)!; + const filePathFromModuleRoot: string = path.relative(moduleInfo.moduleRootPath, fileInfo.filePath); + const declEtsOutputPath: string = changeDeclgenFileExtension( path.join(moduleInfo.declgenV1OutPath as string, moduleInfo.packageName, filePathFromModuleRoot), DECL_ETS_SUFFIX ); - let etsOutputPath: string = changeDeclgenFileExtension( + const etsOutputPath: string = changeDeclgenFileExtension( path.join(moduleInfo.declgenBridgeCodePath as string, moduleInfo.packageName, filePathFromModuleRoot), TS_SUFFIX ); ensurePathExists(declEtsOutputPath); ensurePathExists(etsOutputPath); - let arktsGlobal: ArkTSGlobal = this.buildConfig.arktsGlobal; - let arkts: ArkTS = this.buildConfig.arkts; + const arktsGlobal: ArkTSGlobal = this.buildConfig.arktsGlobal; + const arkts: ArkTS = this.buildConfig.arkts; let errorStatus = false; try { arktsGlobal.filePath = fileInfo.filePath; @@ -200,7 +197,7 @@ export abstract class BaseMode { public compile(fileInfo: CompileFileInfo): void { ensurePathExists(fileInfo.abcFilePath); - let ets2pandaCmd: string[] = [ + const ets2pandaCmd: string[] = [ '_', '--extension', 'ets', @@ -216,8 +213,8 @@ export abstract class BaseMode { ets2pandaCmd.push(fileInfo.filePath); this.logger.printInfo('ets2pandaCmd: ' + ets2pandaCmd.join(' ')); - let arktsGlobal = this.buildConfig.arktsGlobal; - let arkts = this.buildConfig.arkts; + const arktsGlobal = this.buildConfig.arktsGlobal; + const arkts = this.buildConfig.arkts; let errorStatus = false; try { arktsGlobal.filePath = fileInfo.filePath; @@ -299,8 +296,8 @@ export abstract class BaseMode { } private getDependentModules(moduleInfo: ModuleInfo): Map[] { - let dynamicDepModules: Map = new Map(); - let staticDepModules: Map = new Map(); + const dynamicDepModules: Map = new Map(); + const staticDepModules: Map = new Map(); if (moduleInfo.isMainModule) { this.moduleInfos.forEach((module: ModuleInfo, packageName: string) => { @@ -332,13 +329,13 @@ export abstract class BaseMode { } protected generateArkTSConfigForModules(): void { - this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { + this.moduleInfos.forEach((moduleInfo: ModuleInfo, _: string) => { ArkTSConfigGenerator.getInstance(this.buildConfig, this.moduleInfos).writeArkTSConfigFile(moduleInfo); }); } private collectDepModuleInfos(): void { - this.moduleInfos.forEach((moduleInfo) => { + this.moduleInfos.forEach((moduleInfo: ModuleInfo) => { let [dynamicDepModules, staticDepModules] = this.getDependentModules(moduleInfo); moduleInfo.dynamicDepModuleInfos = dynamicDepModules; moduleInfo.staticDepModuleInfos = staticDepModules; @@ -353,7 +350,7 @@ export abstract class BaseMode { ); this.logger.printError(logData); } - let mainModuleInfo: ModuleInfo = this.getMainModuleInfo(); + const mainModuleInfo: ModuleInfo = this.getMainModuleInfo(); this.moduleInfos.set(this.packageName, mainModuleInfo); this.dependentModuleList.forEach((module: DependentModuleConfig) => { if (!module.packageName || !module.modulePath || !module.sourceRoots || !module.entryFile) { @@ -363,7 +360,7 @@ export abstract class BaseMode { ); this.logger.printError(logData); } - let moduleInfo: ModuleInfo = { + const moduleInfo: ModuleInfo = { isMainModule: false, packageName: module.packageName, moduleRootPath: module.modulePath, @@ -439,7 +436,7 @@ export abstract class BaseMode { if (etsFileLastModified < abcFileLastModified) { const currentHash = getFileHash(etsFilePath); const cachedHash = this.hashCache[etsFilePath]; - if (cachedHash && currentHash === cachedHash) { + if (cachedHash && cachedHash === currentHash) { return false; } } @@ -464,7 +461,7 @@ export abstract class BaseMode { this.entryFiles.forEach((file: string) => { let hasModule = false; - for (const [packageName, moduleInfo] of this.moduleInfos) { + for (const [_, moduleInfo] of this.moduleInfos) { if (!file.startsWith(moduleInfo.moduleRootPath)) { continue; } @@ -513,7 +510,7 @@ export abstract class BaseMode { compileFiles.forEach((file: string) => { let hasModule = false; - for (const [packageName, moduleInfo] of this.moduleInfos) { + for (const [_, moduleInfo] of this.moduleInfos) { if (!file.startsWith(moduleInfo.moduleRootPath)) { continue; } @@ -559,20 +556,20 @@ export abstract class BaseMode { return; } this.entryFiles.forEach((file: string) => { - for (const [packageName, moduleInfo] of this.moduleInfos) { + for (const [_, moduleInfo] of this.moduleInfos) { const relativePath = path.relative(moduleInfo.moduleRootPath, file); if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) { 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)); + const filePathFromModuleRoot: string = path.relative(moduleInfo.moduleRootPath, file); + const filePathInCache: string = path.join(this.cacheDir, moduleInfo.packageName, filePathFromModuleRoot); + const abcFilePath: string = path.resolve(changeFileExtension(filePathInCache, ABC_SUFFIX)); this.abcFiles.add(abcFilePath); if (!this.isBuildConfigModified && this.shouldSkipFile(file, moduleInfo, filePathFromModuleRoot, abcFilePath)) { return; } this.hashCache[file] = getFileHash(file); - let fileInfo: CompileFileInfo = { + const fileInfo: CompileFileInfo = { filePath: file, dependentFiles: [], abcFilePath: abcFilePath, @@ -605,7 +602,7 @@ export abstract class BaseMode { this.generateModuleInfos(); const compilePromises: Promise[] = []; - this.compileFiles.forEach((fileInfo: CompileFileInfo, file: string) => { + this.compileFiles.forEach((fileInfo: CompileFileInfo, _: string) => { compilePromises.push(new Promise((resolve) => { this.declgen(fileInfo); resolve(); @@ -618,7 +615,7 @@ export abstract class BaseMode { this.generateModuleInfos(); const compilePromises: Promise[] = []; - this.compileFiles.forEach((fileInfo: CompileFileInfo, file: string) => { + this.compileFiles.forEach((fileInfo: CompileFileInfo, _: string) => { compilePromises.push(new Promise((resolve) => { this.compile(fileInfo); resolve(); @@ -639,7 +636,7 @@ export abstract class BaseMode { if (this.isBuildConfigModified || !this.isCacheFileExists || this.enableDeclgenEts2Ts) { return; } - let dependencyInputFile: string = path.join(this.cacheDir, DEPENDENCY_INPUT_FILE); + const dependencyInputFile: string = path.join(this.cacheDir, DEPENDENCY_INPUT_FILE); let dependencyInputContent: string = ''; this.entryFiles.forEach((entryFile: string) => { dependencyInputContent += entryFile + os.EOL; @@ -647,7 +644,7 @@ export abstract class BaseMode { fs.writeFileSync(dependencyInputFile, dependencyInputContent); this.dependencyAnalyzerCmd.push('@' + '"' + dependencyInputFile + '"'); - for (const [packageName, module] of this.moduleInfos) { + for (const [_, module] of this.moduleInfos) { if (module.isMainModule) { this.dependencyAnalyzerCmd.push('--arktsconfig=' + '"' + module.arktsConfigFile + '"'); break; -- Gitee From 3f7abc276615a32abb168c56e86d464875a7f29f Mon Sep 17 00:00:00 2001 From: oh-rgx Date: Mon, 30 Jun 2025 09:48:28 +0800 Subject: [PATCH 045/145] Fix method compare Issue: #ICIN1P Signed-off-by: oh-rgx --- ets2panda/checker/ETSchecker.h | 2 +- ets2panda/checker/ets/validateHelpers.cpp | 5 ++- ets2panda/compiler/core/ETSemitter.cpp | 11 ++++-- .../compiler/lowering/ets/lambdaLowering.cpp | 23 ++++++------ ets2panda/ir/base/classDefinition.h | 6 ++-- .../ast/parser/ets/FixedArray/StringFasta.ets | 3 -- ets2panda/test/ast/parser/ets/StringFasta.ets | 3 -- .../parser/ets/missing_in_for_statement_1.ets | 1 - .../parser/ets/missing_in_for_statement_2.ets | 1 - .../ast/parser/ets/unexpected_token_56.ets | 1 - ets2panda/test/runtime/ets/compare-method.ets | 26 ++++++++++++++ .../runtime/ets/overload-static-method.ets | 35 +++++++++++++++++++ 12 files changed, 91 insertions(+), 26 deletions(-) create mode 100644 ets2panda/test/runtime/ets/compare-method.ets create mode 100644 ets2panda/test/runtime/ets/overload-static-method.ets diff --git a/ets2panda/checker/ETSchecker.h b/ets2panda/checker/ETSchecker.h index 06de9f47df..16dcdb0da1 100644 --- a/ets2panda/checker/ETSchecker.h +++ b/ets2panda/checker/ETSchecker.h @@ -865,6 +865,7 @@ public: ir::MethodDefinition *CreateClassMethod(std::string_view name, ir::ScriptFunctionFlags funcFlags, ir::ModifierFlags modifierFlags, const MethodBuilder &builder); ir::ClassDeclaration *BuildClass(util::StringView name, const ClassBuilder &builder); + const varbinder::Variable *GetTargetRef(const ir::MemberExpression *memberExpr); void LogUnresolvedReferenceError(ir::Identifier *ident); void WrongContextErrorClassifyByType(ir::Identifier *ident); @@ -958,7 +959,6 @@ private: std::tuple IsResolvedAndValue(const ir::Expression *expr, Type *type) const; PropertySearchFlags GetSearchFlags(const ir::MemberExpression *memberExpr, const varbinder::Variable *targetRef); PropertySearchFlags GetInitialSearchFlags(const ir::MemberExpression *memberExpr); - const varbinder::Variable *GetTargetRef(const ir::MemberExpression *memberExpr); Type *GetTypeOfSetterGetter([[maybe_unused]] varbinder::Variable *var); void IterateInVariableContext([[maybe_unused]] varbinder::Variable *const var); bool CheckInit(ir::Identifier *ident, ir::TypeNode *typeAnnotation, ir::Expression *init, diff --git a/ets2panda/checker/ets/validateHelpers.cpp b/ets2panda/checker/ets/validateHelpers.cpp index f3ad9a385b..b27eecd8a1 100644 --- a/ets2panda/checker/ets/validateHelpers.cpp +++ b/ets2panda/checker/ets/validateHelpers.cpp @@ -174,7 +174,10 @@ void ETSChecker::ValidateResolvedIdentifier(ir::Identifier *const ident) if (ValidateBinaryExpressionIdentifier(ident, resolvedType)) { return; } - [[fallthrough]]; + if (resolved != nullptr && !resolved->Declaration()->PossibleTDZ() && !resolvedType->IsETSFunctionType()) { + WrongContextErrorClassifyByType(ident); + } + break; case ir::AstNodeType::UPDATE_EXPRESSION: case ir::AstNodeType::UNARY_EXPRESSION: if (resolved != nullptr && !resolved->Declaration()->PossibleTDZ()) { diff --git a/ets2panda/compiler/core/ETSemitter.cpp b/ets2panda/compiler/core/ETSemitter.cpp index f8b73b206f..66a81912f4 100644 --- a/ets2panda/compiler/core/ETSemitter.cpp +++ b/ets2panda/compiler/core/ETSemitter.cpp @@ -1004,10 +1004,17 @@ pandasm::AnnotationData ETSEmitter::GenAnnotationFunctionalReference(const ir::C { GenAnnotationRecord(Signatures::ETS_ANNOTATION_FUNCTIONAL_REFERENCE); pandasm::AnnotationData functionalReference(Signatures::ETS_ANNOTATION_FUNCTIONAL_REFERENCE); + bool isStatic = classDef->FunctionalReferenceReferencedMethod()->IsStatic(); pandasm::AnnotationElement value( Signatures::ANNOTATION_KEY_VALUE, - std::make_unique(pandasm::ScalarValue::Create( - const_cast(classDef)->FunctionalReferenceReferencedMethod().Mutf8()))); + std::make_unique( + pandasm::ScalarValue::Create(const_cast(classDef) + ->FunctionalReferenceReferencedMethod() + ->Function() + ->Scope() + ->InternalName() + .Mutf8(), + isStatic))); functionalReference.AddElement(std::move(value)); return functionalReference; } diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index df7f1a1a0b..c513801d30 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -857,7 +857,7 @@ static ir::ClassDeclaration *CreateLambdaClass(public_lib::Context *ctx, checker CreateEmptyLambdaClassDeclaration(ctx, info, newTypeParams, fnInterface, lambdaProviderClass); auto classDefinition = classDeclaration->Definition(); if (info->isFunctionReference) { - classDefinition->SetFunctionalReferenceReferencedMethod(callee->Function()->Scope()->InternalName()); + classDefinition->SetFunctionalReferenceReferencedMethod(callee); classDefinition->SetModifiers(classDefinition->Modifiers() | ir::ClassDefinitionModifiers::FUNCTIONAL_REFERENCE); } @@ -1047,11 +1047,17 @@ static ir::AstNode *ConvertFunctionReference(public_lib::Context *ctx, ir::Expre } else { auto *mexpr = funcRef->AsMemberExpression(); // NOTE(gogabr): mexpr->PropVar() is a synthetic variable wwith no reference to the method definition. Why? - 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); + auto refVar = ctx->checker->AsETSChecker()->GetTargetRef(mexpr); + auto flags = checker::PropertySearchFlags::SEARCH_IN_BASE | + checker::PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION; + if (refVar != nullptr && refVar->HasFlag(varbinder::VariableFlags::CLASS)) { + flags |= checker::PropertySearchFlags::SEARCH_STATIC_METHOD; + } else { + flags |= (checker::PropertySearchFlags::SEARCH_INSTANCE_METHOD | + checker::PropertySearchFlags::SEARCH_STATIC_METHOD); + } + var = + mexpr->Object()->TsType()->AsETSObjectType()->GetProperty(mexpr->Property()->AsIdentifier()->Name(), flags); ES2PANDA_ASSERT(var != nullptr); } @@ -1062,10 +1068,7 @@ static ir::AstNode *ConvertFunctionReference(public_lib::Context *ctx, ir::Expre // Direct reference to method will be impossible from the lambda class, so replace func ref with a lambda // that will translate to a proxy method auto *lam = CreateWrappingLambda(ctx, funcRef); - if (lam == nullptr) { - return funcRef; - } - return ConvertLambda(ctx, lam); + return lam == nullptr ? funcRef : ConvertLambda(ctx, lam); } LambdaInfo info; diff --git a/ets2panda/ir/base/classDefinition.h b/ets2panda/ir/base/classDefinition.h index 2eb349f8cc..0526e6128a 100644 --- a/ets2panda/ir/base/classDefinition.h +++ b/ets2panda/ir/base/classDefinition.h @@ -384,12 +384,12 @@ public: return localIndex_; } - [[nodiscard]] util::StringView FunctionalReferenceReferencedMethod() const noexcept + [[nodiscard]] MethodDefinition *FunctionalReferenceReferencedMethod() const noexcept { return functionalReferenceReferencedMethod_; } - void SetFunctionalReferenceReferencedMethod(util::StringView functionalReferenceReferencedMethod) + void SetFunctionalReferenceReferencedMethod(MethodDefinition *functionalReferenceReferencedMethod) { functionalReferenceReferencedMethod_ = functionalReferenceReferencedMethod; } @@ -531,7 +531,7 @@ private: static int classCounter_; int localIndex_ {}; std::string localPrefix_ {}; - util::StringView functionalReferenceReferencedMethod_ {}; + MethodDefinition *functionalReferenceReferencedMethod_ {}; ArenaVector exportedClasses_; }; } // namespace ark::es2panda::ir diff --git a/ets2panda/test/ast/parser/ets/FixedArray/StringFasta.ets b/ets2panda/test/ast/parser/ets/FixedArray/StringFasta.ets index b9680ece6b..2e97dc534f 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/StringFasta.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/StringFasta.ets @@ -169,15 +169,12 @@ function main(): void { /* @@? 95:65 Error TypeError: 'For-of' statement source expression is not of iterable type. */ /* @@? 103:20 Error TypeError: Type 'double' has no call signatures. */ /* @@? 112:16 Error TypeError: Static property 'fastaRepeat' must be accessed through it's class 'StringFasta' */ -/* @@? 112:32 Error TypeError: Function name 'count' used in the wrong context */ /* @@? 112:28 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 112:48 Error TypeError: Static property 'ALU' must be accessed through it's class 'StringFasta' */ /* @@? 113:16 Error TypeError: Static property 'fastaRandom' must be accessed through it's class 'StringFasta' */ -/* @@? 113:32 Error TypeError: Function name 'count' used in the wrong context */ /* @@? 113:28 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 113:46 Error TypeError: Static property 'IUB' must be accessed through it's class 'StringFasta' */ /* @@? 114:16 Error TypeError: Static property 'fastaRandom' must be accessed through it's class 'StringFasta' */ -/* @@? 114:32 Error TypeError: Function name 'count' used in the wrong context */ /* @@? 114:28 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 114:46 Error TypeError: Static property 'HomoSap' must be accessed through it's class 'StringFasta' */ /* @@? 116:28 Error TypeError: 'expected' is a static property of 'StringFasta' */ diff --git a/ets2panda/test/ast/parser/ets/StringFasta.ets b/ets2panda/test/ast/parser/ets/StringFasta.ets index a448ec8c02..f36d7cbf6b 100644 --- a/ets2panda/test/ast/parser/ets/StringFasta.ets +++ b/ets2panda/test/ast/parser/ets/StringFasta.ets @@ -169,15 +169,12 @@ function main(): void { /* @@? 95:65 Error TypeError: 'For-of' statement source expression is not of iterable type. */ /* @@? 103:20 Error TypeError: Type 'double' has no call signatures. */ /* @@? 112:16 Error TypeError: Static property 'fastaRepeat' must be accessed through it's class 'StringFasta' */ -/* @@? 112:32 Error TypeError: Function name 'count' used in the wrong context */ /* @@? 112:28 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 112:48 Error TypeError: Static property 'ALU' must be accessed through it's class 'StringFasta' */ /* @@? 113:16 Error TypeError: Static property 'fastaRandom' must be accessed through it's class 'StringFasta' */ -/* @@? 113:32 Error TypeError: Function name 'count' used in the wrong context */ /* @@? 113:28 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 113:46 Error TypeError: Static property 'IUB' must be accessed through it's class 'StringFasta' */ /* @@? 114:16 Error TypeError: Static property 'fastaRandom' must be accessed through it's class 'StringFasta' */ -/* @@? 114:32 Error TypeError: Function name 'count' used in the wrong context */ /* @@? 114:28 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 114:46 Error TypeError: Static property 'HomoSap' must be accessed through it's class 'StringFasta' */ /* @@? 116:28 Error TypeError: 'expected' is a static property of 'StringFasta' */ diff --git a/ets2panda/test/ast/parser/ets/missing_in_for_statement_1.ets b/ets2panda/test/ast/parser/ets/missing_in_for_statement_1.ets index e348adfa0f..05cbe6e2fd 100644 --- a/ets2panda/test/ast/parser/ets/missing_in_for_statement_1.ets +++ b/ets2panda/test/ast/parser/ets/missing_in_for_statement_1.ets @@ -19,7 +19,6 @@ for /* @@ label */let i = 0; i < count; ++i) { /* @@@ label Error SyntaxError: Expected '(', got 'let'. */ /* @@? 16:30 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ -/* @@? 16:34 Error TypeError: Function name 'count' used in the wrong context */ /* @@? 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. */ diff --git a/ets2panda/test/ast/parser/ets/missing_in_for_statement_2.ets b/ets2panda/test/ast/parser/ets/missing_in_for_statement_2.ets index b8ba1653ee..ca20535a7b 100644 --- a/ets2panda/test/ast/parser/ets/missing_in_for_statement_2.ets +++ b/ets2panda/test/ast/parser/ets/missing_in_for_statement_2.ets @@ -17,7 +17,6 @@ for (let i = 0; i < count; ++i /* @@ label */{ result = result + p[i]!.awaitResolution() * /* @@label1 */a[i]; } -/* @@? 16:21 Error TypeError: Function name 'count' used in the wrong context */ /* @@? 16:17 Error TypeError: Bad operand type, the types of the operands must be numeric, same enumeration, or boolean type. */ /* @@@ label Error SyntaxError: Expected ')', got '{'. */ /* @@? 17:5 Error TypeError: Unresolved reference result */ diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_56.ets b/ets2panda/test/ast/parser/ets/unexpected_token_56.ets index 68f8b04937..2042f939a6 100644 --- a/ets2panda/test/ast/parser/ets/unexpected_token_56.ets +++ b/ets2panda/test/ast/parser/ets/unexpected_token_56.ets @@ -22,7 +22,6 @@ for (let i?: Number = 1;;) { break; } /* @@@ 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 ')'. */ /* @@@ label7 Error SyntaxError: Unexpected token '{'. */ diff --git a/ets2panda/test/runtime/ets/compare-method.ets b/ets2panda/test/runtime/ets/compare-method.ets new file mode 100644 index 0000000000..8ac5c99647 --- /dev/null +++ b/ets2panda/test/runtime/ets/compare-method.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 foo() {} +function bar() {} +function goo(a: number) {} + +function main() { + arktest.assertEQ(foo == foo, true); + arktest.assertEQ(foo == bar, false); + arktest.assertEQ(foo == goo, false); + arktest.assertEQ(bar == goo, false); + arktest.assertEQ(goo == goo, true); +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/overload-static-method.ets b/ets2panda/test/runtime/ets/overload-static-method.ets new file mode 100644 index 0000000000..b55854600a --- /dev/null +++ b/ets2panda/test/runtime/ets/overload-static-method.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. + */ + +class A { + method() {} + static method(){} +} + +class B { + foo() {} + static foo(){} +} + +function main() { + let a = new A(); + let b = new B(); + arktest.assertEQ(a.method == a.method, true); + arktest.assertEQ(A.method == A.method, true); + arktest.assertEQ(b.foo == A.method, false); + arktest.assertEQ(B.foo == A.method, false); + arktest.assertEQ(B.foo == a.method, false); + arktest.assertEQ(b.foo == a.method, false); +} \ No newline at end of file -- Gitee From c7088f333dd33232b70532cfee76767c3938c477 Mon Sep 17 00:00:00 2001 From: Georgy Bronnikov Date: Mon, 23 Jun 2025 07:51:32 +0300 Subject: [PATCH 046/145] Fix bug from instanceof and generics Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGV43 Signed-off-by: Georgy Bronnikov --- ets2panda/checker/ETSAnalyzer.cpp | 1 + ets2panda/checker/ets/object.cpp | 9 +++++- ets2panda/test/runtime/ets/27016.ets | 41 ++++++++++++++++++++++++++ ets2panda/test/runtime/ets/27016_2.ets | 33 +++++++++++++++++++++ 4 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/runtime/ets/27016.ets create mode 100644 ets2panda/test/runtime/ets/27016_2.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index f8f1ec7e37..06efd4e454 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -3632,6 +3632,7 @@ checker::Type *ETSAnalyzer::Check(ir::TSQualifiedName *expr) const checker::Type *ETSAnalyzer::Check(ir::TSTypeAliasDeclaration *st) const { ETSChecker *checker = GetETSChecker(); + auto checkerContext = SavedCheckerContext(checker, CheckerStatus::NO_OPTS, checker->Context().ContainingClass()); checker->CheckAnnotations(st->Annotations()); diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index c5724a9d7e..7f957d9fa1 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -440,6 +440,13 @@ Type *ETSChecker::BuildBasicInterfaceProperties(ir::TSInterfaceDeclaration *inte interfaceType = var->TsType()->AsETSObjectType(); } + // Save before we mess with savedContext. + bool builtinsInitialized = HasStatus(CheckerStatus::BUILTINS_INITIALIZED); + + auto *enclosingClass = Context().ContainingClass(); + interfaceType->SetEnclosingType(enclosingClass); + CheckerStatus newStatus = CheckerStatus::IN_INTERFACE; + auto savedContext = checker::SavedCheckerContext(this, newStatus, interfaceType); ConstraintCheckScope ctScope(this); if (interfaceDecl->TypeParams() != nullptr) { interfaceType->AddTypeFlag(TypeFlag::GENERIC); @@ -453,7 +460,7 @@ Type *ETSChecker::BuildBasicInterfaceProperties(ir::TSInterfaceDeclaration *inte // Skip this check if the builtins are not initialized. // They will be initialized in different order, // and it is possible that the FunctionType interface is not yet created. - if (HasStatus(CheckerStatus::BUILTINS_INITIALIZED)) { + if (builtinsInitialized) { CheckInterfaceFunctions(interfaceType); } diff --git a/ets2panda/test/runtime/ets/27016.ets b/ets2panda/test/runtime/ets/27016.ets new file mode 100644 index 0000000000..fa618d9c23 --- /dev/null +++ b/ets2panda/test/runtime/ets/27016.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 NNBB { + static f(a: Object) { + return a instanceof B + } +} + +interface A { + get(): TA +} +interface B extends A { +} + +class D implements B { + constructor(d: TD) { + this.d = d + } + get(): TD { + return this.d + } + d: TD +} + +function main() { + let a: A = new D(5) + arktest.assertEQ(a.get(), 5) +} diff --git a/ets2panda/test/runtime/ets/27016_2.ets b/ets2panda/test/runtime/ets/27016_2.ets new file mode 100644 index 0000000000..9e95ee41cd --- /dev/null +++ b/ets2panda/test/runtime/ets/27016_2.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 A { + f(b: object) { + b instanceof B + let c: B = {v: 1} + return c + } +} + +type B = C + +interface C { + v: T +} + +function main() { + let a = new A + arktest.assertEQ(a.f(a).v, 1) +} -- Gitee From 9b6d390f31984f25f6dad3557985b7851aeae1d8 Mon Sep 17 00:00:00 2001 From: ekkoruse Date: Tue, 24 Jun 2025 00:10:39 +0800 Subject: [PATCH 047/145] Compile simultaneously for build_system support compile simultaneously Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICDR65?from=project-issue Change-Id: I4c3b7fc48469c2cc1cc6febb1113f4467a2a2eb6 Signed-off-by: zenghang --- ets2panda/driver/build_system/package.json | 11 +- .../build_system/src/build/base_mode.ts | 111 ++++++++++++++---- ets2panda/driver/build_system/src/types.ts | 1 + 3 files changed, 91 insertions(+), 32 deletions(-) diff --git a/ets2panda/driver/build_system/package.json b/ets2panda/driver/build_system/package.json index 597e3abe96..5d9fe607cc 100644 --- a/ets2panda/driver/build_system/package.json +++ b/ets2panda/driver/build_system/package.json @@ -8,20 +8,15 @@ "clean": "rimraf dist", "build": "npm run clean && tsc", "build_debug": "npm run clean && tsc --sourceMap", - "mixed_hap:gen_decl": "npm run build && node ./dist/entry.js test/demo_mix_hap/build_config_decl.json", "mixed_hap:gen_abc": "node ./dist/entry.js test/demo_mix_hap/build_config.json", "mixed_hap:run": "npm run mixed_hap:gen_decl && npm run mixed_hap:gen_abc", - "demo_hap:gen_abc": "npm run build && node ./dist/entry.js test/demo_hap/build_config.json" }, "devDependencies": { - "typescript": "^5.0.0", - "@types/node": "22.10.7", "@tsconfig/recommended": "1.0.8", - "rimraf": "6.0.1" - }, - "dependencies": { - + "@types/node": "22.10.7", + "rimraf": "^6.0.1", + "typescript": "^5.0.0" } } diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 2b5e6213d6..745a5482da 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -260,6 +260,63 @@ export abstract class BaseMode { } } + public compileMultiFiles(filePaths: string[], moduleInfo: ModuleInfo): void { + let ets2pandaCmd: string[] = [ + '_', + '--extension', + 'ets', + '--arktsconfig', + moduleInfo.arktsConfigFile, + '--output', + path.resolve(this.outputDir, MERGED_ABC_FILE), + '--simultaneous' + ]; + ensurePathExists(path.resolve(this.outputDir, MERGED_ABC_FILE)); + if (this.isDebug) { + ets2pandaCmd.push('--debug-info'); + } + ets2pandaCmd.push(this.buildConfig.compileFiles[0]); + this.logger.printInfo('ets2pandaCmd: ' + ets2pandaCmd.join(' ')); + + let arktsGlobal = this.buildConfig.arktsGlobal; + let arkts = this.buildConfig.arkts; + let errorStatus = false; + try { + arktsGlobal.config = arkts.Config.create(ets2pandaCmd).peer; + //@ts-ignore + arktsGlobal.compilerContext = arkts.Context.createContextGenerateAbcForExternalSourceFiles(this.buildConfig.compileFiles);; + PluginDriver.getInstance().getPluginContext().setArkTSProgram(arktsGlobal.compilerContext.program); + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, arktsGlobal.compilerContext.peer); + this.logger.printInfo('es2panda proceedToState parsed'); + let ast = arkts.EtsScript.fromContext(); + PluginDriver.getInstance().getPluginContext().setArkTSAst(ast); + PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); + this.logger.printInfo('plugin parsed finished'); + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, arktsGlobal.compilerContext.peer); + this.logger.printInfo('es2panda proceedToState checked'); + + ast = arkts.EtsScript.fromContext(); + PluginDriver.getInstance().getPluginContext().setArkTSAst(ast); + PluginDriver.getInstance().runPluginHook(PluginHook.CHECKED); + this.logger.printInfo('plugin checked finished'); + + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED, arktsGlobal.compilerContext.peer); + this.logger.printInfo('es2panda bin generated'); + } catch (error) { + errorStatus = true; + throw error; + } finally { + if (!errorStatus) { + // when error occur,wrapper will destroy context. + arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + } + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + arkts.destroyConfig(arktsGlobal.config); + } + } + public mergeAbcFiles(): void { let linkerInputFile: string = path.join(this.cacheDir, LINKER_INPUT_FILE); let linkerInputContent: string = ''; @@ -542,19 +599,15 @@ export abstract class BaseMode { } }); } - + private shouldSkipFile(file: string, moduleInfo: ModuleInfo, filePathFromModuleRoot: string, abcFilePath: string): boolean { const targetPath = this.enableDeclgenEts2Ts - ? changeFileExtension(path.join(moduleInfo.declgenBridgeCodePath as string, moduleInfo.packageName, filePathFromModuleRoot), TS_SUFFIX) - : abcFilePath; + ? changeFileExtension(path.join(moduleInfo.declgenBridgeCodePath as string, moduleInfo.packageName, filePathFromModuleRoot), TS_SUFFIX) + : abcFilePath; return !this.isFileChanged(file, targetPath); } protected collectCompileFiles(): void { - if (!this.isBuildConfigModified && this.isCacheFileExists && !this.enableDeclgenEts2Ts) { - this.collectDependentCompileFiles(); - return; - } this.entryFiles.forEach((file: string) => { for (const [_, moduleInfo] of this.moduleInfos) { const relativePath = path.relative(moduleInfo.moduleRootPath, file); @@ -614,16 +667,26 @@ export abstract class BaseMode { public async run(): Promise { this.generateModuleInfos(); - const compilePromises: Promise[] = []; + let moduleToFile = new Map(); this.compileFiles.forEach((fileInfo: CompileFileInfo, _: string) => { - compilePromises.push(new Promise((resolve) => { - this.compile(fileInfo); - resolve(); - })); + if (!moduleToFile.has(fileInfo.packageName)) { + moduleToFile.set(fileInfo.packageName, []); + } + moduleToFile.get(fileInfo.packageName)?.push(fileInfo.filePath); }); - await Promise.all(compilePromises); - - this.mergeAbcFiles(); + try { + //@ts-ignore + this.compileMultiFiles([], this.moduleInfos.get(this.packageName)); + } catch (error) { + if (error instanceof Error) { + const logData: LogData = LogDataFactory.newInstance( + ErrorCode.BUILDSYSTEM_COMPILE_ABC_FAIL, + 'Compile abc files failed.', + error.message + ); + this.logger.printErrorAndExit(logData); + } + } } private terminateAllWorkers(): void { @@ -646,8 +709,8 @@ export abstract class BaseMode { this.dependencyAnalyzerCmd.push('@' + '"' + dependencyInputFile + '"'); for (const [_, module] of this.moduleInfos) { if (module.isMainModule) { - this.dependencyAnalyzerCmd.push('--arktsconfig=' + '"' + module.arktsConfigFile + '"'); - break; + this.dependencyAnalyzerCmd.push('--arktsconfig=' + '"' + module.arktsConfigFile + '"'); + break; } } this.dependencyAnalyzerCmd.push('--output=' + '"' + this.dependencyJsonFile + '"'); @@ -660,7 +723,7 @@ export abstract class BaseMode { ensurePathExists(this.dependencyJsonFile); try { - const output = child_process.execSync(dependencyAnalyzerCmdStr, { + const output = child_process.execSync(dependencyAnalyzerCmdStr, { stdio: 'pipe', encoding: 'utf-8' }); @@ -680,10 +743,10 @@ export abstract class BaseMode { const execError = error as child_process.ExecException; let fullErrorMessage = execError.message; if (execError.stderr) { - fullErrorMessage += `\nError output: ${execError.stderr}`; + fullErrorMessage += `\nError output: ${execError.stderr}`; } if (execError.stdout) { - fullErrorMessage += `\nOutput: ${execError.stdout}`; + fullErrorMessage += `\nOutput: ${execError.stdout}`; } const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_Dependency_Analyze_FAIL, @@ -736,7 +799,7 @@ export abstract class BaseMode { await this.dispatchTasks(); this.logger.printInfo('All declaration generation tasks complete.'); } catch (error) { - this.logger.printError(LogDataFactory.newInstance( + this.logger.printError(LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_DECLGEN_FAIL, 'Generate declaration files failed.' )); @@ -773,7 +836,7 @@ export abstract class BaseMode { const worker = cluster.fork(); this.setupWorkerMessageHandler(worker); - worker.send({ taskList: taskChunk, buildConfig: serializableConfig, moduleInfos: moduleInfosArray}); + worker.send({ taskList: taskChunk, buildConfig: serializableConfig, moduleInfos: moduleInfosArray }); const exitPromise = new Promise((resolve, reject) => { worker.on('exit', (status) => status === 0 ? resolve() : reject()); @@ -836,11 +899,11 @@ export abstract class BaseMode { execPath, execArgs = [], } = options; - + if (clearExitListeners) { cluster.removeAllListeners('exit'); } - + cluster.setupPrimary({ exec: execPath, execArgv: execArgs, diff --git a/ets2panda/driver/build_system/src/types.ts b/ets2panda/driver/build_system/src/types.ts index fa82a48003..7a49cc64f5 100644 --- a/ets2panda/driver/build_system/src/types.ts +++ b/ets2panda/driver/build_system/src/types.ts @@ -44,6 +44,7 @@ export interface ArkTSGlobal { export interface ArkTS { Config: { create: Function; + createContextGenerateAbcForExternalSourceFiles: Function; }; Context: { createFromString: Function; -- Gitee From cc3aadba9ee85029cb2ec029de79433c2693e68e Mon Sep 17 00:00:00 2001 From: tengtengh Date: Mon, 30 Jun 2025 10:24:12 +0800 Subject: [PATCH 048/145] Fix es2panda abort Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJN8Z Signed-off-by: tengtengh --- ets2panda/checker/ets/helpers.cpp | 12 ++++- .../parser/ets/invalid_lambda_parameter.ets | 27 ++++++++++ ets2panda/test/runtime/ets/typeAlias_1.ets | 20 +++++++ ets2panda/util/diagnostic/semantic.yaml | 52 +++++++++++++++++++ 4 files changed, 109 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/invalid_lambda_parameter.ets create mode 100644 ets2panda/test/runtime/ets/typeAlias_1.ets diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index a9b83658ec..b3ac490f1a 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -1512,8 +1512,8 @@ static void CollectAliasParametersForBoxing(Type *expandedAliasType, std::setIsETSObjectType()) { auto objectType = expandedAliasType->AsETSObjectType(); - needToBeBoxed = - objectType->GetDeclNode()->IsClassDefinition() || objectType->GetDeclNode()->IsTSInterfaceDeclaration(); + needToBeBoxed = objectType->GetDeclNode() != nullptr && (objectType->GetDeclNode()->IsClassDefinition() || + objectType->GetDeclNode()->IsTSInterfaceDeclaration()); for (const auto typeArgument : objectType->TypeArguments()) { CollectAliasParametersForBoxing(typeArgument, parametersNeedToBeBoxed, needToBeBoxed); } @@ -2522,6 +2522,10 @@ void ETSChecker::InferTypesForLambda(ir::ScriptFunction *lambda, ir::ETSFunction Signature *maybeSubstitutedFunctionSig) { for (size_t i = 0; i < lambda->Params().size(); ++i) { + if (!lambda->Params().at(i)->IsETSParameterExpression()) { + LogError(diagnostic::INVALID_LAMBDA_PARAMETER, lambda->Params().at(i)->Start()); + continue; + } auto *const lambdaParam = lambda->Params().at(i)->AsETSParameterExpression()->Ident(); if (lambdaParam->TypeAnnotation() == nullptr) { // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) @@ -2551,6 +2555,10 @@ void ETSChecker::InferTypesForLambda(ir::ScriptFunction *lambda, Signature *sign { ES2PANDA_ASSERT(signature->Params().size() >= lambda->Params().size()); for (size_t i = 0; i < lambda->Params().size(); ++i) { + if (!lambda->Params().at(i)->IsETSParameterExpression()) { + LogError(diagnostic::INVALID_LAMBDA_PARAMETER, lambda->Params().at(i)->Start()); + continue; + } auto *const lambdaParam = lambda->Params().at(i)->AsETSParameterExpression()->Ident(); if (lambdaParam->TypeAnnotation() == nullptr) { // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) diff --git a/ets2panda/test/ast/parser/ets/invalid_lambda_parameter.ets b/ets2panda/test/ast/parser/ets/invalid_lambda_parameter.ets new file mode 100644 index 0000000000..fc163f36e8 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/invalid_lambda_parameter.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 {} +class A { + constructor(callback: (entries: I[]) => void) {} +} + +function foo(entry: I) { + const x = new A(/* @@ label1 */([entry]) /* @@ label2 */=> { + }); +} + +/* @@@ label1 Error TypeError: Invalid lambda parameter. Expected: 'identifier(: type)?', 'identifier?(: type)?' or '...identifier(: type)?'. */ +/* @@@ label2 Error SyntaxError: Unexpected token '=>'. */ diff --git a/ets2panda/test/runtime/ets/typeAlias_1.ets b/ets2panda/test/runtime/ets/typeAlias_1.ets new file mode 100644 index 0000000000..b985bad474 --- /dev/null +++ b/ets2panda/test/runtime/ets/typeAlias_1.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. + */ + +type ValueAlias = Record<"val", V>; + +declare function value(): ValueAlias; + +function main() {} diff --git a/ets2panda/util/diagnostic/semantic.yaml b/ets2panda/util/diagnostic/semantic.yaml index ba0191e4ad..80fb740788 100644 --- a/ets2panda/util/diagnostic/semantic.yaml +++ b/ets2panda/util/diagnostic/semantic.yaml @@ -1494,3 +1494,55 @@ semantic: - name: CYCLIC_CALLEE id: 381 message: "Circular call function" + +- name: DYMANIC_INIT_WITH_OBJEXPR + id: 382 + message: "Dymanic Type {} cannot be initialize with an object expression" + +- name: OVERLOAD_NAME_MUST_BE_IDENTIFIER + id: 383 + message: "The name of overload declaration should be an identifier." + +- name: OVERLOADED_NAME_MUST_FUNCTION + id: 384 + message: "overloaded name must refer to an accessible method." + +- name: DUPLICATE_OVERLOADED_NAME + id: 385 + message: "Duplicate overloaded method." + +- name: OVERLOAD_SAME_ACCESS_MODIFIERS + id: 386 + message: "Overload alias and overloaded method name must have exactly the same modifiers (public, private, protected)." + +- name: OVERLOAD_SAME_ACCESS_MODIFIERS_STATIC_ASYNC + id: 387 + message: "Overload alias and overloaded method name must have exactly the same modifiers (static, async)." + +- name: OVERLOAD_MUST_BOTH_CONSTRUCT + id: 388 + message: "The overload alias and the overloaded method must either both be constructors or both be non-constructors." + +- name: OVERLOADED_NAME_REFER_TO_OVERLOAD_FUNCTION + id: 389 + message: "The overloaded name '{}' can't refer to a function with overload signatures." + +- name: OVERLOADED_NAME_MUST_ALSO_EXPORTED + id: 390 + message: "Overload alias is exported, then overload functions must also be exported." + +- name: OVERLOADED_UNION_CALL + id: 391 + message: "Overload declaration cannot be called by union." + +- name: OVERLOAD_MODIFIERS_ABSTRACT + id: 392 + message: "overload declaration cannot contain abstract methods." + +- name: INVALID_RECORD_PROPERTY + id: 393 + message: "Invalid record property" + +- name: INVALID_LAMBDA_PARAMETER + id: 394 + message: "Invalid lambda parameter. Expected: 'identifier(: type)?', 'identifier?(: type)?' or '...identifier(: type)?'." -- Gitee From b72a2664554d8333f923b78536bb808313aaa3cd Mon Sep 17 00:00:00 2001 From: leo9001 Date: Tue, 27 May 2025 16:41:03 +0800 Subject: [PATCH 049/145] support test cases for class hierarchies Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICAWA9 Signed-off-by: leo9001 --- ets2panda/lsp/src/class_hierarchy.cpp | 124 +++++++++++------- .../test/unit/lsp/class_hierarchys_test.cpp | 95 +++++++++++++- 2 files changed, 173 insertions(+), 46 deletions(-) diff --git a/ets2panda/lsp/src/class_hierarchy.cpp b/ets2panda/lsp/src/class_hierarchy.cpp index 7022639d66..368a3ac5a5 100644 --- a/ets2panda/lsp/src/class_hierarchy.cpp +++ b/ets2panda/lsp/src/class_hierarchy.cpp @@ -308,8 +308,8 @@ TypeHierarchiesInfo GetTypeHierarchiesImpl(es2panda_Context *context, size_t pos } /** - * @brief (查找当前类的父类) Retrieves the direct superclass of a given class declaration node - * @param node - AST node representing a class declaration + * @brief (查找当前类的父类) Find immediate superclass of current class node + * @param node - current class node declaration * @return Pointer to the direct superclass node or nullptr if not found */ ir::AstNode *GetClassDirectSuperClass(ir::AstNode *node) @@ -338,9 +338,9 @@ ir::AstNode *GetClassDirectSuperClass(ir::AstNode *node) } /** - * @brief (1. 查找当前类的(所有)父类) Collects all ancestor classes in the inheritance hierarchy + * @brief (1. 查找当前类的(所有)父类) Find all superclasses of the current class node * @param context - Compiler context (unused) - * @param node - Starting class declaration node + * @param node - Current class declaration node * @return Vector of superclass nodes in inheritance order */ std::vector GetClassSuperClasses([[maybe_unused]] es2panda_Context *context, ir::AstNode *node) @@ -361,9 +361,9 @@ std::vector GetClassSuperClasses([[maybe_unused]] es2panda_Contex } /** - * @brief (查找当前类的子类) Finds immediate subclasses of a given class + * @brief (查找当前类的子类) Find immediate subclass of current class node * @param program - Pointer to the program AST - * @param node - Class declaration node to check + * @param node - Current class declaration node * @return Set of direct subclass nodes */ std::unordered_set GetClassDirectSubClasses(ark::es2panda::parser::Program *program, ir::AstNode *node) @@ -394,9 +394,9 @@ std::unordered_set GetClassDirectSubClasses(ark::es2panda::parser } /** - * @brief (2. 查找当前类的(所有)子类) Discovers all subclasses in the inheritance hierarchy using BFS + * @brief (2. 查找当前类的(所有)子类) Find all possible implementing classes of current class node * @param context - Compiler context containing program AST - * @param node - Root class declaration node + * @param node - Current class declaration node * @return Vector of all subclass nodes */ std::vector GetClassSubClasses(es2panda_Context *context, ir::AstNode *node) @@ -432,8 +432,8 @@ std::vector GetClassSubClasses(es2panda_Context *context, ir::Ast } /** - * @brief (查找当前类的父接口) Extracts directly implemented interfaces from class declaration - * @param node - Class declaration node + * @brief (查找当前类的父接口) Find interface of current class node + * @param node - Current class declaration node * @return Set of directly implemented interface nodes */ std::unordered_set GetClassDirectImplementedInterfaces(ir::AstNode *node) @@ -461,8 +461,8 @@ std::unordered_set GetClassDirectImplementedInterfaces(ir::AstNod } /** - * @brief (查找当前接口的父接口) Gets directly extended interfaces from interface declaration - * @param node - Interface declaration node + * @brief (查找当前接口的父接口) Find which interfaces current interface node extends + * @param node - Current declaration node * @return Set of directly extended interface nodes */ std::unordered_set GetInterfaceDirectExtendedInterfaces(ir::AstNode *node) @@ -490,9 +490,9 @@ std::unordered_set GetInterfaceDirectExtendedInterfaces(ir::AstNo } /** - * @brief (3. 查找当前类的(所有)父接口) Aggregates all implemented interfaces including inherited ones + * @brief (3. 查找当前类的(所有)父接口) Find all interfaces extended by current class node * @param context - Compiler context (unused) - * @param node - Starting class declaration node + * @param node - Current class declaration node * @return Vector of implemented interface nodes */ std::vector GetClassImplementedInterfaces([[maybe_unused]] es2panda_Context *context, ir::AstNode *node) @@ -542,9 +542,9 @@ std::vector GetClassImplementedInterfaces([[maybe_unused]] es2pan } /** - * @brief (4. 查找当前接口的(所有)父接口) Collects all ancestor interfaces through extension hierarchy + * @brief (4. 查找当前接口的(所有)父接口) Find all interfaces extended by current interface node * @param context - Compiler context (unused) - * @param node - Starting interface node + * @param node - Current interface node * @return Vector of ancestor interface nodes */ std::vector GetInterfaceSuperInterfaces([[maybe_unused]] es2panda_Context *context, ir::AstNode *node) @@ -558,7 +558,7 @@ std::vector GetInterfaceSuperInterfaces([[maybe_unused]] es2panda if (!visited.insert(currentNode).second) { return; } - auto extends = node->AsTSInterfaceDeclaration()->Extends(); + auto extends = currentNode->AsTSInterfaceDeclaration()->Extends(); for (auto extend : extends) { auto partNode = GetIdentifierFromTSInterfaceHeritage(extend); if (partNode == nullptr) { @@ -590,7 +590,7 @@ std::vector GetImplements(ir::AstNode *node) auto classDefinition = node->AsClassDefinition(); auto implements = classDefinition->Implements(); for (auto implement : implements) { - auto partNode = GetIdentifierFromTSInterfaceHeritage(implement->AsTSInterfaceHeritage()); + auto partNode = GetIdentifierFromTSInterfaceHeritage(implement); if (partNode == nullptr || !partNode->IsIdentifier()) { continue; } @@ -624,7 +624,6 @@ std::vector GetInterfaceOrClasses(es2panda_Context *context, ir:: [&](ir::AstNode *base) { return parentSet.count(base) > 0; }); if (isSubInterface) { result.push_back(child); - GetInterfaceOrClasses(context, child, isInterfaceMode); // 递归处理子接口 } } else { // The current interface gets the subclass @@ -643,29 +642,67 @@ std::vector GetInterfaceOrClasses(es2panda_Context *context, ir:: return result; } +void AddMissingExtends(std::vector &implementingClasses, const std::vector &extends) +{ + std::unordered_set existing(implementingClasses.begin(), implementingClasses.end()); + std::copy_if(extends.begin(), extends.end(), std::back_inserter(implementingClasses), + [&existing](ir::AstNode *node) { return existing.find(node) == existing.end(); }); +} + /** - * @brief (5|6、查找当前接口的(所有)子类或子接口) Finds all subclasses/sub-interfaces of the current interface node - * @param context - Compiler context with AST tree - * @param node - Target interface node to search from - * @return Vector of subclass/sub-interface nodes (includes both direct and nested) + * @brief (通用函数,用于查找接口的子接口或实现类及其子类) Generic function to find sub-interfaces or implementing + * classes and their subclasses of an interface + * @param context - Compiler context containing program AST + * @param node - Current interface node + * @param isInterfaceMode - Flag to determine lookup mode (true for interfaces, false for classes) + * @return Vector of found nodes */ -std::vector GetInterfaceImplementingClasses(es2panda_Context *context, ir::AstNode *node) +std::vector GetRelatedNodes(es2panda_Context *context, ir::AstNode *node, bool isInterfaceMode) { - std::vector implementingClasses; + std::vector result; auto ctx = reinterpret_cast(context); - auto rootNode = ctx->parserProgram->Ast(); - if (rootNode == nullptr) { - return implementingClasses; + if (ctx->parserProgram->Ast() == nullptr) { + return result; } - bool findSubInterfaces = true; - implementingClasses = GetInterfaceOrClasses(context, node, findSubInterfaces); - if (!findSubInterfaces) { - std::vector subInterfaces = GetInterfaceImplementingClasses(context, node); - for (auto subInterface : subInterfaces) { - implementingClasses = GetInterfaceOrClasses(context, subInterface, false); + result = GetInterfaceOrClasses(context, node, isInterfaceMode); + for (size_t i = 0; i < result.size(); ++i) { + auto elem = result[i]; + if (!isInterfaceMode && elem->IsClassDefinition()) { + elem = elem->Parent(); + result[i] = elem; } + std::vector extends; + if (isInterfaceMode) { + extends = GetRelatedNodes(context, elem, isInterfaceMode); + } else { + extends = GetClassSubClasses(context, elem); + } + AddMissingExtends(result, extends); } - return implementingClasses; + return result; +} + +/** + * @brief (5. 查找当前接口的(所有)子接口) Find all interfaces extended by current interface node + * @param context - Compiler context containing program AST + * @param node - Current interface node + * @return Vector of descendant interface nodes + */ +std::vector GetInterfaceSubInterfaces(es2panda_Context *context, ir::AstNode *node) +{ + return GetRelatedNodes(context, node, true); +} + +/** + * @brief (6. 查找当前接口的(所有)子类) Find all interfaces current interface node extends & their corresponding + * implementation classes + * @param context - Compiler context containing program AST + * @param node - Current interface node + * @return Vector of implementing class nodes + */ +std::vector GetInterfaceImplementingClasses(es2panda_Context *context, ir::AstNode *node) +{ + return GetRelatedNodes(context, node, false); } /** @@ -709,19 +746,16 @@ std::vector GetMembers([[maybe_unused]] es2panda_Context *context */ bool IsMethodMatch(ir::AstNode *a, ir::AstNode *b) { - if (!a->IsMethodDefinition() || !b->IsMethodDefinition()) { - return false; - } return GetIdentifierName(a) == GetIdentifierName(b); } /** - * @brief 比较成员匹配情况,记录匹配与未匹配项 - * @param currentMembers 当前类的成员列表 - * @param targetMembers 目标类的成员列表 - * @param matchedContainer 匹配成员的记录容器 - * @param unmatchedContainer 未匹配成员的记录容器 - * @param fileName 文件名,用于记录定位信息 + * @brief Compares member matches and records matched and unmatched items + * @param currentMembers the list of members in the current class + * @param targetMembers the list of members in the target class + * @param matchedContainer the container to record matched members + * @param unmatchedContainer the container to record unmatched members + * @param fileName the file name, used for recording location information */ void CompareMembersCommon(const std::vector ¤tMembers, const std::vector &targetMembers, @@ -814,7 +848,7 @@ std::vector GetClassHierarchiesImpl(es2panda_Context *co ProcessItemsParams {currentMembers, result, GetInterfaceSuperInterfaces, ClassRelationKind::INTERFACE, false, CompareMembersForOverride}); ProcessItems(context, classNode, fileName, - ProcessItemsParams {currentMembers, result, GetInterfaceImplementingClasses, + ProcessItemsParams {currentMembers, result, GetInterfaceSubInterfaces, ClassRelationKind::INTERFACE, true, CompareMembersForOverride}); ProcessItems(context, classNode, fileName, ProcessItemsParams {currentMembers, result, GetInterfaceImplementingClasses, diff --git a/ets2panda/test/unit/lsp/class_hierarchys_test.cpp b/ets2panda/test/unit/lsp/class_hierarchys_test.cpp index e946aed474..5a4647aeb9 100644 --- a/ets2panda/test/unit/lsp/class_hierarchys_test.cpp +++ b/ets2panda/test/unit/lsp/class_hierarchys_test.cpp @@ -32,7 +32,6 @@ using ark::es2panda::lsp::Initializer; class LspClassHierarchiesTests : public LSPAPITests {}; -std::vector fileNames = {"wangz_test.ets"}; std::vector fileContents = { R"( interface Iaa { @@ -120,6 +119,100 @@ TEST_F(LspClassHierarchiesTests, GetClassHierarchiesImpl_001) constexpr size_t expectedInfoCount = 5; constexpr size_t tokenOffset = 600; + std::vector fileNames = {"GetClassHierarchiesImpl_001_file1.ets"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + std::vector sourceFiles; + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents[i]); + } + ASSERT_EQ(fileNames.size(), sourceFiles.size()); + Initializer initializer; + size_t sourceIndex = 0; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + std::vector infos = + ark::es2panda::lsp::GetClassHierarchiesImpl(context, fileNames[sourceIndex], tokenOffset); + ASSERT_EQ(expectedInfoCount, infos.size()); +} + +TEST_F(LspClassHierarchiesTests, GetClassHierarchiesImpl_002) +{ + constexpr size_t expectedInfoCount = 5; + constexpr size_t tokenOffset = 1100; + + std::vector fileNames = {"GetClassHierarchiesImpl_002_file1.ets"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + std::vector sourceFiles; + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents[i]); + } + ASSERT_EQ(fileNames.size(), sourceFiles.size()); + Initializer initializer; + size_t sourceIndex = 0; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + std::vector infos = + ark::es2panda::lsp::GetClassHierarchiesImpl(context, fileNames[sourceIndex], tokenOffset); + ASSERT_EQ(expectedInfoCount, infos.size()); +} + +TEST_F(LspClassHierarchiesTests, GetClassHierarchiesImpl_003) +{ + constexpr size_t expectedInfoCount = 12; + constexpr size_t tokenOffset = 100; + + std::vector fileNames = {"GetClassHierarchiesImpl_003_file1.ets"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + std::vector sourceFiles; + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents[i]); + } + ASSERT_EQ(fileNames.size(), sourceFiles.size()); + Initializer initializer; + size_t sourceIndex = 0; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + std::vector infos = + ark::es2panda::lsp::GetClassHierarchiesImpl(context, fileNames[sourceIndex], tokenOffset); + ASSERT_EQ(expectedInfoCount, infos.size()); +} + +TEST_F(LspClassHierarchiesTests, GetClassHierarchiesImpl_004) +{ + constexpr size_t expectedInfoCount = 7; + constexpr size_t tokenOffset = 130; + + std::vector fileNames = {"GetClassHierarchiesImpl_004_file1.ets"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + std::vector sourceFiles; + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents[i]); + } + ASSERT_EQ(fileNames.size(), sourceFiles.size()); + Initializer initializer; + size_t sourceIndex = 0; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + std::vector infos = + ark::es2panda::lsp::GetClassHierarchiesImpl(context, fileNames[sourceIndex], tokenOffset); + ASSERT_EQ(expectedInfoCount, infos.size()); +} + +TEST_F(LspClassHierarchiesTests, GetClassHierarchiesImpl_005) +{ + constexpr size_t expectedInfoCount = 5; + constexpr size_t tokenOffset = 1000; + + std::vector fileNames = {"GetClassHierarchiesImpl_005_file1.ets"}; + auto filePaths = CreateTempFile(fileNames, fileContents); std::vector sourceFiles; for (size_t i = 0; i < filePaths.size(); ++i) { -- Gitee From 30e2958459e7679579767ec75e63d12d73d2b7e9 Mon Sep 17 00:00:00 2001 From: leo9001 Date: Wed, 28 May 2025 15:50:22 +0800 Subject: [PATCH 050/145] support organizeImports new function support organizeImports new function Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICB5WC Signed-off-by: leo9001 --- ets2panda/lsp/src/organize_imports.cpp | 15 +++- .../test/unit/lsp/organize_imports_test.cpp | 85 ++++++++++++------- 2 files changed, 67 insertions(+), 33 deletions(-) diff --git a/ets2panda/lsp/src/organize_imports.cpp b/ets2panda/lsp/src/organize_imports.cpp index aacf38ab47..c91ebd45bd 100644 --- a/ets2panda/lsp/src/organize_imports.cpp +++ b/ets2panda/lsp/src/organize_imports.cpp @@ -36,6 +36,13 @@ bool IsImportUsed(es2panda_Context *ctx, const ImportSpecifier &spec) } if (spec.type == ImportType::NAMESPACE) { + if (node->IsTSQualifiedName()) { + auto *qname = node->AsTSQualifiedName(); + found = qname->Left()->IsIdentifier() && + (std::string(qname->Left()->AsIdentifier()->Name()) == spec.localName); + return found; + } + if (node->IsMemberExpression()) { auto *member = node->AsMemberExpression(); found = member->Object()->IsIdentifier() && @@ -182,9 +189,9 @@ std::vector GenerateTextChanges(const std::vector &impor if (index + 1 < imp.namedImports.size()) { osst << ", "; } + index++; } - osst << " } from \"" << imp.moduleName << "\";\n"; - index++; + osst << " } from \'" << imp.moduleName << "\';\n"; }; for (const auto &imp : imports) { @@ -197,10 +204,10 @@ std::vector GenerateTextChanges(const std::vector &impor generateImportBlock(imp, oss, "import { "); break; case ImportType::DEFAULT: - oss << "import " << imp.namedImports[0].localName << " from \"" << imp.moduleName << "\";\n"; + oss << "import " << imp.namedImports[0].localName << " from \'" << imp.moduleName << "\';\n"; break; case ImportType::NAMESPACE: - oss << "import * as " << imp.namedImports[0].localName << " from \"" << imp.moduleName << "\";\n"; + oss << "import * as " << imp.namedImports[0].localName << " from \'" << imp.moduleName << "\';\n"; break; case ImportType::TYPE_ONLY: generateImportBlock(imp, oss, "import type { "); diff --git a/ets2panda/test/unit/lsp/organize_imports_test.cpp b/ets2panda/test/unit/lsp/organize_imports_test.cpp index 573c3dc35b..137fea4d9d 100644 --- a/ets2panda/test/unit/lsp/organize_imports_test.cpp +++ b/ets2panda/test/unit/lsp/organize_imports_test.cpp @@ -28,15 +28,15 @@ class OrganizeImportsTest : public LSPAPITests {}; TEST_F(OrganizeImportsTest, NormalImports) { - std::vector files = {"normal-imports-test.ets", "mod1/organize-imports-1.ets", - "mod2/organize-imports-2.ets"}; + std::vector files = {"normal-imports-test.ets", "organize-imports-1.ets", "organize-imports-2.ets"}; std::vector texts = { R"( - import {B, C} from "./mod1/organize-imports-1"; - import { X } from "./mod2/organize-imports-2"; + import {B, C, A} from "./organize-imports-1"; + import { X } from "./organize-imports-2"; const a = B; + const b = C; )", - R"(const A = 1; export default A; export const B = 2; export const C = 3;)", R"(export const X = 1;)"}; + R"(export const A = 1; export const B = 2; export const C = 3;)", R"(export const X = 1;)"}; auto filePaths = CreateTempFile(files, texts); Initializer initializer; @@ -49,20 +49,20 @@ TEST_F(OrganizeImportsTest, NormalImports) std::string result = changes[0].textChanges[0].newText; - EXPECT_TRUE(result.find("import { X } from \"./mod2/organize-imports-2\";") == std::string::npos); - EXPECT_TRUE(result.find("import { B } from \"./mod1/organize-imports-1\";") != std::string::npos); + EXPECT_TRUE(result.find("import { X } from \'./organize-imports-2\';") == std::string::npos); + EXPECT_TRUE(result.find("import { B, C } from \'./organize-imports-1\';") != std::string::npos); initializer.DestroyContext(ctx); } TEST_F(OrganizeImportsTest, TypeOnlyImports) { - std::vector files = {"typeonly-imports-test.ets", "mod1/typeonly-index.ets"}; + std::vector files = {"typeonly-imports-test.ets", "typeonly-index.ets"}; std::vector texts = { R"( - import type { T } from "./mod1/typeonly-index"; - import type {T as T1} from "./mod1/typeonly-index"; - import type {T as T2} from "./mod1/typeonly-index"; + import type { T } from "./typeonly-index"; + import type {T as T1} from "./typeonly-index"; + import type {T as T2} from "./typeonly-index"; let t: T1; function foo(arg: T2) {}; )", @@ -78,20 +78,20 @@ TEST_F(OrganizeImportsTest, TypeOnlyImports) std::string result = changes[0].textChanges[0].newText; - EXPECT_TRUE(result.find("import type { T } from \"./mod1/typeonly-index\";") == std::string::npos); - EXPECT_TRUE(result.find("import type { T as T1 } from \"./mod1/typeonly-index\";") != std::string::npos); - EXPECT_TRUE(result.find("import type { T as T2 } from \"./mod1/typeonly-index\";") != std::string::npos); + EXPECT_TRUE(result.find("import type { T } from \'./typeonly-index\';") == std::string::npos); + EXPECT_TRUE(result.find("import type { T as T1 } from \'./typeonly-index\';") != std::string::npos); + EXPECT_TRUE(result.find("import type { T as T2 } from \'./typeonly-index\';") != std::string::npos); initializer.DestroyContext(ctx); } TEST_F(OrganizeImportsTest, NamespaceImports) { - std::vector files = {"namespace-imports-test.ets", "mod1/namespace-imports-index.ets"}; + std::vector files = {"namespace-imports-test.ets", "namespace-imports-index.ets"}; std::vector texts = { R"( - import * as NS1 from "./mod1/namespace-imports-index"; - import * as NS2 from "./mod1/namespace-imports-index"; + import * as NS1 from "./namespace-imports-index"; + import * as NS2 from "./namespace-imports-index"; const b = NS1.color.red; )", R"(export const A = 1; export const B = 2;export enum color{red, blue, yellow};)"}; @@ -106,19 +106,19 @@ TEST_F(OrganizeImportsTest, NamespaceImports) std::string result = changes[0].textChanges[0].newText; - EXPECT_TRUE(result.find("import * as NS1 from \"./mod1/namespace-imports-index\";") != std::string::npos); - EXPECT_TRUE(result.find("import * as NS2 from \"./mod1/namespace-imports-index\";") == std::string::npos); + EXPECT_TRUE(result.find("import * as NS1 from \'./namespace-imports-index\';") != std::string::npos); + EXPECT_TRUE(result.find("import * as NS2 from \'./namespace-imports-index\';") == std::string::npos); initializer.DestroyContext(ctx); } TEST_F(OrganizeImportsTest, AliasImports) { - std::vector files = {"alias-imports-test.ets", "mod1/alias-imports-index.ets"}; + std::vector files = {"alias-imports-test.ets", "alias-imports-index.ets"}; std::vector texts = { R"( - import {B as B1, C} from "./mod1/alias-imports-index"; - import { B as B2 } from "./mod1/alias-imports-index"; + import {B as B1, C} from "./alias-imports-index"; + import { B as B2 } from "./alias-imports-index"; const b = B1; )", R"(export const B = 2; export const C = 3;)"}; @@ -133,19 +133,19 @@ TEST_F(OrganizeImportsTest, AliasImports) std::string result = changes[0].textChanges[0].newText; - EXPECT_TRUE(result.find("import { B as B1 } from \"./mod1/alias-imports-index\"") != std::string::npos); - EXPECT_TRUE(result.find("import { B as B2 } from \"./mod1/alias-imports-index\"") == std::string::npos); + EXPECT_TRUE(result.find("import { B as B1 } from \'./alias-imports-index\'") != std::string::npos); + EXPECT_TRUE(result.find("import { B as B2 } from \'./alias-imports-index\'") == std::string::npos); initializer.DestroyContext(ctx); } TEST_F(OrganizeImportsTest, DefaultImports) { - std::vector files = {"default-imports-test.ets", "mod1/default-imports-index.ets"}; + std::vector files = {"default-imports-test.ets", "default-imports-index.ets"}; std::vector texts = { R"( - import B from "./mod1/default-imports-index"; - import {C as C1} from "./mod1/default-imports-index"; + import B from "./default-imports-index"; + import {C as C1} from "./default-imports-index"; const b = B; const c = C1; )", @@ -161,8 +161,35 @@ TEST_F(OrganizeImportsTest, DefaultImports) std::string result = changes[0].textChanges[0].newText; - EXPECT_TRUE(result.find("import B from \"./mod1/default-imports-index\"") != std::string::npos); - EXPECT_TRUE(result.find("import { C as C1 } from \"./mod1/default-imports-index\"") != std::string::npos); + EXPECT_TRUE(result.find("import B from \'./default-imports-index\'") != std::string::npos); + EXPECT_TRUE(result.find("import { C as C1 } from \'./default-imports-index\'") != std::string::npos); + + initializer.DestroyContext(ctx); +} + +TEST_F(OrganizeImportsTest, SystemDefaultImports) +{ + std::vector files = {"system-default-imports-test.ets", "system-default-index.ets"}; + std::vector texts = { + R"( + import * as T1 from "./system-default-index"; + import * as T2 from "./system-default-index"; + let t: T2.T = "hello"; + )", + R"(export type T = string;)"}; + + auto filePaths = CreateTempFile(files, texts); + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + + std::vector changes = OrganizeImports::Organize(ctx, filePaths[0]); + + ASSERT_EQ(changes.size(), 1); + + std::string result = changes[0].textChanges[0].newText; + + EXPECT_TRUE(result.find("import * as T1 from \'./system-default-index\';") == std::string::npos); + EXPECT_TRUE(result.find("import * as T2 from \'./system-default-index\';") != std::string::npos); initializer.DestroyContext(ctx); } -- Gitee From 63a7b8d3705d06cfeb4e8de8203e4c2038e18e12 Mon Sep 17 00:00:00 2001 From: leo9001 Date: Thu, 29 May 2025 10:33:52 +0800 Subject: [PATCH 051/145] Add more tests and Fix bug Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC8GDW Signed-off-by: leo9001 --- ets2panda/lsp/src/completions_details.cpp | 3 + ets2panda/lsp/src/quick_info.cpp | 29 +- .../lsp/get_completions_entry_details.cpp | 299 ++++++++++++++++++ 3 files changed, 328 insertions(+), 3 deletions(-) diff --git a/ets2panda/lsp/src/completions_details.cpp b/ets2panda/lsp/src/completions_details.cpp index 54b46cc224..f82c5f40a4 100644 --- a/ets2panda/lsp/src/completions_details.cpp +++ b/ets2panda/lsp/src/completions_details.cpp @@ -109,6 +109,9 @@ CompletionEntryDetails GetCompletionEntryDetailsImpl(es2panda_Context *context, auto ast = ctx->parserProgram->Ast(); auto leIdentifier = ast->FindChild([entryName](ir::AstNode *node) { return HasPropertyAccessExpressionWithName(node, entryName); }); + if (leIdentifier == nullptr || !leIdentifier->IsIdentifier()) { + return CompletionEntryDetails(); + } auto targetNode = compiler::DeclarationFromIdentifier(leIdentifier->AsIdentifier()); if (targetNode == nullptr) { return CompletionEntryDetails(); diff --git a/ets2panda/lsp/src/quick_info.cpp b/ets2panda/lsp/src/quick_info.cpp index 1205f9ac5b..e79b26420d 100644 --- a/ets2panda/lsp/src/quick_info.cpp +++ b/ets2panda/lsp/src/quick_info.cpp @@ -680,6 +680,10 @@ std::vector CreateDisplayOfReturnType(ark::es2panda::ir::Type std::vector displayParts; displayParts.emplace_back(CreatePunctuation(":")); displayParts.emplace_back(CreateSpace()); + if (returnType == nullptr) { + displayParts.emplace_back(CreateReturnType("void")); + return displayParts; + } if (returnType->Type() == ir::AstNodeType::ETS_TYPE_REFERENCE) { auto part = returnType->AsETSTypeReference()->Part()->AsETSTypeReferencePart(); auto typeName = part->Name()->AsIdentifier()->Name(); @@ -946,9 +950,17 @@ std::vector CreateDisplayForMethodDefinition(ir::AstNode *nod if (node->Parent() != nullptr && node->Parent()->Type() == ir::AstNodeType::TS_INTERFACE_BODY) { return CreateDisplayForMethodDefinitionOfInterfaceBody(node); } + if (node->Parent() != nullptr && node->Parent()->IsClassDefinition()) { + auto className = node->Parent()->AsClassDefinition()->Ident()->Name(); + if (className != "ETSGLOBAL") { + displayParts.emplace_back(CreateClassName(std::string(className))); + displayParts.emplace_back(CreatePunctuation(".")); + } else { + displayParts.emplace_back(CreateKeyword("function")); + displayParts.emplace_back(CreateSpace()); + } + } - displayParts.emplace_back(CreateKeyword("function")); - displayParts.emplace_back(CreateSpace()); auto functionName = node->AsMethodDefinition()->Key()->AsIdentifier()->Name(); displayParts.emplace_back(CreateFunctionName(std::string(functionName))); @@ -978,6 +990,12 @@ std::vector CreateDisplayForMethodDefinition(ir::AstNode *nod return displayParts; } +bool IsKindModifierInSet(const std::string &target) +{ + static std::set kindModifierSet = {"const", "static public declare const"}; + return kindModifierSet.find(target) != kindModifierSet.end(); +} + std::vector CreateDisplayForClassProperty(ir::AstNode *node, const std::string &kindModifier) { std::vector displayParts; @@ -990,7 +1008,7 @@ std::vector CreateDisplayForClassProperty(ir::AstNode *node, if (className != "ETSGLOBAL") { displayParts.emplace_back(CreateClassName(std::string(className))); displayParts.emplace_back(CreatePunctuation(".")); - } else if (kindModifier == "const") { + } else if (IsKindModifierInSet(kindModifier)) { displayParts.emplace_back(CreateKeyword("const")); displayParts.emplace_back(CreateSpace()); } else { @@ -1005,6 +1023,11 @@ std::vector CreateDisplayForClassProperty(ir::AstNode *node, auto typeAnnotation = node->AsClassProperty()->TypeAnnotation(); std::string type; if (typeAnnotation == nullptr) { + if (node->AsClassProperty()->Value() == nullptr || + !node->AsClassProperty()->Value()->IsETSNewClassInstanceExpression()) { + displayParts.emplace_back(CreateTypeName("undefined")); + return displayParts; + } auto newClassExpr = node->AsClassProperty()->Value()->AsETSNewClassInstanceExpression(); if (newClassExpr != nullptr) { type = std::string(newClassExpr->GetTypeRef()->AsETSTypeReference()->Part()->GetIdent()->Name()); diff --git a/ets2panda/test/unit/lsp/get_completions_entry_details.cpp b/ets2panda/test/unit/lsp/get_completions_entry_details.cpp index d55b0df0f4..1bb64d6bba 100644 --- a/ets2panda/test/unit/lsp/get_completions_entry_details.cpp +++ b/ets2panda/test/unit/lsp/get_completions_entry_details.cpp @@ -18,6 +18,9 @@ #include "lsp/include/internal_api.h" #include "lsp/include/api.h" #include "lsp/include/completions_details.h" +#include "lsp/include/quick_info.h" +#include "lsp/include/suggestion_diagnostics.h" +#include "compiler/lowering/util.h" namespace { @@ -119,4 +122,300 @@ TEST_F(LSPCompletionsEntryDetailsTests, GetCompletionEntryDetails2) initializer.DestroyContext(ctx); } +TEST_F(LSPCompletionsEntryDetailsTests, GetCompletionEntryDetails3) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("completion_entry_details9.ets", ES2PANDA_STATE_CHECKED, + R"(function name (params: string) { + new CC().getName() +} + +class CC { + getName() { + } +})"); + size_t const offset = 79; + LSPAPI const *lspApi = GetImpl(); + const char *entryName = "getName"; + auto completionEntryDetails = + lspApi->getCompletionEntryDetails(entryName, "completion_entry_details9.ets", ctx, offset); + ASSERT_NE(completionEntryDetails, CompletionEntryDetails()); + std::vector source {}; + std::vector sourceDisplay {}; + std::vector document {}; + const std::string kind = "function"; + const std::string kindModifiers = "public"; + const std::string expectedFileName = "completion_entry_details9.ets"; + + std::vector expected; + expected.emplace_back("CC", "className"); + expected.emplace_back(".", "punctuation"); + expected.emplace_back("getName", "functionName"); + expected.emplace_back("(", "punctuation"); + expected.emplace_back(")", "punctuation"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("void", "returnType"); + + auto expectedCompletionEntryDetails = CompletionEntryDetails(entryName, kind, kindModifiers, expected, document, + source, sourceDisplay, expectedFileName); + initializer.DestroyContext(ctx); + ASSERT_EQ(completionEntryDetails, expectedCompletionEntryDetails); +} + +TEST_F(LSPCompletionsEntryDetailsTests, GetCompletionEntryDetails4) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("completion_entry_details10.ets", ES2PANDA_STATE_CHECKED, + R"(interface DuttonInterface { + ff(): number; +} + +declare const Dutton: DuttonInterface;)"); + size_t const offset = 66; + LSPAPI const *lspApi = GetImpl(); + const char *entryName = "Dutton"; + auto completionEntryDetails = + lspApi->getCompletionEntryDetails(entryName, "completion_entry_details10.ets", ctx, offset); + ASSERT_NE(completionEntryDetails, CompletionEntryDetails()); + std::vector source {}; + std::vector sourceDisplay {}; + std::vector document {}; + const std::string kind = "property"; + const std::string kindModifiers = "static public declare const"; + const std::string expectedFileName = "completion_entry_details10.ets"; + + std::vector expected; + expected.emplace_back("const", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("Dutton", "property"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("DuttonInterface", "typeName"); + + auto expectedCompletionEntryDetails = CompletionEntryDetails(entryName, kind, kindModifiers, expected, document, + source, sourceDisplay, expectedFileName); + initializer.DestroyContext(ctx); + ASSERT_EQ(completionEntryDetails, expectedCompletionEntryDetails); +} + +TEST_F(LSPCompletionsEntryDetailsTests, GetCompletionEntryDetails5) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("completion_entry_details11.ets", ES2PANDA_STATE_CHECKED, + R"(class DuttonInterface { + ff : number; + constructor(ff:number) { + this.ff = ff; + } + static buttonRun(value: string | number | boolean):number{ + return 1; + } +} + + function aa() { + let Dutton: DuttonInterface = new DuttonInterface(1); + let a = DuttonInterface.buttonRun(1) +})"); + size_t const offset = 280; + LSPAPI const *lspApi = GetImpl(); + const char *entryName = "buttonRun"; + auto completionEntryDetails = + lspApi->getCompletionEntryDetails(entryName, "completion_entry_details11.ets", ctx, offset); + ASSERT_NE(completionEntryDetails, CompletionEntryDetails()); + std::vector source {}; + std::vector sourceDisplay {}; + std::vector document {}; + const std::string kind = "function"; + const std::string kindModifiers = "static public"; + const std::string expectedFileName = "completion_entry_details11.ets"; + + std::vector expected; + expected.emplace_back("DuttonInterface", "className"); + expected.emplace_back(".", "punctuation"); + expected.emplace_back("buttonRun", "functionName"); + expected.emplace_back("(", "punctuation"); + expected.emplace_back("value", "functionParameter"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("string|number|boolean", "typeParameter"); + expected.emplace_back(")", "punctuation"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("number", "returnType"); + + auto expectedCompletionEntryDetails = CompletionEntryDetails(entryName, kind, kindModifiers, expected, document, + source, sourceDisplay, expectedFileName); + initializer.DestroyContext(ctx); + ASSERT_EQ(completionEntryDetails, expectedCompletionEntryDetails); +} + +TEST_F(LSPCompletionsEntryDetailsTests, CreateDisplayForClass) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = + initializer.CreateContext("completion_entry_details3.ets", ES2PANDA_STATE_CHECKED, + "class Test {\n private _a: number = 1;\n public get a(): number {\n " + "return this._a;\n }\n public static ccc:number = 1\n\n constructor(a : " + "number) {\n }\n}\n\nlet a = 1\nlet test: Test = new Test(a)\nlet t_a = test.a"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + const char *entryName = "Test"; + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [entryName](ark::es2panda::ir::AstNode *node) { + return ark::es2panda::lsp::HasPropertyAccessExpressionWithName(node, entryName); + }; + auto found = ast->FindChild(checkFunc); + auto targetNode = ark::es2panda::compiler::DeclarationFromIdentifier(found->AsIdentifier()); + std::vector display = ark::es2panda::lsp::CreateDisplayForClass(targetNode); + std::vector expected; + auto keyword1 = SymbolDisplayPart("class", "keyword"); + auto keyword2 = SymbolDisplayPart(" ", "space"); + auto keyword3 = SymbolDisplayPart("Test", "className"); + expected.push_back(keyword1); + expected.push_back(keyword2); + expected.push_back(keyword3); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsEntryDetailsTests, CreateDisplayForClassDeclarationTypeParameter) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("completion_entry_details4.ets", ES2PANDA_STATE_CHECKED, + "class Queue { private items: T[] = []; }"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + const char *entryName = "T"; + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [entryName](ark::es2panda::ir::AstNode *node) { + return ark::es2panda::lsp::HasPropertyAccessExpressionWithName(node, entryName); + }; + auto found = ast->FindChild(checkFunc); + auto targetNode = ark::es2panda::compiler::DeclarationFromIdentifier(found->AsIdentifier()); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeParameter(targetNode); + std::vector expected; + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(" ", "space"); + expected.emplace_back("in", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("Queue", "className"); + expected.emplace_back("<", "punctuation"); + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(">", "punctuation"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsEntryDetailsTests, CreateDisplayForUnionTypeAlias) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("completion_entry_details5.ets", ES2PANDA_STATE_CHECKED, + "type TestUnion = string | number;"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + const char *entryName = "TestUnion"; + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [entryName](ark::es2panda::ir::AstNode *node) { + return ark::es2panda::lsp::HasPropertyAccessExpressionWithName(node, entryName); + }; + auto found = ast->FindChild(checkFunc); + auto targetNode = ark::es2panda::compiler::DeclarationFromIdentifier(found->AsIdentifier()); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeAlias(targetNode); + std::vector expected; + expected.emplace_back("type", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("TestUnion", "className"); + expected.emplace_back(" ", "space"); + expected.emplace_back("=", "operator"); + expected.emplace_back(" ", "space"); + expected.emplace_back("string|number", "typeName"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsEntryDetailsTests, CreateDisplayForTypeAlias) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = + initializer.CreateContext("completion_entry_details6.ets", ES2PANDA_STATE_CHECKED, "type TestType = string;"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + const char *entryName = "TestType"; + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [entryName](ark::es2panda::ir::AstNode *node) { + return ark::es2panda::lsp::HasPropertyAccessExpressionWithName(node, entryName); + }; + auto found = ast->FindChild(checkFunc); + auto targetNode = ark::es2panda::compiler::DeclarationFromIdentifier(found->AsIdentifier()); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeAlias(targetNode); + std::vector expected; + expected.emplace_back("type", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("TestType", "className"); + expected.emplace_back(" ", "space"); + expected.emplace_back("=", "operator"); + expected.emplace_back(" ", "space"); + expected.emplace_back("string", "typeName"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsEntryDetailsTests, CreateDisplayForInterface) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext( + "completion_entry_details7.ets", ES2PANDA_STATE_CHECKED, + "interface Inner { key : string; }\ninterface Outer { inner : Inner; keyValue : number; }"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + const char *entryName = "Inner"; + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [entryName](ark::es2panda::ir::AstNode *node) { + return ark::es2panda::lsp::HasPropertyAccessExpressionWithName(node, entryName); + }; + auto found = ast->FindChild(checkFunc); + auto targetNode = ark::es2panda::compiler::DeclarationFromIdentifier(found->AsIdentifier()); + std::vector display = ark::es2panda::lsp::CreateDisplayForInterface(targetNode); + std::vector expected; + auto keyword1 = SymbolDisplayPart("interface", "keyword"); + auto keyword2 = SymbolDisplayPart(" ", "space"); + auto keyword3 = SymbolDisplayPart("Inner", "className"); + expected.push_back(keyword1); + expected.push_back(keyword2); + expected.push_back(keyword3); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsEntryDetailsTests, CreateDisplayForTypeAliasTypeParameter) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = + initializer.CreateContext("completion_entry_details8.ets", ES2PANDA_STATE_CHECKED, "type list = T[]"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + const char *entryName = "T"; + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [entryName](ark::es2panda::ir::AstNode *node) { + return ark::es2panda::lsp::HasPropertyAccessExpressionWithName(node, entryName); + }; + auto found = ast->FindChild(checkFunc); + auto targetNode = ark::es2panda::compiler::DeclarationFromIdentifier(found->AsIdentifier()); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeParameter(targetNode); + std::vector expected; + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(" ", "space"); + expected.emplace_back("in", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("type", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("list", "typeName"); + expected.emplace_back("<", "punctuation"); + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(">", "punctuation"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + } // namespace \ No newline at end of file -- Gitee From cb4887104ee4891a414890d0305210350f01b3ce Mon Sep 17 00:00:00 2001 From: leo9001 Date: Wed, 28 May 2025 16:34:28 +0800 Subject: [PATCH 052/145] support test cases for getClassPropertyInfo Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICB69F Signed-off-by: leo9001 --- ets2panda/lsp/src/get_class_property_info.cpp | 13 +- .../unit/lsp/get_class_property_info_test.cpp | 799 +++++++++++++++++- 2 files changed, 805 insertions(+), 7 deletions(-) diff --git a/ets2panda/lsp/src/get_class_property_info.cpp b/ets2panda/lsp/src/get_class_property_info.cpp index e0228eea95..750d24fd84 100644 --- a/ets2panda/lsp/src/get_class_property_info.cpp +++ b/ets2panda/lsp/src/get_class_property_info.cpp @@ -70,8 +70,17 @@ void CollectClassProperties(const ir::AstNode *classNode, std::vector> modifiersOpt(modifiers); - FieldListProperty propertyInfo("classField", std::move(modifiersOpt), GetIdentifierName(property), - property->Start().index, property->End().index); + std::string name = GetIdentifierName(property); + + constexpr auto K_PROPERTY_PREFIX = ""; + constexpr std::size_t K_PROPERTY_PREFIX_LENGTH = std::char_traits::length(K_PROPERTY_PREFIX); + if (name.size() >= K_PROPERTY_PREFIX_LENGTH && + name.compare(0, K_PROPERTY_PREFIX_LENGTH, K_PROPERTY_PREFIX) == 0) { + name.erase(0, K_PROPERTY_PREFIX_LENGTH); + } + + FieldListProperty propertyInfo("classField", std::move(modifiersOpt), name, property->Start().index, + property->End().index); classInfo.properties.push_back(propertyInfo); } diff --git a/ets2panda/test/unit/lsp/get_class_property_info_test.cpp b/ets2panda/test/unit/lsp/get_class_property_info_test.cpp index b6d8c37e24..039281bfc6 100644 --- a/ets2panda/test/unit/lsp/get_class_property_info_test.cpp +++ b/ets2panda/test/unit/lsp/get_class_property_info_test.cpp @@ -32,7 +32,6 @@ namespace { using ark::es2panda::lsp::Initializer; class LspGetClassPropertyInfoTests : public LSPAPITests {}; -std::vector fileNames = {"GetClassPropertyInfoFile.ets"}; std::vector fileContents = { R"( enum BloodType { @@ -92,7 +91,76 @@ export class Person extends SelectableControlClass implements SelectableControl onUpdate: (() => void) | null = null; } )"}; -std::vector>> expectedResult = { +std::vector fileContents2 = { + R"( +export enum BloodType { + A = 'A', + AB = 'AB' +} + +export class Address { + state: number = 1; + province: string = ''; + city: string = ''; +} + +interface Control { + state: number +} + +export interface SelectableControl extends Control { + select(): void +} +)", + R"( +import { Address, SelectableControl } from "./GetClassPropertyInfo_SelectableControl"; + +export class SelectableControlClass extends Address implements SelectableControl { + select(): void { + throw new Error("Method not implemented."); + } + + private state1: number = 0; + protected readonly hobbies: string[] = []; +} +)", + R"( +import { Address, BloodType, SelectableControl } from "./GetClassPropertyInfo_SelectableControl"; +import { SelectableControlClass } from "./GetClassPropertyInfo_SelectableControlClass"; + +enum Sex { + Male = 'Male' +} + +export class Person extends SelectableControlClass implements SelectableControl { + static MAX_HEIGHT: number = 250; + static BLOOD_TYPES: BloodType = BloodType.AB; + static defaultAddress: Address = { + province: '北京', + city: '北京市', + state: 0 + }; + name: string = ''; + age: number = Person.MAX_HEIGHT; + weight: number = 0; + sex: Sex = Sex.Male; + bloodType: BloodType = BloodType.A; + address: Address = new Address(); + hobbies: string[] = []; + maritalStatus: 'single' | 'married' | 'divorced' = 'single'; + birthday: Date = new Date(); + location: [number, number] = [0, 0]; + avatar: Resource = $r('app.media.startIcon'); + attributes: Map = new Map(); + isEmployed: boolean = false; + private privateIsEmployed: boolean = false; + protected protectedIsEmployed: boolean = false; + protected readonly readonlyIsEmployed: boolean = false; + onUpdate: (() => void) | null = null; +} +)"}; + +std::vector>> expectedResultWangz1 = { {"MAX_HEIGHT", 561, 585, "classField", {"public", "static"}}, {"BLOOD_TYPES", 596, 633, "classField", {"public", "static"}}, {"defaultAddress", 644, 722, "classField", {"public", "static"}}, @@ -114,7 +182,9 @@ std::vector &actualProperties) +void CheckClassPropertiesMatch( + const std::vector &actualProperties, + const std::vector>> &expectedResult) { for (size_t i = 0; i < actualProperties.size(); ++i) { const auto &perp = actualProperties[i]; @@ -144,12 +214,14 @@ void CheckClassPropertiesMatch(const std::vector &actualPrope } } -TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod1) +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethodTest1) { constexpr size_t EXPECTED_CLASS_COUNT = 3; constexpr size_t EXPECTED_CLASS_COUNT_ONE = 1; constexpr size_t EXPECTED_PROP_COUNT = 20; + std::vector fileNames = {"GetClassPropertyInfoMethodFile1.ets"}; + auto filePaths = CreateTempFile(fileNames, fileContents); std::vector sourceFiles; @@ -175,7 +247,724 @@ TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod1) FieldsInfo info = infos2[0]; ASSERT_EQ(EXPECTED_PROP_COUNT, info.properties.size()); ASSERT_EQ("Person", info.name); - CheckClassPropertiesMatch(info.properties); + CheckClassPropertiesMatch(info.properties, expectedResultWangz1); +} + +std::vector>> expectedResultWangz2 = { + {"MAX_HEIGHT", 309, 333, "classField", {"public", "static"}}, + {"BLOOD_TYPES", 344, 381, "classField", {"public", "static"}}, + {"defaultAddress", 392, 483, "classField", {"public", "static"}}, + {"name", 487, 504, "classField", {"public"}}, + {"age", 508, 539, "classField", {"public"}}, + {"weight", 543, 561, "classField", {"public"}}, + {"sex", 565, 584, "classField", {"public"}}, + {"bloodType", 588, 622, "classField", {"public"}}, + {"address", 626, 659, "classField", {"public"}}, + {"hobbies", 662, 684, "classField", {"public"}}, + {"maritalStatus", 688, 747, "classField", {"public"}}, + {"birthday", 751, 779, "classField", {"public"}}, + {"location", 782, 817, "classField", {"public"}}, + {"avatar", 821, 865, "classField", {"public"}}, + {"attributes", 869, 913, "classField", {"public"}}, + {"isEmployed", 916, 943, "classField", {"public"}}, + {"privateIsEmployed", 955, 989, "classField", {"private"}}, + {"protectedIsEmployed", 1003, 1039, "classField", {"protected"}}, + {"readonlyIsEmployed", 1062, 1097, "classField", {"protected", "readonly"}}, + {"onUpdate", 1101, 1137, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethodTest2) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 3; + constexpr size_t EXPECTED_CLASS_COUNT_ONE = 1; + constexpr size_t EXPECTED_PROP_COUNT = 20; + + std::vector fileNames2 = {"GetClassPropertyInfo_SelectableControl.ets", + "GetClassPropertyInfo_SelectableControlClass.ets", + "GetClassPropertyInfo_Person.ets"}; + + auto filePaths = CreateTempFile(fileNames2, fileContents2); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents2[i]); + } + ASSERT_EQ(fileNames2.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 2; + size_t tokenOffset = 300; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + + auto infos2 = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset); + initializer.DestroyContext(context); + ASSERT_EQ(EXPECTED_CLASS_COUNT_ONE, infos2.size()); + + FieldsInfo info = infos2[0]; + ASSERT_EQ(EXPECTED_PROP_COUNT, info.properties.size()); + ASSERT_EQ("Person", info.name); + CheckClassPropertiesMatch(info.properties, expectedResultWangz2); +} + +std::vector fileContents3 = { + R"( +class A { +} +)", + R"( +class B { + p1 + p2 + static p3 + readonly p4 + private p5 +} +)", + R"( +class KKK { + tr:string; + constructor(tr: string) { + this.tr = tr; + } +} + +class NNN extends KKK { +} +)", + R"( +class GGG { + tr:string; + constructor(tr: string) { + this.tr = tr; + } +} + +class HHH extends GGG { + pop:string +} +)", + R"( +abstract class AA { + test: number; +} + +class NN extends AA { + jkk: string; +} +)", + R"( +abstract class AA2 { + test: number; + private kn: string; + das: string; + + constructor(test: number, kn: string) { + this.test = test; + this.kn = kn; + } +} + +class NN2 extends AA2 { + jkk: string; + wwa: number; +} +)", + R"( +class ok { + test?:string; +} +)", + R"( +class TY { + private _a: string = "foo" +} +)", + R"( +class TwY { + static a: string = "foo" +} +)", + R"( +class TwasY { + a: string|number; +} +)", + R"( +abstract class TY { + abstract a: string|number; +} +)", + R"( +class Demo { + private name = 'jack'; + private age = 25; + private doTask = () => 34; +} +)", + R"( +interface AA { + aa: number; + getAA(): number; +} + +class BaseNN { + aa: number; + + constructor(aa: number) { + this.aa = aa; + } + + getAA(): number { + return 1; + } +} + +class MM extends BaseNN implements AA { + aa: number; + getAA(): number { + return super.getAA(); + } +} +)", + R"( +import CommonEventManager from '@ohos.commonEventManager'; + +interface SubscribeInfoType { + events: string[]; +} + +class CommonEventRegister { + subscriber: CommonEventManager.CommonEventSubscriber | null = null; + public subscribeInfo: SubscribeInfoType; +} +)"}; + +std::vector>> expectedResult1 = {}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod1) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 0; + + std::vector fileNames3 = { + "get_class_property_info_test_m1_01.ets", "get_class_property_info_test_m1_02.ets", + "get_class_property_info_test_m1_03.ets", "get_class_property_info_test_m1_04.ets", + "get_class_property_info_test_m1_05.ets", "get_class_property_info_test_m1_06.ets", + "get_class_property_info_test_m1_07.ets", "get_class_property_info_test_m1_08.ets", + "get_class_property_info_test_m1_09.ets", "get_class_property_info_test_m1_10.ets", + "get_class_property_info_test_m1_11.ets", "get_class_property_info_test_m1_12.ets", + "get_class_property_info_test_m1_13.ets", "get_class_property_info_test_m1_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 0; + size_t tokenOffset = 12; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult1); +} + +std::vector>> expectedResult2 = { + {"p1", 13, 15, "classField", {"public"}}, + {"p2", 18, 20, "classField", {"public"}}, + {"p3", 30, 32, "classField", {"public", "static"}}, + {"p4", 44, 46, "classField", {"public", "readonly"}}, + {"p5", 57, 59, "classField", {"private"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod2) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 5; + + std::vector fileNames3 = { + "get_class_property_info_test_m2_01.ets", "get_class_property_info_test_m2_02.ets", + "get_class_property_info_test_m2_03.ets", "get_class_property_info_test_m2_04.ets", + "get_class_property_info_test_m2_05.ets", "get_class_property_info_test_m2_06.ets", + "get_class_property_info_test_m2_07.ets", "get_class_property_info_test_m2_08.ets", + "get_class_property_info_test_m2_09.ets", "get_class_property_info_test_m2_10.ets", + "get_class_property_info_test_m2_11.ets", "get_class_property_info_test_m2_12.ets", + "get_class_property_info_test_m2_13.ets", "get_class_property_info_test_m2_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 1; + size_t tokenOffset = 61; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult2); +} + +std::vector>> expectedResult3 = {}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod3) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 2; + constexpr size_t EXPECTED_PROP_COUNT = 0; + + std::vector fileNames3 = { + "get_class_property_info_test_m3_01.ets", "get_class_property_info_test_m3_02.ets", + "get_class_property_info_test_m3_03.ets", "get_class_property_info_test_m3_04.ets", + "get_class_property_info_test_m3_05.ets", "get_class_property_info_test_m3_06.ets", + "get_class_property_info_test_m3_07.ets", "get_class_property_info_test_m3_08.ets", + "get_class_property_info_test_m3_09.ets", "get_class_property_info_test_m3_10.ets", + "get_class_property_info_test_m3_11.ets", "get_class_property_info_test_m3_12.ets", + "get_class_property_info_test_m3_13.ets", "get_class_property_info_test_m3_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 2; + size_t tokenOffset = 104; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult3); +} + +std::vector>> expectedResult4 = { + {"pop", 107, 119, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod4) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 2; + constexpr size_t EXPECTED_PROP_COUNT = 1; + + std::vector fileNames3 = { + "get_class_property_info_test_m4_01.ets", "get_class_property_info_test_m4_02.ets", + "get_class_property_info_test_m4_03.ets", "get_class_property_info_test_m4_04.ets", + "get_class_property_info_test_m4_05.ets", "get_class_property_info_test_m4_06.ets", + "get_class_property_info_test_m4_07.ets", "get_class_property_info_test_m4_08.ets", + "get_class_property_info_test_m4_09.ets", "get_class_property_info_test_m4_10.ets", + "get_class_property_info_test_m4_11.ets", "get_class_property_info_test_m4_12.ets", + "get_class_property_info_test_m4_13.ets", "get_class_property_info_test_m4_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 3; + size_t tokenOffset = 117; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult4); +} + +std::vector>> expectedResult5 = { + {"jkk", 64, 76, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod5) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 2; + constexpr size_t EXPECTED_PROP_COUNT = 1; + + std::vector fileNames3 = { + "get_class_property_info_test_m5_01.ets", "get_class_property_info_test_m5_02.ets", + "get_class_property_info_test_m5_03.ets", "get_class_property_info_test_m5_04.ets", + "get_class_property_info_test_m5_05.ets", "get_class_property_info_test_m5_06.ets", + "get_class_property_info_test_m5_07.ets", "get_class_property_info_test_m5_08.ets", + "get_class_property_info_test_m5_09.ets", "get_class_property_info_test_m5_10.ets", + "get_class_property_info_test_m5_11.ets", "get_class_property_info_test_m5_12.ets", + "get_class_property_info_test_m5_13.ets", "get_class_property_info_test_m5_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 4; + size_t tokenOffset = 76; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult5); +} + +std::vector>> expectedResult6 = { + {"jkk", 195, 207, "classField", {"public"}}, {"wwa", 210, 222, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod6) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 2; + constexpr size_t EXPECTED_PROP_COUNT = 2; + + std::vector fileNames3 = { + "get_class_property_info_test_m6_01.ets", "get_class_property_info_test_m6_02.ets", + "get_class_property_info_test_m6_03.ets", "get_class_property_info_test_m6_04.ets", + "get_class_property_info_test_m6_05.ets", "get_class_property_info_test_m6_06.ets", + "get_class_property_info_test_m6_07.ets", "get_class_property_info_test_m6_08.ets", + "get_class_property_info_test_m6_09.ets", "get_class_property_info_test_m6_10.ets", + "get_class_property_info_test_m6_11.ets", "get_class_property_info_test_m6_12.ets", + "get_class_property_info_test_m6_13.ets", "get_class_property_info_test_m6_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 5; + size_t tokenOffset = 222; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult6); +} + +std::vector>> expectedResult7 = { + {"test", 14, 27, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod7) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 1; + + std::vector fileNames3 = { + "get_class_property_info_test_m7_01.ets", "get_class_property_info_test_m7_02.ets", + "get_class_property_info_test_m7_03.ets", "get_class_property_info_test_m7_04.ets", + "get_class_property_info_test_m7_05.ets", "get_class_property_info_test_m7_06.ets", + "get_class_property_info_test_m7_07.ets", "get_class_property_info_test_m7_08.ets", + "get_class_property_info_test_m7_09.ets", "get_class_property_info_test_m7_10.ets", + "get_class_property_info_test_m7_11.ets", "get_class_property_info_test_m7_12.ets", + "get_class_property_info_test_m7_13.ets", "get_class_property_info_test_m7_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 6; + size_t tokenOffset = 27; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult7); +} + +std::vector>> expectedResult8 = { + {"_a", 22, 40, "classField", {"private"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod8) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 1; + + std::vector fileNames3 = { + "get_class_property_info_test_m8_01.ets", "get_class_property_info_test_m8_02.ets", + "get_class_property_info_test_m8_03.ets", "get_class_property_info_test_m8_04.ets", + "get_class_property_info_test_m8_05.ets", "get_class_property_info_test_m8_06.ets", + "get_class_property_info_test_m8_07.ets", "get_class_property_info_test_m8_08.ets", + "get_class_property_info_test_m8_09.ets", "get_class_property_info_test_m8_10.ets", + "get_class_property_info_test_m8_11.ets", "get_class_property_info_test_m8_12.ets", + "get_class_property_info_test_m8_13.ets", "get_class_property_info_test_m8_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 7; + size_t tokenOffset = 40; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult8); +} + +std::vector>> expectedResult9 = { + {"a", 22, 39, "classField", {"public", "static"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod9) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 1; + + std::vector fileNames3 = { + "get_class_property_info_test_m9_01.ets", "get_class_property_info_test_m9_02.ets", + "get_class_property_info_test_m9_03.ets", "get_class_property_info_test_m9_04.ets", + "get_class_property_info_test_m9_05.ets", "get_class_property_info_test_m9_06.ets", + "get_class_property_info_test_m9_07.ets", "get_class_property_info_test_m9_08.ets", + "get_class_property_info_test_m9_09.ets", "get_class_property_info_test_m9_10.ets", + "get_class_property_info_test_m9_11.ets", "get_class_property_info_test_m9_12.ets", + "get_class_property_info_test_m9_13.ets", "get_class_property_info_test_m9_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 8; + size_t tokenOffset = 39; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult9); +} + +std::vector>> expectedResult10 = { + {"a", 17, 34, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod10) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 1; + + std::vector fileNames3 = { + "get_class_property_info_test_m10_01.ets", "get_class_property_info_test_m10_02.ets", + "get_class_property_info_test_m10_03.ets", "get_class_property_info_test_m10_04.ets", + "get_class_property_info_test_m10_05.ets", "get_class_property_info_test_m10_06.ets", + "get_class_property_info_test_m10_07.ets", "get_class_property_info_test_m10_08.ets", + "get_class_property_info_test_m10_09.ets", "get_class_property_info_test_m10_10.ets", + "get_class_property_info_test_m10_11.ets", "get_class_property_info_test_m10_12.ets", + "get_class_property_info_test_m10_13.ets", "get_class_property_info_test_m10_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 9; + size_t tokenOffset = 35; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult10); +} + +std::vector>> expectedResult11 = { + {"a", 32, 49, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod11) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 1; + + std::vector fileNames3 = { + "get_class_property_info_test_m11_01.ets", "get_class_property_info_test_m11_02.ets", + "get_class_property_info_test_m11_03.ets", "get_class_property_info_test_m11_04.ets", + "get_class_property_info_test_m11_05.ets", "get_class_property_info_test_m11_06.ets", + "get_class_property_info_test_m11_07.ets", "get_class_property_info_test_m11_08.ets", + "get_class_property_info_test_m11_09.ets", "get_class_property_info_test_m11_10.ets", + "get_class_property_info_test_m11_11.ets", "get_class_property_info_test_m11_12.ets", + "get_class_property_info_test_m11_13.ets", "get_class_property_info_test_m11_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 10; + size_t tokenOffset = 50; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult11); +} + +std::vector>> expectedResult12 = { + {"name", 24, 37, "classField", {"private"}}, + {"age", 49, 57, "classField", {"private"}}, + {"doTask", 69, 86, "classField", {"private"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod12) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 3; + + std::vector fileNames3 = { + "get_class_property_info_test_m12_01.ets", "get_class_property_info_test_m12_02.ets", + "get_class_property_info_test_m12_03.ets", "get_class_property_info_test_m12_04.ets", + "get_class_property_info_test_m12_05.ets", "get_class_property_info_test_m12_06.ets", + "get_class_property_info_test_m12_07.ets", "get_class_property_info_test_m12_08.ets", + "get_class_property_info_test_m12_09.ets", "get_class_property_info_test_m12_10.ets", + "get_class_property_info_test_m12_11.ets", "get_class_property_info_test_m12_12.ets", + "get_class_property_info_test_m12_13.ets", "get_class_property_info_test_m12_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 11; + size_t tokenOffset = 87; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult12); +} + +std::vector>> expectedResult13 = { + {"aa", 216, 227, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod13) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 2; + constexpr size_t EXPECTED_PROP_COUNT = 1; + + std::vector fileNames3 = { + "get_class_property_info_test_m13_01.ets", "get_class_property_info_test_m13_02.ets", + "get_class_property_info_test_m13_03.ets", "get_class_property_info_test_m13_04.ets", + "get_class_property_info_test_m13_05.ets", "get_class_property_info_test_m13_06.ets", + "get_class_property_info_test_m13_07.ets", "get_class_property_info_test_m13_08.ets", + "get_class_property_info_test_m13_09.ets", "get_class_property_info_test_m13_10.ets", + "get_class_property_info_test_m13_11.ets", "get_class_property_info_test_m13_12.ets", + "get_class_property_info_test_m13_13.ets", "get_class_property_info_test_m13_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 12; + size_t tokenOffset = 232; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult13); +} + +std::vector>> expectedResult14 = { + {"subscriber", 144, 210, "classField", {"public"}}, {"subscribeInfo", 221, 254, "classField", {"public"}}}; + +TEST_F(LspGetClassPropertyInfoTests, GetClassPropertyInfoMethod14) +{ + constexpr size_t EXPECTED_CLASS_COUNT = 1; + constexpr size_t EXPECTED_PROP_COUNT = 2; + + std::vector fileNames3 = { + "get_class_property_info_test_m14_01.ets", "get_class_property_info_test_m14_02.ets", + "get_class_property_info_test_m14_03.ets", "get_class_property_info_test_m14_04.ets", + "get_class_property_info_test_m14_05.ets", "get_class_property_info_test_m14_06.ets", + "get_class_property_info_test_m14_07.ets", "get_class_property_info_test_m14_08.ets", + "get_class_property_info_test_m14_09.ets", "get_class_property_info_test_m14_10.ets", + "get_class_property_info_test_m14_11.ets", "get_class_property_info_test_m14_12.ets", + "get_class_property_info_test_m14_13.ets", "get_class_property_info_test_m14_14.ets"}; + + auto filePaths = CreateTempFile(fileNames3, fileContents3); + std::vector sourceFiles; + + for (size_t i = 0; i < filePaths.size(); ++i) { + sourceFiles.emplace_back(filePaths[i], fileContents3[i]); + } + ASSERT_EQ(fileNames3.size(), sourceFiles.size()); + + Initializer initializer; + size_t sourceIndex = 13; + size_t tokenOffset = 256; + auto filePath = std::string {sourceFiles[sourceIndex].filePath}; + auto fileContent = std::string {sourceFiles[sourceIndex].source}; + auto context = initializer.CreateContext(filePath.c_str(), ES2PANDA_STATE_CHECKED, fileContent.c_str()); + auto infos = ark::es2panda::lsp::GetClassPropertyInfo(context, tokenOffset, true); + ASSERT_EQ(EXPECTED_CLASS_COUNT, infos.size()); + ASSERT_EQ(EXPECTED_PROP_COUNT, infos[0].properties.size()); + CheckClassPropertiesMatch(infos[0].properties, expectedResult14); } + // NOLINTEND } // namespace \ No newline at end of file -- Gitee From f124a29cd88b3600eba7a8a2c308baee50e9f652 Mon Sep 17 00:00:00 2001 From: dYildiz Date: Sat, 24 May 2025 12:42:24 +0300 Subject: [PATCH 053/145] [LSPAPI]Refactor Provider Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC6F9S Signed-off-by: doneyildiz --- ets2panda/bindings/native/src/lsp.cpp | 59 +--------- ets2panda/compiler/lowering/util.cpp | 4 + ets2panda/lsp/BUILD.gn | 2 + ets2panda/lsp/CMakeLists.txt | 2 + ets2panda/lsp/include/api.h | 26 +---- ets2panda/lsp/include/applicable_refactors.h | 46 +------- ets2panda/lsp/include/refactor_provider.h | 54 +++++++++ .../lsp/include/refactors/convert_function.h | 9 +- .../lsp/include/refactors/refactor_types.h | 106 ++++++++++++++++++ .../services/text_change/change_tracker.h | 5 - ets2panda/lsp/src/api.cpp | 4 +- ets2panda/lsp/src/applicable_refactors.cpp | 53 +-------- ets2panda/lsp/src/completions.cpp | 3 + ets2panda/lsp/src/refactor_provider.cpp | 63 +++++++++++ .../lsp/src/refactors/convert_function.cpp | 30 ++++- .../lsp/src/refactors/refactor_types.cpp | 58 ++++++++++ ets2panda/test/unit/lsp/CMakeLists.txt | 8 +- .../test/unit/lsp/refactor_provider_test.cpp | 34 ++++++ .../lsp/refactors_convert_function_test.cpp | 87 -------------- 19 files changed, 378 insertions(+), 275 deletions(-) create mode 100644 ets2panda/lsp/include/refactor_provider.h create mode 100644 ets2panda/lsp/include/refactors/refactor_types.h create mode 100644 ets2panda/lsp/src/refactor_provider.cpp create mode 100644 ets2panda/lsp/src/refactors/refactor_types.cpp create mode 100644 ets2panda/test/unit/lsp/refactor_provider_test.cpp delete mode 100644 ets2panda/test/unit/lsp/refactors_convert_function_test.cpp diff --git a/ets2panda/bindings/native/src/lsp.cpp b/ets2panda/bindings/native/src/lsp.cpp index a74ee5ae80..286efef597 100644 --- a/ets2panda/bindings/native/src/lsp.cpp +++ b/ets2panda/bindings/native/src/lsp.cpp @@ -19,7 +19,7 @@ #include "common.h" #include "panda_types.h" #include "public/es2panda_lib.h" - +#include "lsp/include/refactors/refactor_types.h" #include #include #include @@ -318,15 +318,15 @@ KNativePointer impl_getClassConstructorInfo(KNativePointer context, KInt positio properties.emplace_back(GetStringCopy(const_cast(el))); } LSPAPI const *ctx = GetImpl(); - auto *info = new RefactorEditInfo(ctx->getClassConstructorInfo(reinterpret_cast(context), - static_cast(position), properties)); + auto *info = new ark::es2panda::lsp::RefactorEditInfo(ctx->getClassConstructorInfo( + reinterpret_cast(context), static_cast(position), properties)); return info; } TS_INTEROP_3(getClassConstructorInfo, KNativePointer, KNativePointer, KInt, KStringArray) KNativePointer impl_getFileTextChangesFromConstructorInfo(KNativePointer infoPtr) { - auto *info = reinterpret_cast(infoPtr); + auto *info = reinterpret_cast(infoPtr); std::vector ptrs; for (auto &el : info->GetFileTextChanges()) { ptrs.push_back(new FileTextChanges(el)); @@ -367,57 +367,6 @@ KNativePointer impl_getTextSpanFromConstructorInfo(KNativePointer infoPtr) } TS_INTEROP_1(getTextSpanFromConstructorInfo, KNativePointer, KNativePointer) -KNativePointer impl_getRefactorActionName(KNativePointer refactorActionPtr) -{ - auto *refactorAction = reinterpret_cast(refactorActionPtr); - return new std::string(refactorAction->name); -} -TS_INTEROP_1(getRefactorActionName, KNativePointer, KNativePointer) - -KNativePointer impl_getRefactorActionDescription(KNativePointer refactorActionPtr) -{ - auto *refactorAction = reinterpret_cast(refactorActionPtr); - return new std::string(refactorAction->description); -} -TS_INTEROP_1(getRefactorActionDescription, KNativePointer, KNativePointer) - -KNativePointer impl_getRefactorActionKind(KNativePointer refactorActionPtr) -{ - auto *refactorAction = reinterpret_cast(refactorActionPtr); - return new std::string(refactorAction->kind); -} -TS_INTEROP_1(getRefactorActionKind, KNativePointer, KNativePointer) - -KNativePointer impl_getApplicableRefactors(KNativePointer context, KStringPtr &kindPtr, KInt position) -{ - LSPAPI const *ctx = GetImpl(); - auto *applicableRefactorInfo = new ark::es2panda::lsp::ApplicableRefactorInfo(ctx->getApplicableRefactors( - reinterpret_cast(context), GetStringCopy(kindPtr), static_cast(position))); - return applicableRefactorInfo; -} -TS_INTEROP_3(getApplicableRefactors, KNativePointer, KNativePointer, KStringPtr, KInt) - -KNativePointer impl_getApplicableRefactorName(KNativePointer applRefsPtr) -{ - auto *applRefsInfo = reinterpret_cast(applRefsPtr); - return new std::string(applRefsInfo->name); -} -TS_INTEROP_1(getApplicableRefactorName, KNativePointer, KNativePointer) - -KNativePointer impl_getApplicableRefactorDescription(KNativePointer applRefsPtr) -{ - auto *applRefsInfo = reinterpret_cast(applRefsPtr); - return new std::string(applRefsInfo->description); -} -TS_INTEROP_1(getApplicableRefactorDescription, KNativePointer, KNativePointer) - -KNativePointer impl_getRefactorAction(KNativePointer applRefsPtr) -{ - auto *applRefsInfo = reinterpret_cast(applRefsPtr); - return new ark::es2panda::lsp::RefactorAction(applRefsInfo->action); -} -TS_INTEROP_1(getRefactorAction, KNativePointer, KNativePointer) - KNativePointer impl_getCompletionEntryDetailsSymbolDisplayPart(KNativePointer completionEntryDetailsPtr) { auto *completionEntryDetails = reinterpret_cast(completionEntryDetailsPtr); diff --git a/ets2panda/compiler/lowering/util.cpp b/ets2panda/compiler/lowering/util.cpp index 09fe048e25..ca9aa4ca82 100644 --- a/ets2panda/compiler/lowering/util.cpp +++ b/ets2panda/compiler/lowering/util.cpp @@ -262,6 +262,10 @@ void Recheck(PhaseManager *phaseManager, varbinder::ETSBinder *varBinder, checke // NOTE: used to get the declaration from identifier in Plugin API and LSP ir::AstNode *DeclarationFromIdentifier(const ir::Identifier *node) { + if (node == nullptr) { + return nullptr; + } + auto idVar = node->Variable(); if (idVar == nullptr) { return nullptr; diff --git a/ets2panda/lsp/BUILD.gn b/ets2panda/lsp/BUILD.gn index db6d280f27..94fcff39ba 100644 --- a/ets2panda/lsp/BUILD.gn +++ b/ets2panda/lsp/BUILD.gn @@ -71,7 +71,9 @@ ohos_source_set("libes2panda_lsp_static") { "src/navigate_to.cpp", "src/organize_imports.cpp", "src/quick_info.cpp", + "src/refactor_provider.cpp", "src/refactors/convert_function.cpp", + "src/refactors/refactor_types.cpp", "src/references.cpp", "src/register_code_fix/add_missing_declare_property.cpp", "src/register_code_fix/fix_missing_call_parantheses.cpp", diff --git a/ets2panda/lsp/CMakeLists.txt b/ets2panda/lsp/CMakeLists.txt index 601ab7f0c9..41272e7af7 100644 --- a/ets2panda/lsp/CMakeLists.txt +++ b/ets2panda/lsp/CMakeLists.txt @@ -29,7 +29,9 @@ set(ES2PANDA_LSP_SRC ./src/find_rename_locations.cpp ./src/find_safe_delete_location.cpp ./src/find_references.cpp + ./src/refactors/refactor_types.cpp ./src/applicable_refactors.cpp + ./src/refactor_provider.cpp ./src/refactors/convert_function.cpp ./src/formatting/formatting_context.cpp ./src/formatting/formatting_settings.cpp diff --git a/ets2panda/lsp/include/api.h b/ets2panda/lsp/include/api.h index 099982127c..424200a26f 100644 --- a/ets2panda/lsp/include/api.h +++ b/ets2panda/lsp/include/api.h @@ -28,11 +28,13 @@ #include "line_column_offset.h" #include "public/es2panda_lib.h" #include "cancellation_token.h" +#include "user_preferences.h" #include "class_hierarchies.h" #include "find_references.h" #include "find_rename_locations.h" #include "class_hierarchy_info.h" #include "completions.h" +#include "refactors/refactor_types.h" #include "applicable_refactors.h" #include "todo_comments.h" #include "types.h" @@ -259,22 +261,6 @@ public: } }; -struct RefactorEditInfo { -private: - std::vector fileTextChanges_; - -public: - explicit RefactorEditInfo(std::vector fileTextChanges = {}) - : fileTextChanges_(std::move(fileTextChanges)) - { - } - - std::vector &GetFileTextChanges() - { - return fileTextChanges_; - } -}; - struct QuickInfo { private: std::string kind_; @@ -502,8 +488,8 @@ struct CodeFixOptions { typedef struct LSPAPI { DefinitionInfo (*getDefinitionAtPosition)(es2panda_Context *context, size_t position); - ark::es2panda::lsp::ApplicableRefactorInfo (*getApplicableRefactors)(es2panda_Context *context, const char *kind, - size_t position); + std::vector (*getApplicableRefactors)( + const ark::es2panda::lsp::RefactorContext *context); DefinitionInfo (*getImplementationAtPosition)(es2panda_Context *context, size_t position); bool (*isPackageModule)(es2panda_Context *context); ark::es2panda::lsp::CompletionEntryKind (*getAliasScriptElementKind)(es2panda_Context *context, size_t position); @@ -543,8 +529,8 @@ typedef struct LSPAPI { ark::es2panda::lsp::CompletionInfo (*getCompletionsAtPosition)(es2panda_Context *context, size_t position); ark::es2panda::lsp::ClassHierarchy (*getClassHierarchyInfo)(es2panda_Context *context, size_t position); std::vector (*getBraceMatchingAtPosition)(char const *fileName, size_t position); - RefactorEditInfo (*getClassConstructorInfo)(es2panda_Context *context, size_t position, - const std::vector &properties); + ark::es2panda::lsp::RefactorEditInfo (*getClassConstructorInfo)(es2panda_Context *context, size_t position, + const std::vector &properties); std::vector (*getImplementationLocationAtPosition)(es2panda_Context *context, int position); ark::es2panda::lsp::LineAndCharacter (*toLineColumnOffset)(es2panda_Context *context, size_t position); std::vector (*getTodoComments)( diff --git a/ets2panda/lsp/include/applicable_refactors.h b/ets2panda/lsp/include/applicable_refactors.h index 3329f8891f..9d736ddbf8 100644 --- a/ets2panda/lsp/include/applicable_refactors.h +++ b/ets2panda/lsp/include/applicable_refactors.h @@ -17,56 +17,14 @@ #define APPLICABLE_REFACTORS_H #include "public/es2panda_lib.h" +#include "refactors/refactor_types.h" #include #include #include namespace ark::es2panda::lsp { -using RefactorActionView = struct RefactorActionView { - std::string_view name; - std::string_view description; - std::string_view kind; -}; - -using RefactorAction = struct RefactorAction { - std::string name; - std::string description; - std::string kind; -}; - -using ApplicableRefactorInfo = struct ApplicableRefactorInfo { - std::string name; - std::string description; - RefactorAction action; -}; - -namespace refactor_name { -constexpr std::string_view CONVERT_FUNCTION_REFACTOR_NAME = "Convert arrow function or function expression"; -} // namespace refactor_name - -namespace refactor_description { -constexpr std::string_view CONVERT_FUNCTION_REFACTOR_DESC = "Convert arrow function or function expression"; -} // namespace refactor_description - -class Refactor { -private: - std::vector kinds_; - -public: - bool IsKind(const std::string &kind); - void AddKind(const std::string &kind); - virtual ApplicableRefactorInfo GetAvailableActions(es2panda_Context *context, std::string kind, - size_t position) = 0; - virtual ~Refactor() = default; - Refactor() = default; - Refactor &operator=(const Refactor &other); - Refactor &operator=(Refactor &&other); - Refactor(const Refactor &other); - Refactor(Refactor &&other); -}; - -ApplicableRefactorInfo GetApplicableRefactorsImpl(es2panda_Context *context, const char *kind, size_t position); +std::vector GetApplicableRefactorsImpl(const RefactorContext *context); } // namespace ark::es2panda::lsp #endif // APPLICABLE_REFACTORS_H \ No newline at end of file diff --git a/ets2panda/lsp/include/refactor_provider.h b/ets2panda/lsp/include/refactor_provider.h new file mode 100644 index 0000000000..dbd529c2c2 --- /dev/null +++ b/ets2panda/lsp/include/refactor_provider.h @@ -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. + */ + +#ifndef ES2PANDA_LSP_INCLUDE_REFACTOR_PROVIDER_H +#define ES2PANDA_LSP_INCLUDE_REFACTOR_PROVIDER_H + +#include "refactors/refactor_types.h" +#include +#include +#include + +namespace ark::es2panda::lsp { + +class RefactorProvider { +public: + void RegisterRefactor(const std::string &name, std::unique_ptr refactor); + static RefactorProvider &Instance(); + std::unique_ptr GetEditsForRefactor(const RefactorContext &context, + const std::string &refactorName, + const std::string &actionName) const; + std::vector GetApplicableRefactors(const RefactorContext &context) const; + + const std::unordered_map> &GetRefactors() const; + +private: + std::unordered_map> refactors_; +}; + +template +struct AutoRefactorRegister { + constexpr explicit AutoRefactorRegister(const std::string &name, std::unique_ptr refactor) + { + RefactorProvider::Instance().RegisterRefactor(name, std::move(refactor)); + } + + constexpr explicit AutoRefactorRegister(const std::string &name) : AutoRefactorRegister(name, std::make_unique()) + { + } +}; + +} // namespace ark::es2panda::lsp +#endif // ES2PANDA_LSP_INCLUDE_REFACTOR_PROVIDER_H diff --git a/ets2panda/lsp/include/refactors/convert_function.h b/ets2panda/lsp/include/refactors/convert_function.h index 2b9767164b..5581ab3dd5 100644 --- a/ets2panda/lsp/include/refactors/convert_function.h +++ b/ets2panda/lsp/include/refactors/convert_function.h @@ -16,7 +16,7 @@ #ifndef CONVERT_FUNCTION_H #define CONVERT_FUNCTION_H -#include "lsp/include/applicable_refactors.h" +#include "refactor_types.h" namespace ark::es2panda::lsp { @@ -30,8 +30,11 @@ constexpr RefactorActionView TO_ARROW_FUNCTION_ACTION {"Convert to arrow functio class ConvertFunctionRefactor : public Refactor { public: ConvertFunctionRefactor(); - ApplicableRefactorInfo GetAvailableActions(es2panda_Context *context, std::string kind, size_t position) override; + ApplicableRefactorInfo GetAvailableActions(const RefactorContext &context) const override; + std::unique_ptr GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const override; }; + } // namespace ark::es2panda::lsp -#endif // CONVERT_FUNCTION_H \ No newline at end of file +#endif // CONVERT_FUNCTION_H diff --git a/ets2panda/lsp/include/refactors/refactor_types.h b/ets2panda/lsp/include/refactors/refactor_types.h new file mode 100644 index 0000000000..72e3dd74ea --- /dev/null +++ b/ets2panda/lsp/include/refactors/refactor_types.h @@ -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. + */ + +#ifndef REFACTOR_TYPES_H +#define REFACTOR_TYPES_H + +#include "public/es2panda_lib.h" +#include "../cancellation_token.h" +#include "../user_preferences.h" +#include "../types.h" +#include "es2panda.h" +#include +#include +#include + +namespace ark::es2panda::lsp { + +struct RefactorEditInfo { +private: + std::vector fileTextChanges_; + +public: + explicit RefactorEditInfo(std::vector fileTextChanges = {}) + : fileTextChanges_(std::move(fileTextChanges)) + { + } + + std::vector &GetFileTextChanges() + { + return fileTextChanges_; + } +}; + +struct TextRange { + size_t pos; + size_t end; +}; + +struct RefactorContext { + ark::es2panda::lsp::CancellationToken *cancellationToken; + ark::es2panda::lsp::UserPreferences *preferences; + TextRange span; + es2panda_Context *context; + std::string kind; +}; + +using RefactorActionView = struct RefactorActionView { + std::string_view name; + std::string_view description; + std::string_view kind; +}; + +using RefactorAction = struct RefactorAction { + std::string name; + std::string description; + std::string kind; +}; + +using ApplicableRefactorInfo = struct ApplicableRefactorInfo { + std::string name; + std::string description; + RefactorAction action; +}; + +namespace refactor_name { +constexpr std::string_view CONVERT_FUNCTION_REFACTOR_NAME = "Convert arrow function or function expression"; +} // namespace refactor_name + +namespace refactor_description { +constexpr std::string_view CONVERT_FUNCTION_REFACTOR_DESC = "Convert arrow function or function expression"; +} // namespace refactor_description + +class Refactor { +private: + std::vector kinds_; + +public: + bool IsKind(const std::string &kind) const; + void AddKind(const std::string &kind); + virtual ApplicableRefactorInfo GetAvailableActions(const RefactorContext &context) const = 0; + + virtual std::unique_ptr GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const = 0; + virtual ~Refactor() = default; + Refactor() = default; + Refactor &operator=(const Refactor &other); + Refactor &operator=(Refactor &&other); + Refactor(const Refactor &other); + Refactor(Refactor &&other); +}; + +} // namespace ark::es2panda::lsp + +#endif // REFACTOR_TYPES_H \ No newline at end of file diff --git a/ets2panda/lsp/include/services/text_change/change_tracker.h b/ets2panda/lsp/include/services/text_change/change_tracker.h index 168c1f36b3..d7d6d1042b 100644 --- a/ets2panda/lsp/include/services/text_change/change_tracker.h +++ b/ets2panda/lsp/include/services/text_change/change_tracker.h @@ -46,11 +46,6 @@ struct ConfigurableEnd { std::optional trailingTriviaOption; }; -struct TextRange { - size_t pos; - size_t end; -}; - struct ConfigurableStartEnd { std::optional leadingTriviaOption; std::optional trailingTriviaOption; diff --git a/ets2panda/lsp/src/api.cpp b/ets2panda/lsp/src/api.cpp index aeca335a37..0de730e3e1 100644 --- a/ets2panda/lsp/src/api.cpp +++ b/ets2panda/lsp/src/api.cpp @@ -343,9 +343,9 @@ LineAndCharacter ToLineColumnOffsetWrapper(es2panda_Context *context, size_t pos // Returns type of refactoring and action that can be performed based // on the input kind information and cursor position -ApplicableRefactorInfo GetApplicableRefactors(es2panda_Context *context, const char *kind, size_t position) +std::vector GetApplicableRefactors(const RefactorContext *context) { - auto result = GetApplicableRefactorsImpl(context, kind, position); + auto result = GetApplicableRefactorsImpl(context); return result; } diff --git a/ets2panda/lsp/src/applicable_refactors.cpp b/ets2panda/lsp/src/applicable_refactors.cpp index 20a8994900..602cfeb76c 100644 --- a/ets2panda/lsp/src/applicable_refactors.cpp +++ b/ets2panda/lsp/src/applicable_refactors.cpp @@ -15,60 +15,15 @@ #include #include +#include "refactors/refactor_types.h" #include "applicable_refactors.h" +#include "lsp/include/refactor_provider.h" #include "refactors/convert_function.h" namespace ark::es2panda::lsp { -Refactor::Refactor(const Refactor &other) -{ - kinds_.insert(kinds_.end(), other.kinds_.begin(), other.kinds_.end()); -} - -Refactor &Refactor::operator=(const Refactor &other) -{ - kinds_.insert(kinds_.end(), other.kinds_.begin(), other.kinds_.end()); - return *this; -} - -Refactor &Refactor::operator=(Refactor &&other) -{ - kinds_.insert(kinds_.end(), other.kinds_.begin(), other.kinds_.end()); - return *this; -} - -Refactor::Refactor(Refactor &&other) -{ - kinds_.insert(kinds_.end(), other.kinds_.begin(), other.kinds_.end()); -} - -bool Refactor::IsKind(const std::string &kind) -{ - for (const std::string &rKind : kinds_) { - if (rKind.substr(0, kind.length()) == kind) { - return true; - } - } - return false; -} -void Refactor::AddKind(const std::string &kind) +std::vector GetApplicableRefactorsImpl(const RefactorContext *context) { - kinds_.push_back(kind); -} - -ApplicableRefactorInfo GetApplicableRefactorsImpl(es2panda_Context *context, const char *kind, size_t position) -{ - ApplicableRefactorInfo result; - std::unordered_map> refactors; - Refactor *convertFunctionRefactor = new ConvertFunctionRefactor(); - refactors[std::string(refactor_name::CONVERT_FUNCTION_REFACTOR_NAME)] = - std::shared_ptr(convertFunctionRefactor); - for (const auto &[refactorName, refactor] : refactors) { - if (refactor->IsKind(std::string(kind))) { - return refactor->GetAvailableActions(context, std::string(kind), position); - } - } - - return result; + return RefactorProvider::Instance().GetApplicableRefactors(*context); } } // namespace ark::es2panda::lsp \ No newline at end of file diff --git a/ets2panda/lsp/src/completions.cpp b/ets2panda/lsp/src/completions.cpp index fc0e486bf6..cc8bda9324 100644 --- a/ets2panda/lsp/src/completions.cpp +++ b/ets2panda/lsp/src/completions.cpp @@ -462,6 +462,9 @@ std::vector GetCompletionFromTSInterfaceDeclaration(ir::TSInter auto ident = GetIdentifierFromTSInterfaceHeritage(extend); if (ident != nullptr && ident->IsIdentifier()) { auto extendInterf = compiler::DeclarationFromIdentifier(ident->AsIdentifier()); + if (extendInterf == nullptr) { + continue; + } auto extendCom = extendInterf->IsTSInterfaceDeclaration() ? GetCompletionFromTSInterfaceDeclaration(extendInterf->AsTSInterfaceDeclaration(), triggerWord) diff --git a/ets2panda/lsp/src/refactor_provider.cpp b/ets2panda/lsp/src/refactor_provider.cpp new file mode 100644 index 0000000000..f6e8e598ff --- /dev/null +++ b/ets2panda/lsp/src/refactor_provider.cpp @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "refactor_provider.h" +#include "refactors/refactor_types.h" + +namespace ark::es2panda::lsp { + +void RefactorProvider::RegisterRefactor(const std::string &name, std::unique_ptr refactor) +{ + refactors_.emplace(name, std::move(refactor)); +} + +RefactorProvider &RefactorProvider::Instance() +{ + static RefactorProvider instance; + return instance; +} + +std::unique_ptr RefactorProvider::GetEditsForRefactor(const RefactorContext &context, + const std::string &refactorName, + const std::string &actionName) const +{ + auto it = refactors_.find(refactorName); + if (it == refactors_.end()) { + return nullptr; + } + + return it->second->GetEditsForAction(context, actionName); +} + +std::vector RefactorProvider::GetApplicableRefactors(const RefactorContext &context) const +{ + std::vector applicable; + + for (const auto &[name, refactor] : refactors_) { + auto result = refactor->GetAvailableActions(context); + if (!result.name.empty()) { + applicable.push_back(result); + } + } + + return applicable; +} + +const std::unordered_map> &RefactorProvider::GetRefactors() const +{ + return refactors_; +} + +} // namespace ark::es2panda::lsp diff --git a/ets2panda/lsp/src/refactors/convert_function.cpp b/ets2panda/lsp/src/refactors/convert_function.cpp index d5996360f3..e594fa230a 100644 --- a/ets2panda/lsp/src/refactors/convert_function.cpp +++ b/ets2panda/lsp/src/refactors/convert_function.cpp @@ -15,10 +15,12 @@ #include #include "refactors/convert_function.h" +#include "refactor_provider.h" #include "compiler/lowering/util.h" #include "internal_api.h" namespace ark::es2panda::lsp { + ConvertFunctionRefactor::ConvertFunctionRefactor() { AddKind(std::string(TO_ANONYMOUS_FUNCTION_ACTION.kind)); @@ -26,27 +28,43 @@ ConvertFunctionRefactor::ConvertFunctionRefactor() AddKind(std::string(TO_ARROW_FUNCTION_ACTION.kind)); } -ApplicableRefactorInfo ConvertFunctionRefactor::GetAvailableActions(es2panda_Context *context, std::string kind, - size_t position) +ApplicableRefactorInfo ConvertFunctionRefactor::GetAvailableActions(const RefactorContext &refContext) const { + es2panda_Context *context = refContext.context; + size_t position = refContext.span.pos; + ApplicableRefactorInfo res; - if (TO_NAMED_FUNCTION_ACTION.kind.substr(0, kind.length()) != kind) { + + if (!IsKind(refContext.kind)) { return res; } + auto node = GetTouchingToken(context, position, false); if (node == nullptr || !node->IsIdentifier()) { return res; } + auto nodeDecl = compiler::DeclarationFromIdentifier(node->AsIdentifier()); - if (nodeDecl->IsClassProperty() && nodeDecl->AsClassProperty()->Value()->IsArrowFunctionExpression()) { + if (nodeDecl != nullptr && nodeDecl->IsClassProperty() && nodeDecl->AsClassProperty()->Value() != nullptr && + nodeDecl->AsClassProperty()->Value()->IsArrowFunctionExpression()) { res.name = refactor_name::CONVERT_FUNCTION_REFACTOR_NAME; res.description = refactor_description::CONVERT_FUNCTION_REFACTOR_DESC; res.action.kind = std::string(TO_NAMED_FUNCTION_ACTION.kind); res.action.name = std::string(TO_NAMED_FUNCTION_ACTION.name); res.action.description = std::string(TO_NAMED_FUNCTION_ACTION.description); - return res; } return res; } -} // namespace ark::es2panda::lsp \ No newline at end of file + +std::unique_ptr ConvertFunctionRefactor::GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const +{ + (void)context; + (void)actionName; + return std::make_unique(); +} +// NOLINTNEXTLINE(fuchsia-statically-constructed-objects, cert-err58-cpp) +AutoRefactorRegister g_convertFunctionRefactorRegister("ConvertFunctionRefactor"); + +} // namespace ark::es2panda::lsp diff --git a/ets2panda/lsp/src/refactors/refactor_types.cpp b/ets2panda/lsp/src/refactors/refactor_types.cpp new file mode 100644 index 0000000000..4a9c1a1980 --- /dev/null +++ b/ets2panda/lsp/src/refactors/refactor_types.cpp @@ -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. + */ + +#include "refactors/refactor_types.h" + +namespace ark::es2panda::lsp { + +Refactor::Refactor(const Refactor &other) +{ + kinds_.insert(kinds_.end(), other.kinds_.begin(), other.kinds_.end()); +} + +Refactor &Refactor::operator=(const Refactor &other) +{ + kinds_.insert(kinds_.end(), other.kinds_.begin(), other.kinds_.end()); + return *this; +} + +Refactor &Refactor::operator=(Refactor &&other) +{ + kinds_.insert(kinds_.end(), other.kinds_.begin(), other.kinds_.end()); + return *this; +} + +Refactor::Refactor(Refactor &&other) +{ + kinds_.insert(kinds_.end(), other.kinds_.begin(), other.kinds_.end()); +} + +bool Refactor::IsKind(const std::string &kind) const +{ + for (const std::string &rKind : kinds_) { + if (rKind.substr(0, kind.length()) == kind) { + return true; + } + } + return false; +} + +void Refactor::AddKind(const std::string &kind) +{ + kinds_.push_back(kind); +} + +} // namespace ark::es2panda::lsp \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/CMakeLists.txt b/ets2panda/test/unit/lsp/CMakeLists.txt index 6f10ba2d98..82d3f06764 100644 --- a/ets2panda/test/unit/lsp/CMakeLists.txt +++ b/ets2panda/test/unit/lsp/CMakeLists.txt @@ -15,10 +15,6 @@ ets2panda_add_gtest(lsp_get_definition_at_position_test CPP_SOURCES get_definition_at_position_test.cpp ) -ets2panda_add_gtest(lsp_api_test_get_applicable_refactors CPP_SOURCES - refactors_convert_function_test.cpp -) - ets2panda_add_gtest(lsp_get_file_references_test CPP_SOURCES get_file_references_test.cpp ) @@ -168,6 +164,10 @@ ets2panda_add_gtest(lsp_api_test_inlay_hints CPP_SOURCES inlay_hints_test.cpp ) +ets2panda_add_gtest(lsp_api_test_refactor_provider_test CPP_SOURCES + refactor_provider_test.cpp +) + ets2panda_add_gtest(lsp_api_test_find_rename_locations CPP_SOURCES find_rename_locations_test.cpp ) diff --git a/ets2panda/test/unit/lsp/refactor_provider_test.cpp b/ets2panda/test/unit/lsp/refactor_provider_test.cpp new file mode 100644 index 0000000000..b033fa469d --- /dev/null +++ b/ets2panda/test/unit/lsp/refactor_provider_test.cpp @@ -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. + */ + +#include +#include "lsp/include/refactor_provider.h" +#include "lsp/include/refactors/convert_function.h" +#include "lsp/include/types.h" +#include "lsp_api_test.h" // LSPAPITests header file + +namespace { +class RefactorProviderRegistrationTest : public LSPAPITests {}; + +TEST(RefactorProviderRegistrationTest, RegistersConvertFunctionRefactor) +{ + const auto &provider = ark::es2panda::lsp::RefactorProvider::Instance(); + const auto &refactors = provider.GetRefactors(); + + auto it = refactors.find("ConvertFunctionRefactor"); + + ASSERT_NE(it, refactors.end()) << "ConvertFunctionRefactor was not registered in RefactorProvider."; +} +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/refactors_convert_function_test.cpp b/ets2panda/test/unit/lsp/refactors_convert_function_test.cpp deleted file mode 100644 index 2688b3b2c5..0000000000 --- a/ets2panda/test/unit/lsp/refactors_convert_function_test.cpp +++ /dev/null @@ -1,87 +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 -#include "lsp_api_test.h" - -namespace { -using ark::es2panda::lsp::Initializer; - -class LspGetRefTests : public LSPAPITests { -public: - static constexpr std::string_view TO_NAMED_FUNCTION_KIND = "refactor.rewrite.function.named"; - static constexpr std::string_view INVALID_KIND = "aaabbbccc"; - static constexpr std::string_view TO_NAMED_FUNCTION_NAME = "Convert to named function"; -}; - -TEST_F(LspGetRefTests, ConvertFunctionRefactor1) -{ - std::vector files = {"convertFunctionRefactor1.ets"}; - std::vector texts = {R"(const add = (x: number, y: number): number => { - return x + y; - };)"}; - auto filePaths = CreateTempFile(files, texts); - size_t const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - - LSPAPI const *lspApi = GetImpl(); - size_t const position = 8; - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - auto result = lspApi->getApplicableRefactors(ctx, std::string(TO_NAMED_FUNCTION_KIND).c_str(), position); - initializer.DestroyContext(ctx); - ASSERT_EQ(std::string(TO_NAMED_FUNCTION_NAME), result.action.name); -} - -TEST_F(LspGetRefTests, ConvertFunctionRefactor2) -{ - std::vector files = {"convertFunctionRefactor2.ets"}; - std::vector texts = {R"(function sub(a: number, b: number): number{ - return a - b; - };)"}; - auto filePaths = CreateTempFile(files, texts); - size_t const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - - LSPAPI const *lspApi = GetImpl(); - size_t const position = 11; - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - auto result = lspApi->getApplicableRefactors(ctx, std::string(TO_NAMED_FUNCTION_KIND).c_str(), position); - initializer.DestroyContext(ctx); - ASSERT_EQ(std::string(""), result.name); -} - -TEST_F(LspGetRefTests, ConvertFunctionRefactor3) -{ - std::vector files = {"convertFunctionRefactor3.ets"}; - std::vector texts = {R"(const add = (x: number, y: number): number => { - return x + y; - };)"}; - auto filePaths = CreateTempFile(files, texts); - size_t const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - - LSPAPI const *lspApi = GetImpl(); - size_t const position = 8; - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - auto result = lspApi->getApplicableRefactors(ctx, std::string(INVALID_KIND).c_str(), position); - initializer.DestroyContext(ctx); - ASSERT_EQ(std::string(""), result.name); -} -} // namespace \ No newline at end of file -- Gitee From 83f5d7005b98af216317e5906e4b71e2886fb990 Mon Sep 17 00:00:00 2001 From: dogasahin Date: Thu, 29 May 2025 13:44:41 +0300 Subject: [PATCH 054/145] [LSP-API] GetNameOrDottedNameSpan Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/IC9UFH Signed-off-by: dogasahin --- ets2panda/lsp/BUILD.gn | 1 + ets2panda/lsp/CMakeLists.txt | 1 + ets2panda/lsp/include/api.h | 1 + .../include/get_name_or_dotted_name_span.h | 33 ++++ ets2panda/lsp/src/api.cpp | 10 +- .../lsp/src/get_name_or_dotted_name_span.cpp | 145 +++++++++++++++++ ets2panda/test/unit/lsp/CMakeLists.txt | 4 + .../lsp/get_name_or_dotted_name_span_test.cpp | 153 ++++++++++++++++++ 8 files changed, 347 insertions(+), 1 deletion(-) create mode 100644 ets2panda/lsp/include/get_name_or_dotted_name_span.h create mode 100644 ets2panda/lsp/src/get_name_or_dotted_name_span.cpp create mode 100644 ets2panda/test/unit/lsp/get_name_or_dotted_name_span_test.cpp diff --git a/ets2panda/lsp/BUILD.gn b/ets2panda/lsp/BUILD.gn index 94fcff39ba..e8572f6d7c 100644 --- a/ets2panda/lsp/BUILD.gn +++ b/ets2panda/lsp/BUILD.gn @@ -63,6 +63,7 @@ ohos_source_set("libes2panda_lsp_static") { "src/get_adjusted_location.cpp", "src/get_class_property_info.cpp", "src/get_definition_and_bound_span.cpp", + "src/get_name_or_dotted_name_span.cpp", "src/get_safe_delete_info.cpp", "src/inlay_hints.cpp", "src/internal_api.cpp", diff --git a/ets2panda/lsp/CMakeLists.txt b/ets2panda/lsp/CMakeLists.txt index 41272e7af7..b3dd0cc578 100644 --- a/ets2panda/lsp/CMakeLists.txt +++ b/ets2panda/lsp/CMakeLists.txt @@ -64,6 +64,7 @@ set(ES2PANDA_LSP_SRC ./src/register_code_fix/fix_nan_equality.cpp ./src/register_code_fix/forgetten_this_property_access.cpp ./src/register_code_fix/import_fixes.cpp + ./src/get_name_or_dotted_name_span.cpp ) panda_add_library(${LSP_LIB} SHARED ${ES2PANDA_LSP_SRC}) diff --git a/ets2panda/lsp/include/api.h b/ets2panda/lsp/include/api.h index 424200a26f..b49cab1586 100644 --- a/ets2panda/lsp/include/api.h +++ b/ets2panda/lsp/include/api.h @@ -543,6 +543,7 @@ typedef struct LSPAPI { CodeFixOptions &codeFixOptions); CombinedCodeActionsInfo (*getCombinedCodeFix)(const char *fileName, const std::string &fixId, CodeFixOptions &codeFixOptions); + TextSpan *(*GetNameOrDottedNameSpan)(es2panda_Context *context, int startPos); } LSPAPI; CAPI_EXPORT LSPAPI const *GetImpl(); // NOLINTEND diff --git a/ets2panda/lsp/include/get_name_or_dotted_name_span.h b/ets2panda/lsp/include/get_name_or_dotted_name_span.h new file mode 100644 index 0000000000..1835282643 --- /dev/null +++ b/ets2panda/lsp/include/get_name_or_dotted_name_span.h @@ -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. + */ + +#ifndef GET_NAME_OR_DOTTED_NAME_SPAN_H +#define GET_NAME_OR_DOTTED_NAME_SPAN_H + +#include "api.h" +#include "ir/astNode.h" +#include "es2panda.h" +#include "public/es2panda_lib.h" + +namespace ark::es2panda::lsp { +bool IsRightSideOfPropertyAccess(ir::AstNode *node); +bool IsRightSideOfQualifiedName(ir::AstNode *node); +bool IsNameOfModuleDeclaration(ir::AstNode *node); +ir::AstNode *AscendToRootName(ir::AstNode *node); + +TextSpan *GetNameOrDottedNameSpanImpl(es2panda_Context *context, int startPos); + +} // namespace ark::es2panda::lsp +#endif // GET_NAME_OR_DOTTED_NAME_SPAN_H \ No newline at end of file diff --git a/ets2panda/lsp/src/api.cpp b/ets2panda/lsp/src/api.cpp index 0de730e3e1..5ea606a0bf 100644 --- a/ets2panda/lsp/src/api.cpp +++ b/ets2panda/lsp/src/api.cpp @@ -40,6 +40,7 @@ #include "inlay_hints.h" #include "signature_help.h" #include "completions_details.h" +#include "get_name_or_dotted_name_span.h" using ark::es2panda::lsp::details::GetCompletionEntryDetailsImpl; @@ -397,6 +398,12 @@ CombinedCodeActionsInfo GetCombinedCodeFix(const char *fileName, const std::stri return result; } +TextSpan *GetNameOrDottedNameSpan(es2panda_Context *context, int startPos) +{ + auto result = ark::es2panda::lsp::GetNameOrDottedNameSpanImpl(context, startPos); + return result; +} + LSPAPI g_lspImpl = {GetDefinitionAtPosition, GetApplicableRefactors, GetImplementationAtPosition, @@ -434,7 +441,8 @@ LSPAPI g_lspImpl = {GetDefinitionAtPosition, ProvideInlayHints, GetSignatureHelpItems, GetCodeFixesAtPosition, - GetCombinedCodeFix}; + GetCombinedCodeFix, + GetNameOrDottedNameSpan}; } // namespace ark::es2panda::lsp CAPI_EXPORT LSPAPI const *GetImpl() diff --git a/ets2panda/lsp/src/get_name_or_dotted_name_span.cpp b/ets2panda/lsp/src/get_name_or_dotted_name_span.cpp new file mode 100644 index 0000000000..3d942472a4 --- /dev/null +++ b/ets2panda/lsp/src/get_name_or_dotted_name_span.cpp @@ -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. + */ + +#include "get_name_or_dotted_name_span.h" +#include "get_adjusted_location.h" +#include + +namespace ark::es2panda::lsp { +bool IsRightSideOfPropertyAccess(ir::AstNode *node) +{ + ir::AstNode *parent = node->Parent(); + + if (parent == nullptr) { + return false; + } + + if (parent->Type() == ir::AstNodeType::MEMBER_EXPRESSION) { + auto *memberExpr = static_cast(parent); + return memberExpr->Property() == node; + } + + if (parent->Type() == ir::AstNodeType::CALL_EXPRESSION) { + auto *callExpr = static_cast(parent); + ir::AstNode *callee = callExpr->Callee(); + + if (callee->Type() == ir::AstNodeType::MEMBER_EXPRESSION) { + auto *memberExpr = static_cast(callee); + return memberExpr->Property() == node; + } + } + + return false; +} + +bool IsNameOfModuleDeclaration(ir::AstNode *node) +{ + ir::AstNode *parent = node->Parent(); + if (parent == nullptr || parent->Type() != ir::AstNodeType::TS_MODULE_DECLARATION) { + return false; + } + + auto *moduleDecl = static_cast(parent); + return moduleDecl->Name() == node; +} + +bool IsRightSideOfQualifiedName(ir::AstNode *node) +{ + ir::AstNode *parent = node->Parent(); + if (parent == nullptr || (parent->Type() != ir::AstNodeType::TS_QUALIFIED_NAME && + parent->Type() != ir::AstNodeType::MEMBER_EXPRESSION)) { + return false; + } + + if (parent->Type() == ir::AstNodeType::TS_QUALIFIED_NAME) { + auto *qualifiedName = static_cast(parent); + return qualifiedName->Right() == node; + } + + if (parent->Type() == ir::AstNodeType::MEMBER_EXPRESSION) { + auto *memberExpr = static_cast(parent); + return memberExpr->Property() == node; + } + + return false; +} + +ir::AstNode *AscendToRootName(ir::AstNode *node) +{ + while (node != nullptr) { + if (IsRightSideOfPropertyAccess(node) || IsRightSideOfQualifiedName(node)) { + node = node->Parent(); + continue; + } + + if (!IsNameOfModuleDeclaration(node)) { + break; + } + + ir::AstNode *parentDecl = node->Parent(); + if (parentDecl == nullptr || parentDecl->Parent() == nullptr) { + break; + } + + if (parentDecl->Parent()->Type() != ir::AstNodeType::TS_MODULE_DECLARATION) { + break; + } + + auto *grandParent = static_cast(parentDecl->Parent()); + if (grandParent->Body() != parentDecl) { + break; + } + + node = const_cast(static_cast(grandParent->Name())); + } + + return node; +} + +TextSpan *GetNameOrDottedNameSpanImpl(es2panda_Context *context, int startPos) +{ + ir::AstNode *astNode = ark::es2panda::lsp::GetTouchingPropertyName(context, startPos); + if (astNode == nullptr) { + return nullptr; + } + + switch (astNode->Type()) { + case ir::AstNodeType::TS_QUALIFIED_NAME: + case ir::AstNodeType::STRING_LITERAL: + case ir::AstNodeType::TS_BOOLEAN_KEYWORD: + case ir::AstNodeType::TS_NULL_KEYWORD: + case ir::AstNodeType::SUPER_EXPRESSION: + case ir::AstNodeType::THIS_EXPRESSION: + case ir::AstNodeType::TS_THIS_TYPE: + case ir::AstNodeType::IDENTIFIER: + break; + default: + return nullptr; + } + + auto nodeForStartPos = AscendToRootName(astNode); + if (nodeForStartPos == nullptr) { + return nullptr; + } + size_t start = nodeForStartPos->Start().index; + size_t end = nodeForStartPos->End().index; + if (start >= end) { + return nullptr; + } + + auto span = new TextSpan(start, end - start); + return span; +} +} // namespace ark::es2panda::lsp \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/CMakeLists.txt b/ets2panda/test/unit/lsp/CMakeLists.txt index 82d3f06764..e50ecc4ac0 100644 --- a/ets2panda/test/unit/lsp/CMakeLists.txt +++ b/ets2panda/test/unit/lsp/CMakeLists.txt @@ -210,3 +210,7 @@ ets2panda_add_gtest(lsp_api_test_navigate_to CPP_SOURCES ets2panda_add_gtest(lsp_api_test_code_fix_registration CPP_SOURCES code_fix_registration_test.cpp ) + +ets2panda_add_gtest(lsp_api_test_get_name_or_dotted_name_span CPP_SOURCES + get_name_or_dotted_name_span_test.cpp +) \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/get_name_or_dotted_name_span_test.cpp b/ets2panda/test/unit/lsp/get_name_or_dotted_name_span_test.cpp new file mode 100644 index 0000000000..26eb5a80b6 --- /dev/null +++ b/ets2panda/test/unit/lsp/get_name_or_dotted_name_span_test.cpp @@ -0,0 +1,153 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "lsp_api_test.h" +#include "lsp/include/internal_api.h" +#include "lsp/include/get_name_or_dotted_name_span.h" + +namespace { +const size_t IDENTIFIER_ONLY_IDX = 24; +const size_t PROPERTY_ACCESS_IDX = 36; +const size_t FULL_DOTTED_EXPR_IDX = 56; +const size_t INVALID_TOKEN_IDX = 31; +const size_t MODULE_DECLARATION_QUALIFIED_NAME_IDX = 72; + +std::string ExtractSpanText(const std::string &source, const TextSpan *span) +{ + if (span == nullptr || span->start + span->length > source.size()) { + return {}; + } + + return source.substr(span->start, span->length); +} + +class GetNameOrDottedNameSpanTests : public LSPAPITests {}; +TEST_F(GetNameOrDottedNameSpanTests, GetNameSpanFromSimpleIdentifier) +{ + std::vector fileNames = {"get_name_span_from_simple_identifier.ets"}; + std::vector fileContents = { + R"( +function myMethod() {} +myMethod(); + )"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + ASSERT_EQ(filePaths.size(), 1); + + ark::es2panda::lsp::Initializer initializer; + auto context = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto content = fileContents[0]; + auto span = ark::es2panda::lsp::GetNameOrDottedNameSpanImpl(context, IDENTIFIER_ONLY_IDX); + ASSERT_NE(span, nullptr); + EXPECT_EQ(ExtractSpanText(content, span), "myMethod"); + initializer.DestroyContext(context); +} + +TEST_F(GetNameOrDottedNameSpanTests, GetNameSpanFromPropertyAccess) +{ + std::vector fileNames = {"get_name_span_from_property_access.ets"}; + std::vector fileContents = { + R"( +class A { +static myMethod() {} +} +A.myMethod(); + )"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + ASSERT_EQ(filePaths.size(), 1); + + ark::es2panda::lsp::Initializer initializer; + auto context = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto content = fileContents[0]; + auto span = ark::es2panda::lsp::GetNameOrDottedNameSpanImpl(context, PROPERTY_ACCESS_IDX); + ASSERT_NE(span, nullptr); + EXPECT_EQ(ExtractSpanText(content, span), "A.myMethod"); + initializer.DestroyContext(context); +} + +TEST_F(GetNameOrDottedNameSpanTests, GetNameSpanFromNestedNamespaceClassCall) +{ + std::vector fileNames = {"get_name_span_from_nested_namespace_class_call.ets"}; + std::vector fileContents = { + R"( +namespace A { +export class B { +static foo() {} +} +} +A.B.foo(); + )"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + ASSERT_EQ(filePaths.size(), 1); + + ark::es2panda::lsp::Initializer initializer; + auto context = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto content = fileContents[0]; + auto span = ark::es2panda::lsp::GetNameOrDottedNameSpanImpl(context, FULL_DOTTED_EXPR_IDX); + ASSERT_NE(span, nullptr); + EXPECT_EQ(ExtractSpanText(content, span), "A.B.foo"); + initializer.DestroyContext(context); +} + +TEST_F(GetNameOrDottedNameSpanTests, GetNameSpanFromInvalidToken) +{ + std::vector fileNames = {"get_name_span_from_invalid_token.ets"}; + std::vector fileContents = { + R"( +let message = "hello"; +console.log(message); + )"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + ASSERT_EQ(filePaths.size(), 1); + + ark::es2panda::lsp::Initializer initializer; + auto context = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto content = fileContents[0]; + auto span = ark::es2panda::lsp::GetNameOrDottedNameSpanImpl(context, INVALID_TOKEN_IDX); + EXPECT_EQ(span, nullptr); + initializer.DestroyContext(context); +} + +TEST_F(GetNameOrDottedNameSpanTests, GetNameSpanFromQualifiedNamespaceFunction) +{ + std::vector fileNames = {"get_name_span_from_qualified_namespace_function.ets"}; + std::vector fileContents = { + R"( +namespace Outer.Inner { + export function greet() {} +} + +Outer.Inner.greet(); + )"}; + + auto filePaths = CreateTempFile(fileNames, fileContents); + ASSERT_EQ(filePaths.size(), 1); + ark::es2panda::lsp::Initializer initializer; + auto context = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + auto content = fileContents[0]; + auto span = ark::es2panda::lsp::GetNameOrDottedNameSpanImpl(context, MODULE_DECLARATION_QUALIFIED_NAME_IDX); + ASSERT_NE(span, nullptr); + EXPECT_EQ(ExtractSpanText(content, span), "Outer.Inner.greet"); + initializer.DestroyContext(context); +} +} // namespace \ No newline at end of file -- Gitee From cf7da4f050b152f4137a9afa47b740a59a900e0e Mon Sep 17 00:00:00 2001 From: zmw Date: Sat, 7 Jun 2025 14:53:23 +0800 Subject: [PATCH 055/145] Fix assert string to bool Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICDBZ7 Description: Fix assert string to bool Signed-off-by: zmw --- ets2panda/lsp/src/code_fix_provider.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ets2panda/lsp/src/code_fix_provider.cpp b/ets2panda/lsp/src/code_fix_provider.cpp index 1843912767..0aacb84467 100644 --- a/ets2panda/lsp/src/code_fix_provider.cpp +++ b/ets2panda/lsp/src/code_fix_provider.cpp @@ -28,9 +28,8 @@ namespace ark::es2panda::lsp { void CodeFixProvider::RegisterCodeFix(const std::string &aliasName, std::unique_ptr registration) { - if (aliasName.empty()) { - ASSERT("Alias name cannot be empty"); - } + (void)aliasName; + ASSERT(!aliasName.empty()); auto shared = std::shared_ptr(std::move(registration)); for (auto error : shared->GetErrorCodes()) { -- Gitee From 0ed5bae41eca68980702e4162b722bd27684fde0 Mon Sep 17 00:00:00 2001 From: yaohaosen Date: Wed, 4 Jun 2025 20:58:50 +0800 Subject: [PATCH 056/145] [LSP] Support UI Plugin Code Fixes Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICC5VX Signed-off-by: yaohaosen --- ets2panda/bindings/native/src/lsp.cpp | 68 +++++++ .../bindings/src/Es2pandaNativeModule.ts | 31 ++- ets2panda/bindings/src/buildConfigGenerate.ts | 19 +- ets2panda/bindings/src/lspNode.ts | 37 ++++ ets2panda/bindings/src/lsp_helper.ts | 39 +++- ets2panda/lsp/BUILD.gn | 1 + ets2panda/lsp/CMakeLists.txt | 1 + ets2panda/lsp/include/api.h | 6 +- ets2panda/lsp/include/cancellation_token.h | 1 + ets2panda/lsp/include/internal_api.h | 41 ++++ .../register_code_fix/ui_plugin_suggest.h | 39 ++++ ets2panda/lsp/src/api.cpp | 18 +- ets2panda/lsp/src/internal_api.cpp | 17 +- .../register_code_fix/ui_plugin_suggest.cpp | 117 ++++++++++++ ets2panda/test/unit/lsp/CMakeLists.txt | 4 + .../unit/lsp/code_fix/ui_plugin_suggest.cpp | 180 ++++++++++++++++++ .../unit/lsp/code_fix_registration_test.cpp | 1 - ets2panda/test/unit/lsp/get_diagnostics.cpp | 18 +- ets2panda/util/diagnostic.h | 5 + 19 files changed, 618 insertions(+), 25 deletions(-) create mode 100644 ets2panda/lsp/include/register_code_fix/ui_plugin_suggest.h create mode 100644 ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp create mode 100644 ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp diff --git a/ets2panda/bindings/native/src/lsp.cpp b/ets2panda/bindings/native/src/lsp.cpp index 286efef597..f8f6c9c669 100644 --- a/ets2panda/bindings/native/src/lsp.cpp +++ b/ets2panda/bindings/native/src/lsp.cpp @@ -1258,6 +1258,74 @@ KInt impl_getTypeFromTypeHierarchies(KNativePointer infoPtr) } TS_INTEROP_1(getTypeFromTypeHierarchies, KInt, KNativePointer) +KNativePointer impl_getCodeFixesAtPosition(KNativePointer context, KInt startPosition, KInt endPosition, + KInt *errorCodesPtr, KInt codeLength) +{ + CodeFixOptions emptyOptions; + std::vector errorCodesInt; + if (errorCodesPtr != nullptr && codeLength > 0) { + // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic,-warnings-as-errors) + errorCodesInt = std::vector(reinterpret_cast(errorCodesPtr), + reinterpret_cast(errorCodesPtr) + codeLength); + // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic,-warnings-as-errors) + } + LSPAPI const *ctx = GetImpl(); + auto autofix = ctx->getCodeFixesAtPosition(reinterpret_cast(context), startPosition, + endPosition, errorCodesInt, emptyOptions); + return new std::vector(autofix); +} +TS_INTEROP_5(getCodeFixesAtPosition, KNativePointer, KNativePointer, KInt, KInt, KInt *, KInt) + +KNativePointer impl_getCodeFixActionInfos(KNativePointer codeFixActionInfoListPtr) +{ + auto *getCodeFixActionInfoList = reinterpret_cast(codeFixActionInfoListPtr); + std::vector ptrs; + for (auto &el : getCodeFixActionInfoList->infos_) { + ptrs.push_back(new CodeFixActionInfo(el)); + } + return new std::vector(ptrs); +} +TS_INTEROP_1(getCodeFixActionInfos, KNativePointer, KNativePointer) + +KNativePointer impl_getFileTextChangesFromCodeActionInfo(KNativePointer infoPtr) +{ + auto *info = reinterpret_cast(infoPtr); + std::vector ptrs; + for (auto &el : info->changes_) { + ptrs.push_back(new FileTextChanges(el)); + } + return new std::vector(ptrs); +} +TS_INTEROP_1(getFileTextChangesFromCodeActionInfo, KNativePointer, KNativePointer) + +KNativePointer impl_getDescriptionFromCodeActionInfo(KNativePointer infoPtr) +{ + auto *info = reinterpret_cast(infoPtr); + return new std::string(info->description_); +} +TS_INTEROP_1(getDescriptionFromCodeActionInfo, KNativePointer, KNativePointer) + +KNativePointer impl_getFixNameFromCodeFixActionInfo(KNativePointer infoPtr) +{ + auto *info = reinterpret_cast(infoPtr); + return new std::string(info->fixName_); +} +TS_INTEROP_1(getFixNameFromCodeFixActionInfo, KNativePointer, KNativePointer) + +KNativePointer impl_getFixIdFromCodeFixActionInfo(KNativePointer infoPtr) +{ + auto *info = reinterpret_cast(infoPtr); + return new std::string(info->fixId_); +} +TS_INTEROP_1(getFixIdFromCodeFixActionInfo, KNativePointer, KNativePointer) + +KNativePointer impl_getFixAllDescriptionFromCodeFixActionInfo(KNativePointer infoPtr) +{ + auto *info = reinterpret_cast(infoPtr); + return new std::string(info->fixAllDescription_); +} +TS_INTEROP_1(getFixAllDescriptionFromCodeFixActionInfo, KNativePointer, KNativePointer) + KNativePointer impl_getSpanOfEnclosingComment(KNativePointer context, KInt position, KBoolean onlyMultiLine) { LSPAPI const *ctx = GetImpl(); diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts index 72ef3873b9..effe426fb7 100644 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/Es2pandaNativeModule.ts @@ -14,7 +14,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import { KNativePointer as KPtr, KInt, KBoolean, KNativePointer, KDouble, KUInt, KStringPtr } from './InteropTypes'; +import { KNativePointer as KPtr, KInt, KBoolean, KNativePointer, KDouble, KUInt, KStringPtr, KInt32ArrayPtr } from './InteropTypes'; import { Es2pandaNativeModule as GeneratedEs2pandaNativeModule } from './generated/Es2pandaNativeModule'; import { loadNativeModuleLibrary, registerNativeModuleLibraryName } from './loadLibraries'; import { throwError } from './utils'; @@ -724,6 +724,35 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } + _getCodeFixesAtPosition(context: KNativePointer, startPosition: KInt, endPosition: KInt, + errorCodesPtr: KInt32ArrayPtr, codeLength: KInt): KPtr { + throw new Error('Not implemented'); + } + + _getCodeFixActionInfos(infoPtr: KNativePointer): KPtr { + throw new Error('Not implemented'); + } + + _getFileTextChangesFromCodeActionInfo(infoPtr: KNativePointer): KPtr { + throw new Error('Not implemented'); + } + + _getDescriptionFromCodeActionInfo(infoPtr: KNativePointer): KPtr { + throw new Error('Not implemented'); + } + + _getFixNameFromCodeFixActionInfo(infoPtr: KNativePointer): KPtr { + throw new Error('Not implemented'); + } + + _getFixIdFromCodeFixActionInfo(infoPtr: KNativePointer): KPtr { + throw new Error('Not implemented'); + } + + _getFixAllDescriptionFromCodeFixActionInfo(infoPtr: KNativePointer): KPtr { + throw new Error('Not implemented'); + } + _getInlayHintText(ptr: KPtr): KPtr { throw new Error('Not implemented'); } diff --git a/ets2panda/bindings/src/buildConfigGenerate.ts b/ets2panda/bindings/src/buildConfigGenerate.ts index 4d1b1c34d1..478196c6aa 100644 --- a/ets2panda/bindings/src/buildConfigGenerate.ts +++ b/ets2panda/bindings/src/buildConfigGenerate.ts @@ -161,6 +161,19 @@ function getModuleDependencies(modulePath: string, visited = new Set()): return Array.from(new Set([...dependencies, ...nestedDependencies])); } +function createMapEntryForPlugin(buildSdkPath: string, pluginName: string): string { + return path.join(buildSdkPath, 'build-tools', 'ui-plugins', 'lib', pluginName, 'index'); +} + +function createPluginMap(buildSdkPath: string): Record { + let pluginMap: Record = {}; + const pluginList: string[] = ['ui-syntax-plugins', 'ui-plugins', 'memo-plugins']; + for (const plugin of pluginList) { + pluginMap[plugin] = createMapEntryForPlugin(buildSdkPath, plugin); + } + return pluginMap; +} + export function generateBuildConfigs( buildSdkPath: string, projectRoot: string, @@ -179,6 +192,7 @@ export function generateBuildConfigs( for (const module of definedModules) { const modulePath = module.srcPath; const compileFiles = new Set(getEtsFiles(modulePath)); + const pluginMap = createPluginMap(buildSdkPath); // Get recursive dependencies const dependencies = getModuleDependencies(modulePath); @@ -187,10 +201,7 @@ export function generateBuildConfigs( } 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') - }, + plugins: pluginMap, arkts: {}, arktsGlobal: {}, compileFiles: Array.from(compileFiles), diff --git a/ets2panda/bindings/src/lspNode.ts b/ets2panda/bindings/src/lspNode.ts index 17f846fce2..5f305aa2d6 100644 --- a/ets2panda/bindings/src/lspNode.ts +++ b/ets2panda/bindings/src/lspNode.ts @@ -644,6 +644,43 @@ export class FileTextChanges extends LspNode { readonly textChanges: TextChange[]; } +export class CodeActionInfo extends LspNode { + constructor(peer: KNativePointer) { + super(peer); + this.changes = new NativePtrDecoder() + .decode(global.es2panda._getFileTextChangesFromCodeActionInfo(peer)) + .map((elPeer: KNativePointer) => { + return new FileTextChanges(elPeer); + }); + this.description = unpackString(global.es2panda._getDescriptionFromCodeActionInfo(peer)); + } + readonly changes: FileTextChanges[]; + readonly description: String; +} + +export class CodeFixActionInfo extends CodeActionInfo { + constructor(peer: KNativePointer) { + super(peer); + this.fixName = unpackString(global.es2panda._getFixNameFromCodeFixActionInfo(peer)); + this.fixId_ = unpackString(global.es2panda._getFixIdFromCodeFixActionInfo(peer)); + this.fixAllDescription_ = unpackString(global.es2panda._getFixAllDescriptionFromCodeFixActionInfo(peer)); + } + readonly fixName: String; + readonly fixId_: String; + readonly fixAllDescription_: String; +} + +export class CodeFixActionInfoList extends LspNode { + constructor(peer: KNativePointer) { + super(peer); + this.codeFixActionInfos = new NativePtrDecoder() + .decode(global.es2panda._getCodeFixActionInfos(peer)) + .map((elPeer: KNativePointer) => { + return new CodeFixActionInfo(elPeer); + }); + } + readonly codeFixActionInfos: CodeFixActionInfo[]; +} export class LspFileTextChanges extends LspNode { constructor(peer: KNativePointer) { diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index b543a2b07e..7effce3147 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -40,7 +40,9 @@ import { LspInlayHint, LspInlayHintList, TextSpan, - LspSignatureHelpItems + LspSignatureHelpItems, + CodeFixActionInfo, + CodeFixActionInfoList } from './lspNode'; import { passStringArray, unpackString } from './private'; import { Es2pandaContextState } from './generated/Es2pandaEnums'; @@ -111,6 +113,16 @@ export class Lsp { return getSource.replace(/\r\n/g, '\n'); } + private getModuleNameFromFilename(filePath: string): string { + const projectRoot = this.projectPath; + if (!filePath.startsWith(projectRoot)) { + return ''; + } + const relativePath = path.relative(projectRoot, filePath); + const parts = relativePath.split(path.sep); + return parts[0] || ''; + } + getDefinitionAtPosition(filename: String, offset: number): LspDefinitionData { let lspDriverHelper = new LspDriverHelper(); let filePath = path.resolve(filename.valueOf()); @@ -529,6 +541,9 @@ export class Lsp { let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); const source = this.getFileSource(filePath); let localCtx = lspDriverHelper.createCtx(source, filePath, localCfg); + const moduleName = this.getModuleNameFromFilename(filePath); + const buildConfig = this.moduleToBuildConfig[moduleName]; + PluginDriver.getInstance().getPluginContext().setProjectConfig(buildConfig); PluginDriver.getInstance().getPluginContext().setContextPtr(localCtx); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); @@ -683,6 +698,28 @@ export class Lsp { return new LspTextSpan(ptr); } + getCodeFixesAtPosition(filename: String, start: number, end: number, errorCodes: number[]): CodeFixActionInfo[] { + let lspDriverHelper = new LspDriverHelper(); + let filePath = path.resolve(filename.valueOf()); + let arktsconfig = this.fileNameToArktsconfig[filePath]; + let ets2pandaCmd = ets2pandaCmdPrefix.concat(arktsconfig); + let localCfg = lspDriverHelper.createCfg(ets2pandaCmd, filePath, this.pandaLibPath); + const source = this.getFileSource(filePath); + 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._getCodeFixesAtPosition(localCtx, start, end, new Int32Array(errorCodes), errorCodes.length); + PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); + lspDriverHelper.destroyContext(localCtx); + lspDriverHelper.destroyConfig(localCfg); + const codeFixActionInfoList = new CodeFixActionInfoList(ptr); + const codeFixActionInfos: CodeFixActionInfo[] = []; + codeFixActionInfos.push(...codeFixActionInfoList.codeFixActionInfos); + return codeFixActionInfos; + } + provideInlayHints(filename: String, span: TextSpan): LspInlayHint[] { let lspDriverHelper = new LspDriverHelper(); let filePath = path.resolve(filename.valueOf()); diff --git a/ets2panda/lsp/BUILD.gn b/ets2panda/lsp/BUILD.gn index e8572f6d7c..52c00fa560 100644 --- a/ets2panda/lsp/BUILD.gn +++ b/ets2panda/lsp/BUILD.gn @@ -82,6 +82,7 @@ ohos_source_set("libes2panda_lsp_static") { "src/register_code_fix/forgetten_this_property_access.cpp", "src/register_code_fix/import_fixes.cpp", "src/rename.cpp", + "src/register_code_fix/ui_plugin_suggest.cpp", "src/script_element_kind.cpp", "src/services/services.cpp", "src/services/text_change/change_tracker.cpp", diff --git a/ets2panda/lsp/CMakeLists.txt b/ets2panda/lsp/CMakeLists.txt index b3dd0cc578..ea7f2004ed 100644 --- a/ets2panda/lsp/CMakeLists.txt +++ b/ets2panda/lsp/CMakeLists.txt @@ -64,6 +64,7 @@ set(ES2PANDA_LSP_SRC ./src/register_code_fix/fix_nan_equality.cpp ./src/register_code_fix/forgetten_this_property_access.cpp ./src/register_code_fix/import_fixes.cpp + ./src/register_code_fix/ui_plugin_suggest.cpp ./src/get_name_or_dotted_name_span.cpp ) diff --git a/ets2panda/lsp/include/api.h b/ets2panda/lsp/include/api.h index b49cab1586..bd47d74f9d 100644 --- a/ets2panda/lsp/include/api.h +++ b/ets2panda/lsp/include/api.h @@ -480,6 +480,10 @@ struct CodeFixActionInfo : CodeActionInfo { std::string fixAllDescription_ = {}; }; +struct CodeFixActionInfoList { + std::vector infos_; +}; + struct CodeFixOptions { ark::es2panda::lsp::CancellationToken token; ark::es2panda::lsp::FormatCodeSettings options; @@ -538,7 +542,7 @@ typedef struct LSPAPI { ark::es2panda::lsp::CancellationToken *cancellationToken); InlayHintList (*provideInlayHints)(es2panda_Context *context, const TextSpan *span); SignatureHelpItems (*getSignatureHelpItems)(es2panda_Context *context, size_t position); - std::vector (*getCodeFixesAtPosition)(const char *fileName, size_t start_position, + std::vector (*getCodeFixesAtPosition)(es2panda_Context *context, size_t start_position, size_t end_position, std::vector &errorCodes, CodeFixOptions &codeFixOptions); CombinedCodeActionsInfo (*getCombinedCodeFix)(const char *fileName, const std::string &fixId, diff --git a/ets2panda/lsp/include/cancellation_token.h b/ets2panda/lsp/include/cancellation_token.h index a6a9209127..942f7f957e 100644 --- a/ets2panda/lsp/include/cancellation_token.h +++ b/ets2panda/lsp/include/cancellation_token.h @@ -32,6 +32,7 @@ public: bool IsCancellationRequested(); bool ThrottledCancellationCheck(); CancellationToken(time_t designatedThrottleTime, HostCancellationToken *hostCancellationToken); + CancellationToken() : lastCancellationTime_(0), throttleTime_(0), host_(nullptr) {} private: time_t lastCancellationTime_; diff --git a/ets2panda/lsp/include/internal_api.h b/ets2panda/lsp/include/internal_api.h index 9d1f8ff9b6..b021c901da 100644 --- a/ets2panda/lsp/include/internal_api.h +++ b/ets2panda/lsp/include/internal_api.h @@ -52,6 +52,47 @@ public: impl_->DestroyContext(context); } + const es2panda_DiagnosticKind *CreateDiagnosticKind(es2panda_Context *context, const char *dmessage, + es2panda_PluginDiagnosticType etype) + { + return impl_->CreateDiagnosticKind(context, dmessage, etype); + } + + es2panda_SuggestionInfo *CreateSuggestionInfo(es2panda_Context *context, const es2panda_DiagnosticKind *kind, + const char **args, size_t argc, const char *substitutionCode) + { + return impl_->CreateSuggestionInfo(context, kind, args, argc, substitutionCode); + } + + es2panda_DiagnosticInfo *CreateDiagnosticInfo(es2panda_Context *context, const es2panda_DiagnosticKind *kind, + const char **args, size_t argc) + { + return impl_->CreateDiagnosticInfo(context, kind, args, argc); + } + + es2panda_SourcePosition *CreateSourcePosition(es2panda_Context *context, size_t index, size_t line) + { + return impl_->CreateSourcePosition(context, index, line); + } + + es2panda_SourceRange *CreateSourceRange(es2panda_Context *context, es2panda_SourcePosition *start, + es2panda_SourcePosition *end) + { + return impl_->CreateSourceRange(context, start, end); + } + + void LogDiagnosticWithSuggestion(es2panda_Context *context, const es2panda_DiagnosticInfo *diagnosticInfo, + const es2panda_SuggestionInfo *suggestionInfo, es2panda_SourceRange *range) + { + return impl_->LogDiagnosticWithSuggestion(context, diagnosticInfo, suggestionInfo, range); + } + + void LogDiagnostic(es2panda_Context *context, const es2panda_DiagnosticKind *ekind, const char **args, size_t argc, + es2panda_SourcePosition *pos) + { + return impl_->LogDiagnostic(context, ekind, args, argc, pos); + } + NO_COPY_SEMANTIC(Initializer); NO_MOVE_SEMANTIC(Initializer); diff --git a/ets2panda/lsp/include/register_code_fix/ui_plugin_suggest.h b/ets2panda/lsp/include/register_code_fix/ui_plugin_suggest.h new file mode 100644 index 0000000000..31ebf572bb --- /dev/null +++ b/ets2panda/lsp/include/register_code_fix/ui_plugin_suggest.h @@ -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. + */ + +#ifndef IMPORT_FIXES_H +#define IMPORT_FIXES_H + +#include +#include +#include "lsp/include/code_fixes/code_fix_types.h" +#include "lsp/include/services/text_change/change_tracker.h" +#include "lsp/include/types.h" + +namespace ark::es2panda::lsp { + +class UIPluginSuggest : public CodeFixRegistration { +public: + UIPluginSuggest(); + + static std::vector GetUIPluginCodeFixes(es2panda_Context *context, size_t pos, bool isAll); + + std::vector GetCodeActions(const CodeFixContext &context) override; + + CombinedCodeActions GetAllCodeActions(const CodeFixAllContext &codeFixAll) override; +}; + +} // namespace ark::es2panda::lsp +#endif diff --git a/ets2panda/lsp/src/api.cpp b/ets2panda/lsp/src/api.cpp index 5ea606a0bf..01fbfa3e38 100644 --- a/ets2panda/lsp/src/api.cpp +++ b/ets2panda/lsp/src/api.cpp @@ -192,9 +192,19 @@ DiagnosticReferences GetSyntacticDiagnostics(es2panda_Context *context) DiagnosticReferences result {}; auto ctx = reinterpret_cast(context); const auto &diagnostics = ctx->diagnosticEngine->GetDiagnosticStorage(util::DiagnosticType::SYNTAX); + const auto &diagnosticsPluginError = + ctx->diagnosticEngine->GetDiagnosticStorage(util::DiagnosticType::PLUGIN_ERROR); + const auto &diagnosticsPluginWarning = + ctx->diagnosticEngine->GetDiagnosticStorage(util::DiagnosticType::PLUGIN_WARNING); for (const auto &diagnostic : diagnostics) { result.diagnostic.push_back(CreateDiagnosticForError(context, *diagnostic)); } + for (const auto &diagnostic : diagnosticsPluginError) { + result.diagnostic.push_back(CreateDiagnosticForError(context, *diagnostic)); + } + for (const auto &diagnostic : diagnosticsPluginWarning) { + result.diagnostic.push_back(CreateDiagnosticForError(context, *diagnostic)); + } return result; } @@ -377,14 +387,12 @@ SignatureHelpItems GetSignatureHelpItems(es2panda_Context *context, size_t posit auto cancellationToken = ark::es2panda::lsp::CancellationToken(defaultTime, nullptr); return ark::es2panda::lsp::GetSignatureHelpItems(context, position, invokedReason, cancellationToken); } -std::vector GetCodeFixesAtPosition(const char *fileName, size_t startPosition, size_t endPosition, - std::vector &errorCodes, CodeFixOptions &codeFixOptions) +std::vector GetCodeFixesAtPosition(es2panda_Context *context, size_t startPosition, + size_t endPosition, std::vector &errorCodes, + CodeFixOptions &codeFixOptions) { - Initializer initializer = Initializer(); - auto context = initializer.CreateContext(fileName, ES2PANDA_STATE_CHECKED); auto result = ark::es2panda::lsp::GetCodeFixesAtPositionImpl(context, startPosition, endPosition, errorCodes, codeFixOptions); - initializer.DestroyContext(context); return result; } diff --git a/ets2panda/lsp/src/internal_api.cpp b/ets2panda/lsp/src/internal_api.cpp index 05c9922c14..795777e89e 100644 --- a/ets2panda/lsp/src/internal_api.cpp +++ b/ets2panda/lsp/src/internal_api.cpp @@ -510,16 +510,27 @@ std::string GetOwnerId(ir::AstNode *node) DiagnosticSeverity GetSeverity(util::DiagnosticType errorType) { ES2PANDA_ASSERT(errorType != util::DiagnosticType::INVALID); - if (errorType == util::DiagnosticType::WARNING) { + if (errorType == util::DiagnosticType::WARNING || errorType == util::DiagnosticType::PLUGIN_WARNING) { return DiagnosticSeverity::Warning; } if (errorType == util::DiagnosticType::SYNTAX || errorType == util::DiagnosticType::SEMANTIC || - errorType == util::DiagnosticType::FATAL || errorType == util::DiagnosticType::ARKTS_CONFIG_ERROR) { + errorType == util::DiagnosticType::FATAL || errorType == util::DiagnosticType::ARKTS_CONFIG_ERROR || + errorType == util::DiagnosticType::PLUGIN_ERROR) { return DiagnosticSeverity::Error; } throw std::runtime_error("Unknown error type!"); } +// Temp design only support UI Plugin Diag. +int CreateCodeForDiagnostic(const util::DiagnosticBase *error) +{ + const int uiCode = 4000; + if (error->Type() == util::DiagnosticType::PLUGIN_ERROR || error->Type() == util::DiagnosticType::PLUGIN_WARNING) { + return uiCode; + } + return 1; +} + Diagnostic CreateDiagnosticForError(es2panda_Context *context, const util::DiagnosticBase &error) { auto ctx = reinterpret_cast(context); @@ -543,7 +554,7 @@ Diagnostic CreateDiagnosticForError(es2panda_Context *context, const util::Diagn auto range = Range(Position(sourceStartLocation.line, sourceStartLocation.col), Position(sourceEndLocation.line, sourceEndLocation.col)); auto severity = GetSeverity(error.Type()); - auto code = 1; + auto code = CreateCodeForDiagnostic(&error); std::string message = error.Message(); auto codeDescription = CodeDescription("test code description"); auto tags = std::vector(); diff --git a/ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp b/ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp new file mode 100644 index 0000000000..cb5f93b9dd --- /dev/null +++ b/ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp @@ -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. + */ + +#include "lsp/include/register_code_fix/ui_plugin_suggest.h" +#include +#include +#include "lsp/include/code_fix_provider.h" +#include "lsp/include/internal_api.h" + +namespace ark::es2panda::lsp { +const int G_UI_PLUGIN_SUGGEST_CODE = 4000; // change this to the error code you want to handle + +UIPluginSuggest::UIPluginSuggest() +{ + const char *uiPluginSuggestId = "UIPluginSuggest"; + SetErrorCodes({G_UI_PLUGIN_SUGGEST_CODE}); + SetFixIds({uiPluginSuggestId}); +} + +std::vector GetTextChangesFromSuggestions(const ark::es2panda::util::Diagnostic *diag, size_t pos, + bool isAll) +{ + std::vector textChanges; + if (!diag->HasSuggestions()) { + return textChanges; + } + for (auto suggestion : diag->Suggestion()) { + auto sourceStart = suggestion->SourceRange()->start.index; + auto sourceEnd = suggestion->SourceRange()->end.index; + auto span = TextSpan(sourceStart, sourceEnd); + if (isAll) { + textChanges.emplace_back(TextChange(span, suggestion->SubstitutionCode())); + } else if (pos >= sourceStart && pos <= sourceEnd) { + textChanges.emplace_back(TextChange(span, suggestion->SubstitutionCode())); + } + } + return textChanges; +} + +std::vector GetUIPluginCodeFixesByDiagType(public_lib::Context *ctx, size_t pos, + util::DiagnosticType type, bool isAll) +{ + auto filename = ctx->sourceFileName; + std::vector res; + const auto &diagnostics = ctx->diagnosticEngine->GetDiagnosticStorage(type); + auto diagnosticStorage = reinterpret_cast(&diagnostics); + // NOLINTNEXTLINE(modernize-loop-convert,-warnings-as-errors) + for (size_t i = 0; i < diagnosticStorage->size(); ++i) { + auto diag = reinterpret_cast(&(*(*diagnosticStorage)[i])); + auto textChanges = GetTextChangesFromSuggestions(diag, pos, isAll); + FileTextChanges fileTextChanges(filename, textChanges); + res.emplace_back(fileTextChanges); + } + return res; +} + +std::vector UIPluginSuggest::GetUIPluginCodeFixes(es2panda_Context *context, size_t pos, bool isAll) +{ + if (context == nullptr) { + return {}; + } + auto ctx = reinterpret_cast(context); + std::vector res; + auto errorFixes = GetUIPluginCodeFixesByDiagType(ctx, pos, util::DiagnosticType::PLUGIN_ERROR, isAll); + res.insert(res.end(), errorFixes.begin(), errorFixes.end()); + auto warningFixes = GetUIPluginCodeFixesByDiagType(ctx, pos, util::DiagnosticType::PLUGIN_WARNING, isAll); + res.insert(res.end(), warningFixes.begin(), warningFixes.end()); + return res; +} + +std::vector UIPluginSuggest::GetCodeActions(const CodeFixContext &context) +{ + std::vector returnedActions; + auto changes = GetUIPluginCodeFixes(context.context, context.span.start, false); + if (!changes.empty()) { + CodeFixAction codeAction; + codeAction.fixName = "Fix"; + codeAction.description = "Fix Description"; + codeAction.changes = changes; + codeAction.fixId = "UI_PLUGIN_SUGGEST"; + codeAction.fixAllDescription = "Fix All Description"; + InstallPackageAction codeActionCommand; + codeActionCommand.file = reinterpret_cast(context.context)->sourceFileName; + codeActionCommand.packageName = ""; + codeAction.commands.push_back(codeActionCommand); + returnedActions.push_back(codeAction); + } + return returnedActions; +} + +CombinedCodeActions UIPluginSuggest::GetAllCodeActions(const CodeFixAllContext &codeFixAll) +{ + CombinedCodeActions combinedCodeActions; + auto changes = GetUIPluginCodeFixes(codeFixAll.context, 0, true); + combinedCodeActions.changes = changes; + InstallPackageAction codeActionCommand; + codeActionCommand.file = reinterpret_cast(codeFixAll.context)->sourceFileName; + codeActionCommand.packageName = ""; + combinedCodeActions.commands.push_back(codeActionCommand); + + return combinedCodeActions; +} +// NOLINTNEXTLINE(fuchsia-statically-constructed-objects, cert-err58-cpp) +AutoCodeFixRegister g_uiPluginSuggest("UIPluginSuggest"); +} // namespace ark::es2panda::lsp diff --git a/ets2panda/test/unit/lsp/CMakeLists.txt b/ets2panda/test/unit/lsp/CMakeLists.txt index e50ecc4ac0..8314f1cb93 100644 --- a/ets2panda/test/unit/lsp/CMakeLists.txt +++ b/ets2panda/test/unit/lsp/CMakeLists.txt @@ -140,6 +140,10 @@ ets2panda_add_gtest(lsp_api_completions_test CPP_SOURCES get_completions.cpp ) +ets2panda_add_gtest(lsp_api_ui_suggest_test CPP_SOURCES + code_fix/ui_plugin_suggest.cpp +) + ets2panda_add_gtest(lsp_api_test_get_class_hierarchy_info CPP_SOURCES class_hierarchy_info_test.cpp ) diff --git a/ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp b/ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp new file mode 100644 index 0000000000..93c0d77ff8 --- /dev/null +++ b/ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp @@ -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. + */ + +#include "../lsp_api_test.h" + +#include + +#include "ir/astNode.h" +#include "lsp/include/register_code_fix/ui_plugin_suggest.h" +#include "lsp/include/internal_api.h" +#include "public/es2panda_lib.h" +#include "public/public.h" + +namespace { + +class LspUISuggestionTests : public LSPAPITests {}; + +using ark::es2panda::lsp::Initializer; + +void AssertDiagnosticContainsCodeAndMessage(const DiagnosticReferences &suggest, const int code, const char *dmessage) +{ + bool found = false; + for (auto diag : suggest.diagnostic) { + if (std::get(diag.code_) == code) { + if (diag.message_ == dmessage) { + found = true; + } + } + } + ASSERT_TRUE(found) << "Expected code: " << code << " not found"; +} + +TEST_F(LspUISuggestionTests, UIPluginsErrorTest1) +{ + using ark::es2panda::ir::AstNode; + using ark::es2panda::public_lib::Context; + Initializer initializer = Initializer(); + std::vector files = {"ui_error1.ets"}; + std::vector texts = {R"delimiter(function main() {})delimiter"}; + auto filePaths = CreateTempFile(files, texts); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + int const offset = 11; + // NOLINTNEXTLINE + const char *params[] = { + "a", + }; + const char *dmessage1 = "origin {}"; + const size_t argc1 = 1; + const char *substitutionCode = "replace b"; + const char *dmessage2 = "error"; + const size_t argc0 = 0; + const size_t index1 = 0; + const size_t line1 = 0; + const size_t index2 = 15; + const size_t line2 = 0; + const int code = 4000; + auto suggestionkind = initializer.CreateDiagnosticKind(ctx, dmessage1, ES2PANDA_PLUGIN_SUGGESTION); + auto suggestionInfo = initializer.CreateSuggestionInfo(ctx, suggestionkind, params, argc1, substitutionCode); + auto diagnostikind = initializer.CreateDiagnosticKind(ctx, dmessage2, ES2PANDA_PLUGIN_ERROR); + auto diagnosticInfo = initializer.CreateDiagnosticInfo(ctx, diagnostikind, nullptr, argc0); + es2panda_SourcePosition *left = initializer.CreateSourcePosition(ctx, index1, line1); + es2panda_SourcePosition *right = initializer.CreateSourcePosition(ctx, index2, line2); + es2panda_SourceRange *range = initializer.CreateSourceRange(ctx, left, right); + initializer.LogDiagnosticWithSuggestion(ctx, diagnosticInfo, suggestionInfo, range); + auto suggest = lspApi->getSyntacticDiagnostics(ctx); + AssertDiagnosticContainsCodeAndMessage(suggest, code, dmessage2); + auto result = ark::es2panda::lsp::UIPluginSuggest::GetUIPluginCodeFixes(ctx, offset, false); + ASSERT_EQ(result.at(0).textChanges.at(0).newText, substitutionCode); + std::vector codes; + codes.emplace_back(code); + CodeFixOptions emptyOptions; + auto fix = ark::es2panda::lsp::GetCodeFixesAtPositionImpl(ctx, index1, index2, codes, emptyOptions); + ASSERT_EQ(fix.at(0).changes_.at(0).textChanges.at(0).newText, substitutionCode); + + initializer.DestroyContext(ctx); +} + +TEST_F(LspUISuggestionTests, UIPluginsErrorTest2) +{ + using ark::es2panda::ir::AstNode; + using ark::es2panda::public_lib::Context; + Initializer initializer = Initializer(); + std::vector files = {"ui_error2.ets"}; + std::vector texts = {R"delimiter(function main() {})delimiter"}; + auto filePaths = CreateTempFile(files, texts); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + // NOLINTNEXTLINE + const char *params[] = { + "a", + }; + const size_t argc1 = 1; + const char *dmessage2 = "origin {}"; + const char *dmessage1 = "origin a"; + const size_t index1 = 0; + const size_t line1 = 0; + const int code = 4000; + auto diagnostikind = initializer.CreateDiagnosticKind(ctx, dmessage2, ES2PANDA_PLUGIN_ERROR); + es2panda_SourcePosition *left = initializer.CreateSourcePosition(ctx, index1, line1); + + initializer.LogDiagnostic(ctx, diagnostikind, params, argc1, left); + auto suggest = lspApi->getSyntacticDiagnostics(ctx); + AssertDiagnosticContainsCodeAndMessage(suggest, code, dmessage1); + std::vector codes; + codes.emplace_back(code); + CodeFixOptions emptyOptions; + auto fix = ark::es2panda::lsp::GetCodeFixesAtPositionImpl(ctx, index1, index1, codes, emptyOptions); + ASSERT_TRUE(fix.at(0).changes_.at(0).textChanges.empty()); + + initializer.DestroyContext(ctx); +} + +TEST_F(LspUISuggestionTests, UIPluginsErrorTest3) +{ + using ark::es2panda::ir::AstNode; + using ark::es2panda::public_lib::Context; + Initializer initializer = Initializer(); + std::vector files = {"ui_error3.ets"}; + std::vector texts = {R"delimiter(function main() {})delimiter"}; + auto filePaths = CreateTempFile(files, texts); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + const char *dmessage1 = "origin a"; + const char *substitutionCode = "replace b"; + const char *dmessage2 = "error"; + const size_t argc0 = 0; + const size_t index1 = 0; + const size_t line1 = 0; + const size_t index2 = 15; + const size_t line2 = 0; + const int code = 4000; + auto suggestionkind = initializer.CreateDiagnosticKind(ctx, dmessage1, ES2PANDA_PLUGIN_SUGGESTION); + auto suggestionInfo = initializer.CreateSuggestionInfo(ctx, suggestionkind, nullptr, argc0, substitutionCode); + auto diagnostikind = initializer.CreateDiagnosticKind(ctx, dmessage2, ES2PANDA_PLUGIN_ERROR); + auto diagnosticInfo = initializer.CreateDiagnosticInfo(ctx, diagnostikind, nullptr, argc0); + es2panda_SourcePosition *left = initializer.CreateSourcePosition(ctx, index1, line1); + es2panda_SourcePosition *right = initializer.CreateSourcePosition(ctx, index2, line2); + es2panda_SourceRange *range = initializer.CreateSourceRange(ctx, left, right); + initializer.LogDiagnosticWithSuggestion(ctx, diagnosticInfo, suggestionInfo, range); + + const char *substitutionCode2 = "replace c"; + auto suggestionkind2 = initializer.CreateDiagnosticKind(ctx, dmessage1, ES2PANDA_PLUGIN_SUGGESTION); + auto suggestionInfo2 = initializer.CreateSuggestionInfo(ctx, suggestionkind2, nullptr, argc0, substitutionCode2); + auto diagnostikind2 = initializer.CreateDiagnosticKind(ctx, dmessage2, ES2PANDA_PLUGIN_ERROR); + auto diagnosticInfo2 = initializer.CreateDiagnosticInfo(ctx, diagnostikind2, nullptr, argc0); + es2panda_SourcePosition *left2 = initializer.CreateSourcePosition(ctx, index1, line1); + es2panda_SourcePosition *right2 = initializer.CreateSourcePosition(ctx, index2, line2); + es2panda_SourceRange *range2 = initializer.CreateSourceRange(ctx, left2, right2); + initializer.LogDiagnosticWithSuggestion(ctx, diagnosticInfo2, suggestionInfo2, range2); + + auto suggest = lspApi->getSyntacticDiagnostics(ctx); + AssertDiagnosticContainsCodeAndMessage(suggest, code, dmessage2); + AssertDiagnosticContainsCodeAndMessage(suggest, code, dmessage2); + std::vector codes; + codes.emplace_back(code); + CodeFixOptions emptyOptions; + const std::string fixId = "UIPluginSuggest"; + auto fix = ark::es2panda::lsp::GetCodeFixesAtPositionImpl(ctx, index1, index1, codes, emptyOptions); + ASSERT_FALSE(fix.at(0).changes_.at(0).textChanges.empty()); + auto fixAll = ark::es2panda::lsp::GetCombinedCodeFixImpl(ctx, fixId, emptyOptions); + const size_t expectedCount = 2; + ASSERT_EQ(fixAll.changes_.size(), expectedCount); + + initializer.DestroyContext(ctx); +} + +} // namespace diff --git a/ets2panda/test/unit/lsp/code_fix_registration_test.cpp b/ets2panda/test/unit/lsp/code_fix_registration_test.cpp index c493453dba..edac3266f3 100644 --- a/ets2panda/test/unit/lsp/code_fix_registration_test.cpp +++ b/ets2panda/test/unit/lsp/code_fix_registration_test.cpp @@ -25,6 +25,5 @@ TEST(RefactorProviderRegistrationTest, RegistersConvertFunctionRefactor) const auto &fixIdToRegistration = provider.GetFixIdToRegistration(); EXPECT_FALSE(errors.empty()); EXPECT_FALSE(fixIdToRegistration.empty()); - EXPECT_EQ(errors.size(), 5); } } // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/get_diagnostics.cpp b/ets2panda/test/unit/lsp/get_diagnostics.cpp index bfb46178f1..2b89bade3d 100644 --- a/ets2panda/test/unit/lsp/get_diagnostics.cpp +++ b/ets2panda/test/unit/lsp/get_diagnostics.cpp @@ -61,7 +61,7 @@ add("1", 2);)"); ASSERT_EQ(result.diagnostic[thirdIndex].range_.end.line_, expectedFirstEndLine); ASSERT_EQ(result.diagnostic[thirdIndex].range_.end.character_, expectedFirstEndCharacter); ASSERT_EQ(result.diagnostic[thirdIndex].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[thirdIndex].code_), 1); + ASSERT_NE(std::get(result.diagnostic[thirdIndex].code_), 0); ASSERT_EQ(result.diagnostic[thirdIndex].message_, R"(Type '"hello"' cannot be assigned to type 'double')"); ASSERT_EQ(result.diagnostic[thirdIndex].codeDescription_.href_, "test code description"); auto const expectedSecondStartLine = 5; @@ -73,7 +73,7 @@ add("1", 2);)"); ASSERT_EQ(result.diagnostic[0].range_.end.line_, expectedSecondEndLine); ASSERT_EQ(result.diagnostic[0].range_.end.character_, expectedSecondEndCharacter); ASSERT_EQ(result.diagnostic[0].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[0].code_), 1); + ASSERT_NE(std::get(result.diagnostic[0].code_), 0); ASSERT_EQ(result.diagnostic[0].message_, R"(Type '"1"' is not compatible with type 'double' at index 1)"); ASSERT_EQ(result.diagnostic[0].codeDescription_.href_, "test code description"); } @@ -116,7 +116,7 @@ let res = add(n, n);)"); ASSERT_EQ(result.diagnostic[0].range_.end.line_, expectedFirstEndLine); ASSERT_EQ(result.diagnostic[0].range_.end.character_, expectedFirstEndCharacter); ASSERT_EQ(result.diagnostic[0].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[0].code_), 1); + ASSERT_NE(std::get(result.diagnostic[0].code_), 0); auto const expectedSecondStartLine = 1; auto const expectedSecondStartCharacter = 14; auto const expectedSecondEndLine = 1; @@ -126,7 +126,7 @@ let res = add(n, n);)"); ASSERT_EQ(result.diagnostic[1].range_.end.line_, expectedSecondEndLine); ASSERT_EQ(result.diagnostic[1].range_.end.character_, expectedSecondEndCharacter); ASSERT_EQ(result.diagnostic[1].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[1].code_), 1); + ASSERT_NE(std::get(result.diagnostic[1].code_), 0); auto const thirdIndex = 2; auto const expectedThirdStartLine = 1; auto const expectedThirdStartCharacter = 14; @@ -137,7 +137,7 @@ let res = add(n, n);)"); ASSERT_EQ(result.diagnostic[thirdIndex].range_.end.line_, expectedThirdEndLine); ASSERT_EQ(result.diagnostic[thirdIndex].range_.end.character_, expectedThirdEndCharacter); ASSERT_EQ(result.diagnostic[thirdIndex].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[thirdIndex].code_), 1); + ASSERT_NE(std::get(result.diagnostic[thirdIndex].code_), 0); ASSERT_EQ(result.diagnostic[thirdIndex].message_, R"(Unexpected token ':'.)"); } @@ -163,7 +163,7 @@ let res = add(n, n);)"); ASSERT_EQ(result.diagnostic[forthIndex].range_.end.line_, expectedForthEndLine); ASSERT_EQ(result.diagnostic[forthIndex].range_.end.character_, expectedForthEndCharacter); ASSERT_EQ(result.diagnostic[forthIndex].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[forthIndex].code_), 1); + ASSERT_NE(std::get(result.diagnostic[forthIndex].code_), 0); ASSERT_EQ(result.diagnostic[forthIndex].message_, R"(Unexpected token ','.)"); ASSERT_EQ(result.diagnostic[forthIndex].codeDescription_.href_, "test code description"); auto const fifthIndex = 8; @@ -176,7 +176,7 @@ let res = add(n, n);)"); ASSERT_EQ(result.diagnostic[fifthIndex].range_.end.line_, expectedFifthEndLine); ASSERT_EQ(result.diagnostic[fifthIndex].range_.end.character_, expectedFifthEndCharacter); ASSERT_EQ(result.diagnostic[fifthIndex].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[fifthIndex].code_), 1); + ASSERT_NE(std::get(result.diagnostic[fifthIndex].code_), 0); ASSERT_EQ(result.diagnostic[fifthIndex].message_, R"(Label must be followed by a loop statement.)"); ASSERT_EQ(result.diagnostic[fifthIndex].codeDescription_.href_, "test code description"); } @@ -203,7 +203,7 @@ let res = add(n, n);)"); ASSERT_EQ(result.diagnostic[sixthIndex].range_.end.line_, expectedSixthEndLine); ASSERT_EQ(result.diagnostic[sixthIndex].range_.end.character_, expectedSixthEndCharacter); ASSERT_EQ(result.diagnostic[sixthIndex].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[sixthIndex].code_), 1); + ASSERT_NE(std::get(result.diagnostic[sixthIndex].code_), 0); ASSERT_EQ(result.diagnostic[sixthIndex].message_, R"(Unexpected token ')'.)"); ASSERT_EQ(result.diagnostic[sixthIndex].codeDescription_.href_, "test code description"); auto const sevenIndex = 12; @@ -216,7 +216,7 @@ let res = add(n, n);)"); ASSERT_EQ(result.diagnostic[sevenIndex].range_.end.line_, expectedSeventhEndLine); ASSERT_EQ(result.diagnostic[sevenIndex].range_.end.character_, expectedSeventhEndCharacter); ASSERT_EQ(result.diagnostic[sevenIndex].severity_, DiagnosticSeverity::Error); - ASSERT_EQ(std::get(result.diagnostic[sevenIndex].code_), 1); + ASSERT_NE(std::get(result.diagnostic[sevenIndex].code_), 0); ASSERT_EQ(result.diagnostic[sevenIndex].message_, R"(return keyword should be used in function body.)"); ASSERT_EQ(result.diagnostic[sevenIndex].codeDescription_.href_, "test code description"); } diff --git a/ets2panda/util/diagnostic.h b/ets2panda/util/diagnostic.h index cb4c70a256..a3d9bf4d19 100644 --- a/ets2panda/util/diagnostic.h +++ b/ets2panda/util/diagnostic.h @@ -220,6 +220,11 @@ public: DiagnosticType Type() const override; std::string Message() const override; + bool HasSuggestions() const + { + return suggestions_ != nullptr; + } + const std::vector &Suggestion() const { return *suggestions_; -- Gitee From e0b0a32eb18f5ea8f3844181ea2419521096b7ae Mon Sep 17 00:00:00 2001 From: leo9001 Date: Wed, 11 Jun 2025 15:41:45 +0800 Subject: [PATCH 057/145] support GetClassHierarchyInfo support GetClassHierarchyInfo Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICD5N1 Signed-off-by: leo9001 --- ets2panda/bindings/native/src/lsp.cpp | 39 +++- .../bindings/src/Es2pandaNativeModule.ts | 12 +- ets2panda/bindings/src/lspNode.ts | 45 +++- ets2panda/lsp/include/class_hierarchy_info.h | 139 ++++++------ ets2panda/lsp/include/class_hierarchy_item.h | 135 ++++++++++++ ets2panda/lsp/include/internal_api.h | 2 +- ets2panda/lsp/src/class_hierarchy_info.cpp | 169 +++++++++++---- ets2panda/lsp/src/completions.cpp | 14 +- .../unit/lsp/class_hierarchy_info_test.cpp | 199 ++++++++++++++++-- 9 files changed, 588 insertions(+), 166 deletions(-) create mode 100644 ets2panda/lsp/include/class_hierarchy_item.h diff --git a/ets2panda/bindings/native/src/lsp.cpp b/ets2panda/bindings/native/src/lsp.cpp index f8f6c9c669..5a620cfed4 100644 --- a/ets2panda/bindings/native/src/lsp.cpp +++ b/ets2panda/bindings/native/src/lsp.cpp @@ -28,7 +28,9 @@ namespace { using ark::es2panda::lsp::ClassHierarchy; using ark::es2panda::lsp::ClassHierarchyInfo; +using ark::es2panda::lsp::ClassHierarchyItem; using ark::es2panda::lsp::ClassMethodItem; +using ark::es2panda::lsp::ClassPropertyItem; } // namespace char *GetStringCopy(KStringPtr &ptr) @@ -722,14 +724,14 @@ KNativePointer impl_getClassNameFromClassHierarchyInfo(KNativePointer info) } TS_INTEROP_1(getClassNameFromClassHierarchyInfo, KNativePointer, KNativePointer) -KNativePointer impl_getMethodListFromClassHierarchyInfo(KNativePointer info) +KNativePointer impl_getMethodItemsFromClassHierarchyInfo(KNativePointer info) { auto *infoPtr = reinterpret_cast(info); if (infoPtr == nullptr) { return nullptr; } std::vector ptrs; - for (const auto &element : infoPtr->GetMethodList()) { + for (const auto &element : infoPtr->GetMethodItemList()) { if (element.second == nullptr) { continue; } @@ -737,17 +739,34 @@ KNativePointer impl_getMethodListFromClassHierarchyInfo(KNativePointer info) } return new std::vector(ptrs); } -TS_INTEROP_1(getMethodListFromClassHierarchyInfo, KNativePointer, KNativePointer) +TS_INTEROP_1(getMethodItemsFromClassHierarchyInfo, KNativePointer, KNativePointer) -KNativePointer impl_getDetailFromClassMethodItem(KNativePointer item) +KNativePointer impl_getPropertyItemsFromClassHierarchyInfo(KNativePointer info) { - auto *itemPtr = reinterpret_cast(item); + auto *infoPtr = reinterpret_cast(info); + if (infoPtr == nullptr) { + return nullptr; + } + std::vector ptrs; + for (const auto &element : infoPtr->GetPropertyItemList()) { + if (element.second == nullptr) { + continue; + } + ptrs.push_back(new ClassPropertyItem(*(element.second))); + } + return new std::vector(ptrs); +} +TS_INTEROP_1(getPropertyItemsFromClassHierarchyInfo, KNativePointer, KNativePointer) + +KNativePointer impl_getDetailFromClassHierarchyItem(KNativePointer item) +{ + auto *itemPtr = reinterpret_cast(item); if (itemPtr == nullptr) { return nullptr; } - return new std::string(itemPtr->GetFunctionDetail()); + return new std::string(itemPtr->GetDetail()); } -TS_INTEROP_1(getDetailFromClassMethodItem, KNativePointer, KNativePointer) +TS_INTEROP_1(getDetailFromClassHierarchyItem, KNativePointer, KNativePointer) KInt impl_getSetterStyleFromClassMethodItem(KNativePointer item) { @@ -759,15 +778,15 @@ KInt impl_getSetterStyleFromClassMethodItem(KNativePointer item) } TS_INTEROP_1(getSetterStyleFromClassMethodItem, KInt, KNativePointer) -KInt impl_getAccessModifierStyleFromClassMethodItem(KNativePointer item) +KInt impl_getAccessModifierStyleFromClassHierarchyItem(KNativePointer item) { - auto *itemPtr = reinterpret_cast(item); + auto *itemPtr = reinterpret_cast(item); if (itemPtr == nullptr) { return 0; } return static_cast(itemPtr->GetAccessModifierStyle()); } -TS_INTEROP_1(getAccessModifierStyleFromClassMethodItem, KInt, KNativePointer) +TS_INTEROP_1(getAccessModifierStyleFromClassHierarchyItem, KInt, KNativePointer) KInt impl_getAliasScriptElementKind(KNativePointer context, KInt position) { diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts index effe426fb7..c566f93d8f 100644 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/Es2pandaNativeModule.ts @@ -209,19 +209,23 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } - _getMethodListFromClassHierarchyInfo(ptr: KNativePointer): KPtr { + _getMethodItemsFromClassHierarchyInfo(ptr: KNativePointer): KPtr { throw new Error('Not implemented'); } - _getDetailFromClassMethodItem(ptr: KNativePointer): KPtr { + _getPropertyItemsFromClassHierarchyInfo(ptr: KNativePointer): KPtr { throw new Error('Not implemented'); } - _getSetterStyleFromClassMethodItem(ptr: KNativePointer): KInt { + _getDetailFromClassHierarchyItem(ptr: KNativePointer): KPtr { throw new Error('Not implemented'); } - _getAccessModifierStyleFromClassMethodItem(ptr: KNativePointer): KInt { + _getAccessModifierStyleFromClassHierarchyItem(ptr: KNativePointer): KInt { + throw new Error('Not implemented'); + } + + _getSetterStyleFromClassMethodItem(ptr: KNativePointer): KInt { throw new Error('Not implemented'); } diff --git a/ets2panda/bindings/src/lspNode.ts b/ets2panda/bindings/src/lspNode.ts index 5f305aa2d6..52eadf417f 100644 --- a/ets2panda/bindings/src/lspNode.ts +++ b/ets2panda/bindings/src/lspNode.ts @@ -23,7 +23,7 @@ import { NativePtrDecoder } from './Platform'; enum HierarchyType { OTHERS, INTERFACE, CLASS }; export enum SetterStyle { - METHOD = 0, + NONE = 0, SETTER, GETTER } @@ -36,6 +36,11 @@ export enum AccessModifierStyle { enum ClassRelationKind { UNKNOWN, INTERFACE, CLASS, FIELD, METHOD, PROPERTY }; +export enum ClassDefinitionStyle { + FIELD = 0, + METHOD +} + export abstract class LspNode { readonly peer: KNativePointer; @@ -228,30 +233,50 @@ export class LspSymbolDisplayPart extends LspNode { readonly kind: String; } -export class LspClassMethodItem extends LspNode { - constructor(peer: KNativePointer) { +export class LspClassHierarchyItem extends LspNode { + constructor(peer: KNativePointer, style: ClassDefinitionStyle) { super(peer); - this.functionDetail = unpackString(global.es2panda._getDetailFromClassMethodItem(this.peer)); + this.style = style; + this.detail = unpackString(global.es2panda._getDetailFromClassHierarchyItem(this.peer)); + this.accessModifier = global.es2panda._getAccessModifierStyleFromClassHierarchyItem(this.peer); + } + readonly detail: string; + readonly accessModifier: AccessModifierStyle; + readonly style: ClassDefinitionStyle; +} + +export class LspClassMethodItem extends LspClassHierarchyItem { + constructor(peer: KNativePointer) { + super(peer, ClassDefinitionStyle.METHOD); this.setter = global.es2panda._getSetterStyleFromClassMethodItem(this.peer); - this.accessModifier = global.es2panda._getAccessModifierStyleFromClassMethodItem(this.peer); } - readonly functionDetail: string; readonly setter: SetterStyle; - readonly accessModifier: AccessModifierStyle; +} + +export class LspClassPropertyItem extends LspClassHierarchyItem { + constructor(peer: KNativePointer) { + super(peer, ClassDefinitionStyle.FIELD); + } } export class LspClassHierarchyInfo extends LspNode { constructor(peer: KNativePointer) { super(peer); this.className = unpackString(global.es2panda._getClassNameFromClassHierarchyInfo(this.peer)); - this.items = new NativePtrDecoder() - .decode(global.es2panda._getMethodListFromClassHierarchyInfo(this.peer)) + this.methodItems = new NativePtrDecoder() + .decode(global.es2panda._getMethodItemsFromClassHierarchyInfo(this.peer)) .map((elPeer: KNativePointer) => { return new LspClassMethodItem(elPeer); }); + this.fieldItems = new NativePtrDecoder() + .decode(global.es2panda._getPropertyItemsFromClassHierarchyInfo(this.peer)) + .map((elPeer: KNativePointer) => { + return new LspClassPropertyItem(elPeer); + }); } readonly className: string; - readonly items: LspClassMethodItem[]; + readonly methodItems: LspClassMethodItem[]; + readonly fieldItems: LspClassPropertyItem[]; } export class LspClassHierarchy extends LspNode { diff --git a/ets2panda/lsp/include/class_hierarchy_info.h b/ets2panda/lsp/include/class_hierarchy_info.h index f7730151ed..8ff110fa20 100644 --- a/ets2panda/lsp/include/class_hierarchy_info.h +++ b/ets2panda/lsp/include/class_hierarchy_info.h @@ -17,9 +17,9 @@ #define ES2PANDA_LSP_CLASS_HIERARCHY_INFO_H #include -#include #include #include +#include "class_hierarchy_item.h" #include "public/es2panda_lib.h" namespace ark::es2panda::lsp { @@ -45,59 +45,6 @@ private: std::string kind_; }; -enum class SetterStyle { METHOD = 0, SETTER, GETTER }; - -enum class AccessModifierStyle { PUBLIC = 0, PROTECTED, PRIVATE }; - -class ClassMethodItem { -public: - ClassMethodItem(std::string detail, SetterStyle setter, AccessModifierStyle access) - : detail_(std::move(detail)), setter_(setter), accessModifier_(access) - { - } - - virtual ~ClassMethodItem() = default; - - ClassMethodItem(const ClassMethodItem &other) = default; - ClassMethodItem(ClassMethodItem &&other) = default; - ClassMethodItem &operator=(const ClassMethodItem &other) = default; - ClassMethodItem &operator=(ClassMethodItem &&other) = default; - - void SetFunctionName(const std::string &functionName) - { - if (functionName.empty()) { - return; - } - funcName_ = functionName; - } - - const std::string &GetFunctionName() const - { - return funcName_; - } - - const std::string &GetFunctionDetail() const - { - return detail_; - } - - SetterStyle GetSetterStyle() const - { - return setter_; - } - - AccessModifierStyle GetAccessModifierStyle() const - { - return accessModifier_; - } - -private: - std::string funcName_; - std::string detail_; - SetterStyle setter_; - AccessModifierStyle accessModifier_; -}; - class ClassHierarchyInfo { public: ClassHierarchyInfo() = default; @@ -122,58 +69,98 @@ public: return className_; } - const std::unordered_map> &GetMethodList() const + const std::unordered_map> &GetMethodItemList() const + { + return methodItems_; + } + + const std::unordered_map> &GetPropertyItemList() const + { + return propertyItems_; + } + + bool AddItemToMethodList(const std::shared_ptr &item) { - return methods_; + if (item == nullptr) { + return false; + } + auto detail = item->GetDetail(); + auto result = methodItems_.try_emplace(detail, item); + return result.second; } - bool AddClassMethodItem(const std::shared_ptr &item) + bool AddItemToPropertyList(const std::shared_ptr &item) { - if (item == nullptr || IsItemExist(item)) { + if (item == nullptr) { return false; } - auto funcDetail = item->GetFunctionDetail(); - methods_[funcDetail] = item; - return true; + auto detail = item->GetDetail(); + auto result = propertyItems_.try_emplace(detail, item); + return result.second; } - void DeleteClassMethodItem(const std::shared_ptr &item) + void DeleteTargetItemInMethodList(const std::shared_ptr &item) { if (item == nullptr) { return; } - auto funcDetail = item->GetFunctionDetail(); - methods_.erase(funcDetail); + auto detail = item->GetDetail(); + methodItems_.erase(detail); } - void DeleteAllClassMethodItem() + void DeleteTargetItemInPropertyList(const std::shared_ptr &item) { - methods_.clear(); + if (item == nullptr) { + return; + } + auto detail = item->GetDetail(); + propertyItems_.erase(detail); } - bool IsItemExist(const std::shared_ptr &item) const + void DeleteAllItemsInMethodList() + { + methodItems_.clear(); + } + + void DeleteAllItemsInPropertyList() + { + propertyItems_.clear(); + } + + bool IsItemExistInMethodList(const std::shared_ptr &item) const { if (item == nullptr) { return false; } - auto func = item->GetFunctionDetail(); - auto iter = methods_.find(func); - return iter != methods_.end(); + auto detail = item->GetDetail(); + auto iter = methodItems_.find(detail); + return iter != methodItems_.end(); + } + + bool IsItemExistInPropertyList(const std::shared_ptr &item) const + { + if (item == nullptr) { + return false; + } + auto detail = item->GetDetail(); + auto iter = propertyItems_.find(detail); + return iter != propertyItems_.end(); } private: std::string className_; - std::unordered_map> methods_; + std::unordered_map> methodItems_; + std::unordered_map> propertyItems_; }; using ClassHierarchy = std::vector; /** - * Retrieve the list of undefined virtual functions in the parent class. + * Retrieve the list of undefined virtual functions and properties in the parent class. * * such as ets: * class Animal { - * private body_: string = ''; + * public body_: string = ''; * * public action(): void { * console.log("need Animal action"); @@ -192,9 +179,9 @@ using ClassHierarchy = std::vector; * console.log("need Bird Drink"); * } * } - * - * when clicking 'Bird'. - * ClassHierarchy is [ { "Animal", { detail: sleep(), SetterStyle: METHOD, AccessModifierStyle: PUBLIC } } ]. + * when clicking 'Bird'. ClassHierarchy is : + * [ { "Animal", { detail: body_: string, ClassDefinitionStyle FIELD, AccessModifierStyle: PUBLIC } }, + * { "Animal", { detail: sleep(): void, ClassDefinitionStyle: METHOD, AccessModifierStyle: PUBLIC } } ]. */ ClassHierarchy GetClassHierarchyInfoImpl(es2panda_Context *context, size_t position); } // namespace ark::es2panda::lsp diff --git a/ets2panda/lsp/include/class_hierarchy_item.h b/ets2panda/lsp/include/class_hierarchy_item.h new file mode 100644 index 0000000000..a2d6789aa7 --- /dev/null +++ b/ets2panda/lsp/include/class_hierarchy_item.h @@ -0,0 +1,135 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_LSP_CLASS_HIERARCHY_ITEM_H +#define ES2PANDA_LSP_CLASS_HIERARCHY_ITEM_H + +#include + +namespace ark::es2panda::lsp { +enum class SetterStyle { NONE = 0, SETTER, GETTER }; + +enum class AccessModifierStyle { PUBLIC = 0, PROTECTED, PRIVATE }; + +enum class ClassDefinitionStyle { FIELD = 0, METHOD }; + +class ClassHierarchyItem { +public: + ClassHierarchyItem(AccessModifierStyle access, std::string detail) + : accessModifier_(access), detail_(std::move(detail)) + { + } + + virtual ~ClassHierarchyItem() = default; + + ClassHierarchyItem(const ClassHierarchyItem &other) = default; + ClassHierarchyItem(ClassHierarchyItem &&other) = default; + ClassHierarchyItem &operator=(const ClassHierarchyItem &other) = default; + ClassHierarchyItem &operator=(ClassHierarchyItem &&other) = default; + + virtual ClassDefinitionStyle GetClassDefinitionStyle() const = 0; + + AccessModifierStyle GetAccessModifierStyle() const + { + return accessModifier_; + } + + const std::string &GetDetail() const + { + return detail_; + } + +private: + AccessModifierStyle accessModifier_; + std::string detail_; +}; + +class ClassPropertyItem : public ClassHierarchyItem { +public: + ClassPropertyItem(AccessModifierStyle access, std::string detail) : ClassHierarchyItem(access, std::move(detail)) {} + + ~ClassPropertyItem() override = default; + + ClassPropertyItem(const ClassPropertyItem &other) = default; + ClassPropertyItem(ClassPropertyItem &&other) = default; + ClassPropertyItem &operator=(const ClassPropertyItem &other) = default; + ClassPropertyItem &operator=(ClassPropertyItem &&other) = default; + + ClassDefinitionStyle GetClassDefinitionStyle() const override + { + return ClassDefinitionStyle::FIELD; + } + + void SetVariableName(const std::string &variableName) + { + if (variableName.empty()) { + return; + } + variableName_ = variableName; + } + + const std::string &GetVariableName() const + { + return variableName_; + } + +private: + std::string variableName_; +}; + +class ClassMethodItem : public ClassHierarchyItem { +public: + ClassMethodItem(AccessModifierStyle access, std::string detail, SetterStyle setter) + : ClassHierarchyItem(access, std::move(detail)), setter_(setter) + { + } + + ~ClassMethodItem() override = default; + + ClassMethodItem(const ClassMethodItem &other) = default; + ClassMethodItem(ClassMethodItem &&other) = default; + ClassMethodItem &operator=(const ClassMethodItem &other) = default; + ClassMethodItem &operator=(ClassMethodItem &&other) = default; + + ClassDefinitionStyle GetClassDefinitionStyle() const override + { + return ClassDefinitionStyle::METHOD; + } + + void SetFunctionName(const std::string &functionName) + { + if (functionName.empty()) { + return; + } + funcName_ = functionName; + } + + const std::string &GetFunctionName() const + { + return funcName_; + } + + SetterStyle GetSetterStyle() const + { + return setter_; + } + +private: + std::string funcName_; + SetterStyle setter_; +}; +} // namespace ark::es2panda::lsp + +#endif diff --git a/ets2panda/lsp/include/internal_api.h b/ets2panda/lsp/include/internal_api.h index b021c901da..03fa2abb1b 100644 --- a/ets2panda/lsp/include/internal_api.h +++ b/ets2panda/lsp/include/internal_api.h @@ -134,7 +134,7 @@ std::vector GetCodeFixesAtPositionImpl(es2panda_Context *cont CodeFixOptions &codeFixOptions); CombinedCodeActionsInfo GetCombinedCodeFixImpl(es2panda_Context *context, const std::string &fixId, CodeFixOptions &codeFixOptions); - +ir::Identifier *GetIdentFromNewClassExprPart(const ir::Expression *value); } // namespace ark::es2panda::lsp #endif \ No newline at end of file diff --git a/ets2panda/lsp/src/class_hierarchy_info.cpp b/ets2panda/lsp/src/class_hierarchy_info.cpp index 6534cd30d9..94aa7c9c7a 100644 --- a/ets2panda/lsp/src/class_hierarchy_info.cpp +++ b/ets2panda/lsp/src/class_hierarchy_info.cpp @@ -17,6 +17,7 @@ #include "internal_api.h" #include "public/public.h" #include "compiler/lowering/util.h" +#include "quick_info.h" namespace ark::es2panda::lsp { std::string GetNameFromIdentifierNode(const ir::AstNode *node) @@ -24,7 +25,7 @@ std::string GetNameFromIdentifierNode(const ir::AstNode *node) if (node == nullptr || !node->IsIdentifier()) { return ""; } - return std::string(node->AsIdentifier()->Name()); + return node->AsIdentifier()->ToString(); } // Currently only considering enum scenarios. @@ -77,9 +78,17 @@ std::string SpliceFunctionDetailStr(const std::string &functionName, const std:: return result; } +std::string SplicePropertyDetailStr(const std::string &name, const std::string &type) +{ + if (name.empty() || type.empty()) { + return ""; + } + return name + ": " + type; +} + std::string GetFunctionNameFromScriptFunction(const ir::ScriptFunction *function) { - if (function == nullptr) { + if (function == nullptr || function->Id() == nullptr) { return ""; } return function->Id()->ToString(); @@ -92,21 +101,23 @@ std::vector GetParamListFromScriptFunction(const ir::ScriptF return params; } auto nodeParams = function->Params(); - for (const auto &nodeParam : nodeParams) { + for (const auto *it : nodeParams) { + if (it == nullptr || !it->IsETSParameterExpression()) { + continue; + } std::string paramName; std::string paramKind; - if (!nodeParam->IsETSParameterExpression()) { + auto nodeParam = it->AsETSParameterExpression(); + if (nodeParam->IsRestParameter()) { + paramName = nodeParam->RestParameter()->ToString(); + } else { + paramName = GetNameFromIdentifierNode(nodeParam->Ident()); + } + if (paramName == INVALID_EXPRESSION || nodeParam->TypeAnnotation() == nullptr) { continue; } - paramName = std::string(nodeParam->AsETSParameterExpression()->Name()); - nodeParam->AsETSParameterExpression()->FindChild([¶mKind](ir::AstNode *childNode) { - if (childNode->IsETSTypeReference()) { - paramKind = childNode->AsETSTypeReference()->Part()->Name()->ToString(); - } - return false; - }); - FunctionParamStyle tmp(paramName, paramKind); - params.emplace_back(std::move(tmp)); + paramKind = GetNameForTypeNode(nodeParam->TypeAnnotation()); + params.emplace_back(FunctionParamStyle(std::move(paramName), std::move(paramKind))); } return params; } @@ -116,20 +127,17 @@ std::string GetReturnTypeFromScriptFunction(const ir::ScriptFunction *function) if (function == nullptr) { return ""; } - auto nodeReturn = function->ReturnTypeAnnotation(); - if (nodeReturn == nullptr || !nodeReturn->IsETSTypeReference()) { + auto returnNode = function->ReturnTypeAnnotation(); + if (returnNode == nullptr) { return ""; } - auto ident = nodeReturn->AsETSTypeReference()->Part()->Name(); - if (ident == nullptr || !ident->IsIdentifier()) { - return ""; - } - return std::string(ident->AsIdentifier()->Name()); + auto returnType = GetNameForTypeNode(returnNode); + return returnType; } SetterStyle CreateSetterStyle(ir::MethodDefinitionKind kind) { - SetterStyle setter = SetterStyle::METHOD; + SetterStyle setter = SetterStyle::NONE; switch (kind) { case ir::MethodDefinitionKind::GET: case ir::MethodDefinitionKind::EXTENSION_GET: @@ -151,17 +159,31 @@ std::shared_ptr CreateClassMethodItem(const ir::MethodDefinitio if (methodDefinition == nullptr || funcName.empty() || detail.empty()) { return nullptr; } - auto setter = CreateSetterStyle(methodDefinition->Kind()); AccessModifierStyle access = AccessModifierStyle::PUBLIC; if (methodDefinition->IsProtected()) { access = AccessModifierStyle::PROTECTED; } - auto item = std::make_shared(std::move(detail), setter, access); + auto item = std::make_shared(access, std::move(detail), setter); item->SetFunctionName(funcName); return item; } +std::shared_ptr CreateClassPropertyItem(const ir::ClassProperty *property, + const std::string &propertyName, std::string detail) +{ + if (property == nullptr || propertyName.empty() || detail.empty()) { + return nullptr; + } + AccessModifierStyle access = AccessModifierStyle::PUBLIC; + if (property->IsProtected()) { + access = AccessModifierStyle::PROTECTED; + } + auto item = std::make_shared(access, std::move(detail)); + item->SetVariableName(propertyName); + return item; +} + std::shared_ptr ParseFunctionStyleWithCreateItem(const ir::MethodDefinition *methodDefinition, bool isCurrentToken) { @@ -184,6 +206,48 @@ std::shared_ptr ParseFunctionStyleWithCreateItem(const ir::Meth return CreateClassMethodItem(methodDefinition, functionName, functionDetail); } +ir::Identifier *GetIdentFromNewClassExprPart(const ir::Expression *value) +{ + if (value == nullptr || !value->IsETSNewClassInstanceExpression()) { + return nullptr; + } + auto typeRef = value->AsETSNewClassInstanceExpression()->GetTypeRef(); + if (typeRef == nullptr || !typeRef->IsETSTypeReference()) { + return nullptr; + } + auto part = typeRef->AsETSTypeReference()->Part(); + if (part == nullptr) { + return nullptr; + } + return part->GetIdent(); +} + +std::shared_ptr ParsePropertyStyleWithCreateItem(const ir::ClassProperty *property, + bool isCurrentToken) +{ + if (property == nullptr) { + return nullptr; + } + if ((isCurrentToken && property->IsStatic()) || + (!isCurrentToken && (property->IsPrivate() || property->IsStatic()))) { + return nullptr; + } + std::string propertyName = GetNameFromIdentifierNode(property->Key()); + std::string type; + if (property->TypeAnnotation() == nullptr) { + auto value = property->Value(); + auto ident = GetIdentFromNewClassExprPart(value); + type = GetNameFromIdentifierNode(ident); + } else { + type = GetNameForTypeNode(property->TypeAnnotation()); + } + if (propertyName == INVALID_EXPRESSION || type == INVALID_EXPRESSION) { + return nullptr; + } + auto detail = SplicePropertyDetailStr(propertyName, type); + return CreateClassPropertyItem(property, propertyName, detail); +} + ClassHierarchyInfo CreateClassHierarchyInfoFromBody(const ir::ClassDefinition *classDefinition, const std::string &className, bool isCurrentToken) { @@ -194,23 +258,28 @@ ClassHierarchyInfo CreateClassHierarchyInfoFromBody(const ir::ClassDefinition *c result.SetClassName(className); auto bodyNodes = classDefinition->Body(); for (const auto &node : bodyNodes) { - if (node == nullptr || !node->IsMethodDefinition()) { - continue; - } - auto methodDefinition = node->AsMethodDefinition(); - if (methodDefinition == nullptr) { + if (node == nullptr) { continue; } - auto item = ParseFunctionStyleWithCreateItem(methodDefinition, isCurrentToken); - if (item != nullptr) { - result.AddClassMethodItem(item); - } - auto overLoads = methodDefinition->Overloads(); - for (const auto *overLoadMethodDefinition : overLoads) { - auto overLoadItem = ParseFunctionStyleWithCreateItem(overLoadMethodDefinition, isCurrentToken); - if (overLoadItem != nullptr) { - result.AddClassMethodItem(overLoadItem); + if (node->IsMethodDefinition()) { + auto methodDefinition = node->AsMethodDefinition(); + if (methodDefinition == nullptr) { + continue; + } + auto item = ParseFunctionStyleWithCreateItem(methodDefinition, isCurrentToken); + result.AddItemToMethodList(item); + auto overLoads = methodDefinition->Overloads(); + for (const auto *overLoadMethodDefinition : overLoads) { + auto overLoadItem = ParseFunctionStyleWithCreateItem(overLoadMethodDefinition, isCurrentToken); + result.AddItemToMethodList(overLoadItem); + } + } else if (node->IsClassProperty()) { + auto property = node->AsClassProperty(); + if (property == nullptr) { + continue; } + auto item = ParsePropertyStyleWithCreateItem(property, isCurrentToken); + result.AddItemToPropertyList(item); } } return result; @@ -230,13 +299,29 @@ ir::AstNode *GetSuperClassNode(const ir::ClassDefinition *classDefinition) void ComputeClassHierarchyInfo(const ClassHierarchyInfo &deriveInfo, ClassHierarchyInfo &superInfo) { - auto deriveMethods = deriveInfo.GetMethodList(); + auto deriveMethods = deriveInfo.GetMethodItemList(); for (const auto &method : deriveMethods) { - superInfo.DeleteClassMethodItem(method.second); + superInfo.DeleteTargetItemInMethodList(method.second); + } + auto deriveProperties = deriveInfo.GetPropertyItemList(); + for (const auto &property : deriveProperties) { + superInfo.DeleteTargetItemInPropertyList(property.second); + } +} + +void FillBaseClassHierarchyInfo(const ClassHierarchyInfo &extraInfo, ClassHierarchyInfo &baseInfo) +{ + auto extraMethods = extraInfo.GetMethodItemList(); + for (const auto &method : extraMethods) { + baseInfo.AddItemToMethodList(method.second); + } + auto extraProperties = extraInfo.GetPropertyItemList(); + for (const auto &property : extraProperties) { + baseInfo.AddItemToPropertyList(property.second); } } -void ProcessClassHierarchy(const ir::AstNode *token, const ClassHierarchyInfo &baseInfo, ClassHierarchy &result) +void ProcessClassHierarchy(const ir::AstNode *token, ClassHierarchyInfo &baseInfo, ClassHierarchy &result) { if (token == nullptr || !token->IsIdentifier()) { return; @@ -250,8 +335,10 @@ void ProcessClassHierarchy(const ir::AstNode *token, const ClassHierarchyInfo &b if (!className.empty()) { // Calculate the difference between the obtained parent class info and the current clicked node class info. ComputeClassHierarchyInfo(baseInfo, info); - if (info.GetClassName() == className && !info.GetMethodList().empty()) { + if (info.GetClassName() == className && + (!info.GetMethodItemList().empty() || !info.GetPropertyItemList().empty())) { result.emplace_back(info); + FillBaseClassHierarchyInfo(info, baseInfo); } } auto superClass = GetSuperClassNode(classDefinition); diff --git a/ets2panda/lsp/src/completions.cpp b/ets2panda/lsp/src/completions.cpp index cc8bda9324..8b1961ff2f 100644 --- a/ets2panda/lsp/src/completions.cpp +++ b/ets2panda/lsp/src/completions.cpp @@ -303,17 +303,9 @@ ir::AstNode *GetClassDefinitionFromClassProperty(ir::AstNode *node) return nullptr; } auto value = node->AsClassProperty()->Value(); - if (value != nullptr && value->IsETSNewClassInstanceExpression() && - value->AsETSNewClassInstanceExpression()->GetTypeRef() != nullptr && - value->AsETSNewClassInstanceExpression()->GetTypeRef()->IsETSTypeReference()) { - auto typeReferencePart = value->AsETSNewClassInstanceExpression()->GetTypeRef()->AsETSTypeReference()->Part(); - if (typeReferencePart == nullptr) { - return nullptr; - } - auto id = typeReferencePart->Name(); - if (id != nullptr && id->IsIdentifier()) { - return compiler::DeclarationFromIdentifier(id->AsIdentifier()); - } + auto ident = GetIdentFromNewClassExprPart(value); + if (ident != nullptr) { + return compiler::DeclarationFromIdentifier(ident); } auto type = node->AsClassProperty()->TypeAnnotation(); if (type != nullptr && type->IsETSTypeReference()) { diff --git a/ets2panda/test/unit/lsp/class_hierarchy_info_test.cpp b/ets2panda/test/unit/lsp/class_hierarchy_info_test.cpp index 6d2466a99b..231e38ae56 100644 --- a/ets2panda/test/unit/lsp/class_hierarchy_info_test.cpp +++ b/ets2panda/test/unit/lsp/class_hierarchy_info_test.cpp @@ -22,9 +22,9 @@ using ark::es2panda::lsp::Initializer; namespace { -class LspScriptElementKindTests : public LSPAPITests {}; +class LspGetClassHierarchyInfoTests : public LSPAPITests {}; -TEST_F(LSPAPITests, GetClassHierarchyInfo_1) +TEST_F(LspGetClassHierarchyInfoTests, GetClassHierarchyInfo_1) { LSPAPI const *lspApi = GetImpl(); ASSERT_TRUE(lspApi != nullptr); @@ -56,21 +56,21 @@ private privateMethod(): void { ASSERT_EQ(classHierarchy.size(), 1); ASSERT_EQ(classHierarchy[0].GetClassName(), "Parent"); - auto methods = classHierarchy[0].GetMethodList(); - auto it = methods.find("publicMethod()"); + auto methods = classHierarchy[0].GetMethodItemList(); + auto it = methods.find("publicMethod(): void"); ASSERT_TRUE(it != methods.end()); ASSERT_TRUE(it->second != nullptr); - ASSERT_EQ(it->second->GetSetterStyle(), ark::es2panda::lsp::SetterStyle::METHOD); + ASSERT_EQ(it->second->GetSetterStyle(), ark::es2panda::lsp::SetterStyle::NONE); ASSERT_EQ(it->second->GetAccessModifierStyle(), ark::es2panda::lsp::AccessModifierStyle::PUBLIC); it = methods.find("action(fileName: string, position: number): number"); ASSERT_TRUE(it != methods.end()); ASSERT_TRUE(it->second != nullptr); - ASSERT_EQ(it->second->GetSetterStyle(), ark::es2panda::lsp::SetterStyle::METHOD); + ASSERT_EQ(it->second->GetSetterStyle(), ark::es2panda::lsp::SetterStyle::NONE); ASSERT_EQ(it->second->GetAccessModifierStyle(), ark::es2panda::lsp::AccessModifierStyle::PROTECTED); initializer.DestroyContext(context); } -TEST_F(LSPAPITests, GetClassHierarchyInfo_2) +TEST_F(LspGetClassHierarchyInfoTests, GetClassHierarchyInfo_2) { LSPAPI const *lspApi = GetImpl(); ASSERT_TRUE(lspApi != nullptr); @@ -110,16 +110,16 @@ class Magpie extends Bird { ASSERT_EQ(classHierarchy.size(), 1); ASSERT_EQ(classHierarchy[0].GetClassName(), "Animal"); - auto methods = classHierarchy[0].GetMethodList(); - auto it = methods.find("sleep()"); + auto methods = classHierarchy[0].GetMethodItemList(); + auto it = methods.find("sleep(): void"); ASSERT_TRUE(it != methods.end()); ASSERT_TRUE(it->second != nullptr); - ASSERT_EQ(it->second->GetSetterStyle(), ark::es2panda::lsp::SetterStyle::METHOD); + ASSERT_EQ(it->second->GetSetterStyle(), ark::es2panda::lsp::SetterStyle::NONE); ASSERT_EQ(it->second->GetAccessModifierStyle(), ark::es2panda::lsp::AccessModifierStyle::PROTECTED); initializer.DestroyContext(context); } -TEST_F(LSPAPITests, GetClassHierarchyInfo_3) +TEST_F(LspGetClassHierarchyInfoTests, GetClassHierarchyInfo_3) { LSPAPI const *lspApi = GetImpl(); ASSERT_TRUE(lspApi != nullptr); @@ -143,7 +143,7 @@ TEST_F(LSPAPITests, GetClassHierarchyInfo_3) initializer.DestroyContext(context); } -TEST_F(LSPAPITests, GetClassHierarchyInfo_4) +TEST_F(LspGetClassHierarchyInfoTests, GetClassHierarchyInfo_4) { LSPAPI const *lspApi = GetImpl(); ASSERT_TRUE(lspApi != nullptr); @@ -177,7 +177,7 @@ TEST_F(LSPAPITests, GetClassHierarchyInfo_4) ASSERT_EQ(classHierarchy.size(), 1); ASSERT_EQ(classHierarchy[0].GetClassName(), "ii"); - auto methods = classHierarchy[0].GetMethodList(); + auto methods = classHierarchy[0].GetMethodItemList(); auto it = methods.find("Body(): string"); ASSERT_TRUE(it != methods.end()); ASSERT_TRUE(it->second != nullptr); @@ -190,4 +190,177 @@ TEST_F(LSPAPITests, GetClassHierarchyInfo_4) ASSERT_EQ(it->second->GetAccessModifierStyle(), ark::es2panda::lsp::AccessModifierStyle::PUBLIC); initializer.DestroyContext(context); } + +TEST_F(LspGetClassHierarchyInfoTests, GetClassHierarchyInfo_5) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(class C { + func1(): void {} + func2(): string { + return "1"; + } + func3(): number { + return 1; + } + func4(): boolean { + return false; + } + func5(): Array { + return [1, 2]; + } +} + +class B extends C { + method1(): void {} + method2(parameter1: string, callBack: () => void): void {} +} + +class A extends B {/*1*/};)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("class_hierarchy_info_5.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto classHierarchy = lspApi->getClassHierarchyInfo(context, pos); + size_t expectInfoListSize = 2; + ASSERT_EQ(classHierarchy.size(), expectInfoListSize); + ASSERT_EQ(classHierarchy[0].GetClassName(), "B"); + ASSERT_EQ(classHierarchy[1].GetClassName(), "C"); + auto classBItems = classHierarchy[0].GetMethodItemList(); + ASSERT_TRUE(classBItems.find("method1(): void") != classBItems.end()); + ASSERT_TRUE(classBItems.find("method2(parameter1: string, callBack: (() => void)): void") != classBItems.end()); + auto classCItems = classHierarchy[1].GetMethodItemList(); + ASSERT_TRUE(classCItems.find("func1(): void") != classCItems.end()); + ASSERT_TRUE(classCItems.find("func2(): string") != classCItems.end()); + ASSERT_TRUE(classCItems.find("func3(): number") != classCItems.end()); + ASSERT_TRUE(classCItems.find("func4(): boolean") != classCItems.end()); + ASSERT_TRUE(classCItems.find("func5(): Array") != classCItems.end()); + initializer.DestroyContext(context); +} + +TEST_F(LspGetClassHierarchyInfoTests, GetClassHierarchyInfo_6) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(type parameter = number; + +class B { + public method1(parameter1: number): parameter { + return 1; + } + method2(parameter1: number): number { + return parameter1 as number; + } + async method3(parameter1: string): Promise { + return '1'; + } +} + +class A extends B {/*1*/};)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("class_hierarchy_info_6.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto classHierarchy = lspApi->getClassHierarchyInfo(context, pos); + ASSERT_FALSE(classHierarchy.empty()); + ASSERT_EQ(classHierarchy[0].GetClassName(), "B"); + auto classBItems = classHierarchy[0].GetMethodItemList(); + ASSERT_TRUE(classBItems.find("method1(parameter1: number): parameter") != classBItems.end()); + ASSERT_TRUE(classBItems.find("method2(parameter1: number): number") != classBItems.end()); + ASSERT_TRUE(classBItems.find("method3(parameter1: string): Promise") != classBItems.end()); + initializer.DestroyContext(context); +} + +TEST_F(LspGetClassHierarchyInfoTests, GetClassHierarchyInfo_7) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(class C { + func1(): void {} + + func2(): boolean { + return false; + } + + func3(): Array { + return [1, 2]; + } +}; + +class B extends C { + method1() {} + func2(): boolean { + return false; + } +} + +class A extends B { + method1() {} + func3(): Array { + return [1, 2]; + }/*1*/ +})"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("class_hierarchy_info_7.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto classHierarchy = lspApi->getClassHierarchyInfo(context, pos); + size_t expectInfoListSize = 2; + ASSERT_EQ(classHierarchy.size(), expectInfoListSize); + ASSERT_EQ(classHierarchy[0].GetClassName(), "B"); + ASSERT_EQ(classHierarchy[1].GetClassName(), "C"); + auto classBItems = classHierarchy[0].GetMethodItemList(); + ASSERT_EQ(classBItems.size(), 1); + ASSERT_TRUE(classBItems.find("func2(): boolean") != classBItems.end()); + auto classCItems = classHierarchy[1].GetMethodItemList(); + ASSERT_EQ(classCItems.size(), 1); + ASSERT_TRUE(classCItems.find("func1(): void") != classCItems.end()); + initializer.DestroyContext(context); +} + +TEST_F(LspGetClassHierarchyInfoTests, GetClassHierarchyInfo_8) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(class Parent { + public property1: number = 1; + protected property2: string = '1'; + private property3: boolean = true; + readonly property4: number = 1; + static property5: number = 1; +} + +class Son extends Parent { + property1: number = 2; + ChildExtraProperty1: number = 2; + ChildExtraProperty2: number = 2; +} + +class GrandSon extends Son {/*1*/ + public property2: string = '2'; + ChildExtraProperty1: number = 3; +})"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("class_hierarchy_info_8.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto classHierarchy = lspApi->getClassHierarchyInfo(context, pos); + size_t expectInfoListSize = 2; + ASSERT_EQ(classHierarchy.size(), expectInfoListSize); + ASSERT_EQ(classHierarchy[0].GetClassName(), "Son"); + ASSERT_EQ(classHierarchy[1].GetClassName(), "Parent"); + auto sonItems = classHierarchy[0].GetPropertyItemList(); + size_t expectPropertyListSize = 2; + ASSERT_EQ(sonItems.size(), expectPropertyListSize); + ASSERT_TRUE(sonItems.find("property1: number") != sonItems.end()); + ASSERT_TRUE(sonItems.find("ChildExtraProperty2: number") != sonItems.end()); + auto parentItems = classHierarchy[1].GetPropertyItemList(); + ASSERT_EQ(parentItems.size(), 1); + ASSERT_TRUE(parentItems.find("property4: number") != parentItems.end()); + initializer.DestroyContext(context); +} } // namespace -- Gitee From 16b04d6ce19b8ba6956a550a55de14c4d952d15e Mon Sep 17 00:00:00 2001 From: yaohaosen Date: Fri, 13 Jun 2025 11:53:12 +0800 Subject: [PATCH 058/145] [LSP] Fix Wrong Span of UI Plugin Code Fix Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICEY82 Signed-off-by: yaohaosen --- ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp | 2 +- ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp b/ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp index cb5f93b9dd..e450a3c3ec 100644 --- a/ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp +++ b/ets2panda/lsp/src/register_code_fix/ui_plugin_suggest.cpp @@ -39,7 +39,7 @@ std::vector GetTextChangesFromSuggestions(const ark::es2panda::util: for (auto suggestion : diag->Suggestion()) { auto sourceStart = suggestion->SourceRange()->start.index; auto sourceEnd = suggestion->SourceRange()->end.index; - auto span = TextSpan(sourceStart, sourceEnd); + auto span = TextSpan(sourceStart, sourceEnd - sourceStart); if (isAll) { textChanges.emplace_back(TextChange(span, suggestion->SubstitutionCode())); } else if (pos >= sourceStart && pos <= sourceEnd) { diff --git a/ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp b/ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp index 93c0d77ff8..e880bebb1d 100644 --- a/ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp +++ b/ets2panda/test/unit/lsp/code_fix/ui_plugin_suggest.cpp @@ -62,7 +62,7 @@ TEST_F(LspUISuggestionTests, UIPluginsErrorTest1) const char *substitutionCode = "replace b"; const char *dmessage2 = "error"; const size_t argc0 = 0; - const size_t index1 = 0; + const size_t index1 = 1; const size_t line1 = 0; const size_t index2 = 15; const size_t line2 = 0; @@ -84,6 +84,7 @@ TEST_F(LspUISuggestionTests, UIPluginsErrorTest1) CodeFixOptions emptyOptions; auto fix = ark::es2panda::lsp::GetCodeFixesAtPositionImpl(ctx, index1, index2, codes, emptyOptions); ASSERT_EQ(fix.at(0).changes_.at(0).textChanges.at(0).newText, substitutionCode); + ASSERT_EQ(fix.at(0).changes_.at(0).textChanges.at(0).span.length, index2 - index1); initializer.DestroyContext(ctx); } -- Gitee From aabf1d6b1a1bb55ca57386b9443fd4d63d28c259 Mon Sep 17 00:00:00 2001 From: leo9001 Date: Tue, 10 Jun 2025 20:04:22 +0800 Subject: [PATCH 059/145] support getApplicableRefactors refactors support getApplicableRefactors refactors Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICE3WK Signed-off-by: leo9001 --- ets2panda/bindings/native/src/lsp.cpp | 62 ++++ .../bindings/src/Es2pandaNativeModule.ts | 12 +- ets2panda/bindings/src/lspNode.ts | 21 +- ets2panda/bindings/src/lsp_helper.ts | 8 +- ets2panda/lsp/BUILD.gn | 4 + ets2panda/lsp/CMakeLists.txt | 4 + ets2panda/lsp/include/api.h | 5 +- ets2panda/lsp/include/internal_api.h | 1 + .../lsp/include/refactors/convert_chain.h | 35 +++ .../lsp/include/refactors/convert_export.h | 40 +++ .../lsp/include/refactors/convert_import.h | 43 +++ .../lsp/include/refactors/convert_template.h | 34 +++ .../lsp/include/refactors/refactor_types.h | 14 +- ets2panda/lsp/src/api.cpp | 8 +- ets2panda/lsp/src/internal_api.cpp | 11 + ets2panda/lsp/src/refactors/convert_chain.cpp | 79 +++++ .../lsp/src/refactors/convert_export.cpp | 76 +++++ .../lsp/src/refactors/convert_function.cpp | 32 +- .../lsp/src/refactors/convert_import.cpp | 86 ++++++ .../lsp/src/refactors/convert_template.cpp | 65 ++++ ets2panda/test/unit/lsp/CMakeLists.txt | 20 ++ .../unit/lsp/refactors_convert_chain_test.cpp | 121 ++++++++ .../lsp/refactors_convert_export_test.cpp | 101 +++++++ .../lsp/refactors_convert_function_test.cpp | 281 ++++++++++++++++++ .../lsp/refactors_convert_import_test.cpp | 78 +++++ .../lsp/refactors_convert_template_test.cpp | 234 +++++++++++++++ 26 files changed, 1451 insertions(+), 24 deletions(-) create mode 100644 ets2panda/lsp/include/refactors/convert_chain.h create mode 100644 ets2panda/lsp/include/refactors/convert_export.h create mode 100644 ets2panda/lsp/include/refactors/convert_import.h create mode 100644 ets2panda/lsp/include/refactors/convert_template.h create mode 100644 ets2panda/lsp/src/refactors/convert_chain.cpp create mode 100644 ets2panda/lsp/src/refactors/convert_export.cpp create mode 100644 ets2panda/lsp/src/refactors/convert_import.cpp create mode 100644 ets2panda/lsp/src/refactors/convert_template.cpp create mode 100644 ets2panda/test/unit/lsp/refactors_convert_chain_test.cpp create mode 100644 ets2panda/test/unit/lsp/refactors_convert_export_test.cpp create mode 100644 ets2panda/test/unit/lsp/refactors_convert_function_test.cpp create mode 100644 ets2panda/test/unit/lsp/refactors_convert_import_test.cpp create mode 100644 ets2panda/test/unit/lsp/refactors_convert_template_test.cpp diff --git a/ets2panda/bindings/native/src/lsp.cpp b/ets2panda/bindings/native/src/lsp.cpp index 5a620cfed4..09ed313d06 100644 --- a/ets2panda/bindings/native/src/lsp.cpp +++ b/ets2panda/bindings/native/src/lsp.cpp @@ -817,6 +817,68 @@ KNativePointer impl_getClassHierarchies(KNativePointer context, KStringPtr &file } TS_INTEROP_3(getClassHierarchies, KNativePointer, KNativePointer, KStringPtr, KInt) +KNativePointer impl_getApplicableRefactors(KNativePointer context, KStringPtr &kindPtr, KInt position) +{ + LSPAPI const *ctx = GetImpl(); + auto *result = new std::vector(ctx->getApplicableRefactors( + reinterpret_cast(context), GetStringCopy(kindPtr), static_cast(position))); + return result; +} +TS_INTEROP_3(getApplicableRefactors, KNativePointer, KNativePointer, KStringPtr, KInt) + +KNativePointer impl_getApplicableRefactorInfoList(KNativePointer infosPtr) +{ + auto *infos = reinterpret_cast *>(infosPtr); + std::vector ptrs; + for (auto &info : *infos) { + ptrs.push_back(new ark::es2panda::lsp::ApplicableRefactorInfo(info)); + } + return new std::vector(ptrs); +} +TS_INTEROP_1(getApplicableRefactorInfoList, KNativePointer, KNativePointer) + +KNativePointer impl_getRefactorActionName(KNativePointer refactorActionPtr) +{ + auto *refactorAction = reinterpret_cast(refactorActionPtr); + return new std::string(refactorAction->name); +} +TS_INTEROP_1(getRefactorActionName, KNativePointer, KNativePointer) + +KNativePointer impl_getRefactorActionDescription(KNativePointer refactorActionPtr) +{ + auto *refactorAction = reinterpret_cast(refactorActionPtr); + return new std::string(refactorAction->description); +} +TS_INTEROP_1(getRefactorActionDescription, KNativePointer, KNativePointer) + +KNativePointer impl_getRefactorActionKind(KNativePointer refactorActionPtr) +{ + auto *refactorAction = reinterpret_cast(refactorActionPtr); + return new std::string(refactorAction->kind); +} +TS_INTEROP_1(getRefactorActionKind, KNativePointer, KNativePointer) + +KNativePointer impl_getApplicableRefactorName(KNativePointer applRefsPtr) +{ + auto *applRefsInfo = reinterpret_cast(applRefsPtr); + return new std::string(applRefsInfo->name); +} +TS_INTEROP_1(getApplicableRefactorName, KNativePointer, KNativePointer) + +KNativePointer impl_getApplicableRefactorDescription(KNativePointer applRefsPtr) +{ + auto *applRefsInfo = reinterpret_cast(applRefsPtr); + return new std::string(applRefsInfo->description); +} +TS_INTEROP_1(getApplicableRefactorDescription, KNativePointer, KNativePointer) + +KNativePointer impl_getApplicableRefactorAction(KNativePointer applRefsPtr) +{ + auto *applRefsInfo = reinterpret_cast(applRefsPtr); + return new ark::es2panda::lsp::RefactorAction(applRefsInfo->action); +} +TS_INTEROP_1(getApplicableRefactorAction, KNativePointer, KNativePointer) + KNativePointer impl_getClassHierarchyList(KNativePointer infosPtr) { auto *infos = reinterpret_cast *>(infosPtr); diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts index c566f93d8f..07f5b0c4f4 100644 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/Es2pandaNativeModule.ts @@ -349,19 +349,23 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } - _getRefactorAction(ptr: KNativePointer): KPtr { + _getApplicableRefactorAction(ptr: KNativePointer): KPtr { throw new Error('Not implemented'); } - _getApplicableRefactors(context: KNativePointer, kind: String, position: number): KPtr { + _getApplicableRefactorName(ptr: KNativePointer): KPtr { throw new Error('Not implemented'); } - _getApplicableRefactorName(ptr: KNativePointer): KPtr { + _getApplicableRefactorDescription(ptr: KNativePointer): KPtr { throw new Error('Not implemented'); } - _getApplicableRefactorDescription(ptr: KNativePointer): KPtr { + _getApplicableRefactors(context: KNativePointer, kind: String, position: KInt): KPtr { + throw new Error('Not implemented'); + } + + _getApplicableRefactorInfoList(ptr: KNativePointer): KPtr { throw new Error('Not implemented'); } diff --git a/ets2panda/bindings/src/lspNode.ts b/ets2panda/bindings/src/lspNode.ts index 52eadf417f..9f9319e52b 100644 --- a/ets2panda/bindings/src/lspNode.ts +++ b/ets2panda/bindings/src/lspNode.ts @@ -743,7 +743,7 @@ export class LspSafeDeleteLocation extends LspNode { readonly safeDeleteLocationInfos: LspSafeDeleteLocationInfo[]; } -export class LspRefactorAction extends LspNode { +export class RefactorAction extends LspNode { constructor(peer: KNativePointer) { super(peer); this.name = unpackString(global.es2panda._getRefactorActionName(peer)); @@ -755,17 +755,30 @@ export class LspRefactorAction extends LspNode { readonly kind: String; } -export class LspApplicableRefactorInfo extends LspNode { +export class ApplicableRefactorItemInfo extends LspNode { constructor(peer: KNativePointer) { super(peer); this.name = unpackString(global.es2panda._getApplicableRefactorName(peer)); this.description = unpackString(global.es2panda._getApplicableRefactorDescription(peer)); - this.action = new LspRefactorAction(global.es2panda._getRefactorAction(peer)); + this.action = new RefactorAction(global.es2panda._getApplicableRefactorAction(peer)); } readonly name: String; readonly description: String; - readonly action: LspRefactorAction; + readonly action: RefactorAction; +} + +export class LspApplicableRefactorInfo extends LspNode { + constructor(peer: KNativePointer) { + super(peer); + this.applicableRefactorInfo = new NativePtrDecoder() + .decode(global.es2panda._getApplicableRefactorInfoList(peer)) + .map((elPeer: KNativePointer) => { + return new ApplicableRefactorItemInfo(elPeer); + }); + } + + readonly applicableRefactorInfo: ApplicableRefactorItemInfo[]; } export class LspTypeHierarchies extends LspNode { diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index 7effce3147..fed04cb4a6 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -30,6 +30,7 @@ import { LspLineAndCharacter, LspReferenceData, LspClassConstructorInfo, + ApplicableRefactorItemInfo, LspApplicableRefactorInfo, CompletionEntryDetails, LspFileTextChanges, @@ -495,7 +496,7 @@ export class Lsp { return new CompletionEntryDetails(ptr); } - getApplicableRefactors(filename: String, kind: String, offset: number): LspApplicableRefactorInfo { + getApplicableRefactors(filename: String, kind: String, offset: number): ApplicableRefactorItemInfo[] { let lspDriverHelper = new LspDriverHelper(); let filePath = path.resolve(filename.valueOf()); let arktsconfig = this.fileNameToArktsconfig[filePath]; @@ -507,11 +508,14 @@ export class Lsp { lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); + let result: ApplicableRefactorItemInfo[] = []; let ptr = global.es2panda._getApplicableRefactors(localCtx, kind, offset); PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); lspDriverHelper.destroyContext(localCtx); lspDriverHelper.destroyConfig(localCfg); - return new LspApplicableRefactorInfo(ptr); + let refs = new LspApplicableRefactorInfo(ptr); + result.push(...refs.applicableRefactorInfo); + return Array.from(new Set(result)); } getClassConstructorInfo(filename: String, offset: number, properties: string[]): LspClassConstructorInfo { diff --git a/ets2panda/lsp/BUILD.gn b/ets2panda/lsp/BUILD.gn index 52c00fa560..f2b7f2d1eb 100644 --- a/ets2panda/lsp/BUILD.gn +++ b/ets2panda/lsp/BUILD.gn @@ -73,7 +73,11 @@ ohos_source_set("libes2panda_lsp_static") { "src/organize_imports.cpp", "src/quick_info.cpp", "src/refactor_provider.cpp", + "src/refactors/convert_chain.cpp", + "src/refactors/convert_export.cpp", "src/refactors/convert_function.cpp", + "src/refactors/convert_import.cpp", + "src/refactors/convert_template.cpp", "src/refactors/refactor_types.cpp", "src/references.cpp", "src/register_code_fix/add_missing_declare_property.cpp", diff --git a/ets2panda/lsp/CMakeLists.txt b/ets2panda/lsp/CMakeLists.txt index ea7f2004ed..73c5561cbb 100644 --- a/ets2panda/lsp/CMakeLists.txt +++ b/ets2panda/lsp/CMakeLists.txt @@ -32,7 +32,11 @@ set(ES2PANDA_LSP_SRC ./src/refactors/refactor_types.cpp ./src/applicable_refactors.cpp ./src/refactor_provider.cpp + ./src/refactors/convert_chain.cpp + ./src/refactors/convert_export.cpp ./src/refactors/convert_function.cpp + ./src/refactors/convert_import.cpp + ./src/refactors/convert_template.cpp ./src/formatting/formatting_context.cpp ./src/formatting/formatting_settings.cpp ./src/formatting/formatting.cpp diff --git a/ets2panda/lsp/include/api.h b/ets2panda/lsp/include/api.h index bd47d74f9d..900e80c1a8 100644 --- a/ets2panda/lsp/include/api.h +++ b/ets2panda/lsp/include/api.h @@ -492,8 +492,9 @@ struct CodeFixOptions { typedef struct LSPAPI { DefinitionInfo (*getDefinitionAtPosition)(es2panda_Context *context, size_t position); - std::vector (*getApplicableRefactors)( - const ark::es2panda::lsp::RefactorContext *context); + std::vector (*getApplicableRefactors)(es2panda_Context *context, + const char *kind, + size_t position); DefinitionInfo (*getImplementationAtPosition)(es2panda_Context *context, size_t position); bool (*isPackageModule)(es2panda_Context *context); ark::es2panda::lsp::CompletionEntryKind (*getAliasScriptElementKind)(es2panda_Context *context, size_t position); diff --git a/ets2panda/lsp/include/internal_api.h b/ets2panda/lsp/include/internal_api.h index 03fa2abb1b..91cd095e6a 100644 --- a/ets2panda/lsp/include/internal_api.h +++ b/ets2panda/lsp/include/internal_api.h @@ -129,6 +129,7 @@ std::string GetOwnerId(ir::AstNode *node); std::string GetIdentifierName(ir::AstNode *node); bool NodeHasTokens(const ir::AstNode *node); void FindAllChild(const ir::AstNode *ast, const ir::NodePredicate &cb, ArenaVector &results); +ir::AstNode *FindAncestor(ir::AstNode *node, const ir::NodePredicate &cb); std::vector GetCodeFixesAtPositionImpl(es2panda_Context *context, size_t startPosition, size_t endPosition, std::vector &errorCodes, CodeFixOptions &codeFixOptions); diff --git a/ets2panda/lsp/include/refactors/convert_chain.h b/ets2panda/lsp/include/refactors/convert_chain.h new file mode 100644 index 0000000000..44eee48056 --- /dev/null +++ b/ets2panda/lsp/include/refactors/convert_chain.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 CONVERT_CHAIN_H +#define CONVERT_CHAIN_H + +#include "refactor_types.h" + +namespace ark::es2panda::lsp { + +constexpr RefactorActionView TO_NAMED_CHAIN_ACTION {"Convert to optional chain expression", + "Convert to optional chain expression", + "refactor.rewrite.expression.optionalChain"}; +class ConvertChainRefactor : public Refactor { +public: + ConvertChainRefactor(); + ApplicableRefactorInfo GetAvailableActions(const RefactorContext &context) const override; + std::unique_ptr GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const override; +}; +} // namespace ark::es2panda::lsp + +#endif \ No newline at end of file diff --git a/ets2panda/lsp/include/refactors/convert_export.h b/ets2panda/lsp/include/refactors/convert_export.h new file mode 100644 index 0000000000..c4d4fd7982 --- /dev/null +++ b/ets2panda/lsp/include/refactors/convert_export.h @@ -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. + */ + +#ifndef CONVERT_EXPORT_H +#define CONVERT_EXPORT_H + +#include "refactor_types.h" + +namespace ark::es2panda::lsp { + +constexpr RefactorActionView TO_NAMED_EXPORT_ACTION {"Convert default export to named export", + "Convert default export to named export", + "refactor.rewrite.export.named"}; +constexpr RefactorActionView TO_DEFAULT_EXPORT_ACTION {"Convert named export to default export", + "Convert named export to default export", + "refactor.rewrite.export.default"}; + +class ConvertExportRefactor : public Refactor { +public: + ConvertExportRefactor(); + ApplicableRefactorInfo GetAvailableActions(const RefactorContext &context) const override; + std::unique_ptr GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const override; +}; + +} // namespace ark::es2panda::lsp + +#endif // CONVERT_EXPORT_H diff --git a/ets2panda/lsp/include/refactors/convert_import.h b/ets2panda/lsp/include/refactors/convert_import.h new file mode 100644 index 0000000000..a41f5f5b6d --- /dev/null +++ b/ets2panda/lsp/include/refactors/convert_import.h @@ -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. + */ + +#ifndef CONVERT_IMPORT_H +#define CONVERT_IMPORT_H + +#include "refactor_types.h" + +namespace ark::es2panda::lsp { + +constexpr RefactorActionView TO_NAMED_IMPORT_ACTION {"Convert namespace import to named imports", + "Convert namespace import to named imports", + "refactor.rewrite.import.named"}; +constexpr RefactorActionView TO_NAMESPACE_IMPORT_ACTION {"Convert named imports to namespace import", + "Convert named imports to namespace import", + "refactor.rewrite.import.namespace"}; +constexpr RefactorActionView TO_DEFAULT_IMPORT_ACTION {"Convert named imports to default import", + "Convert named imports to default import", + "refactor.rewrite.import.default"}; + +class ConvertImportRefactor : public Refactor { +public: + ConvertImportRefactor(); + ApplicableRefactorInfo GetAvailableActions(const RefactorContext &context) const override; + std::unique_ptr GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const override; +}; + +} // namespace ark::es2panda::lsp + +#endif // CONVERT_IMPORT_H diff --git a/ets2panda/lsp/include/refactors/convert_template.h b/ets2panda/lsp/include/refactors/convert_template.h new file mode 100644 index 0000000000..4c27a6d9c7 --- /dev/null +++ b/ets2panda/lsp/include/refactors/convert_template.h @@ -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. + */ + +#ifndef CONVERT_TEMPLATE_H +#define CONVERT_TEMPLATE_H + +#include "refactor_types.h" + +namespace ark::es2panda::lsp { + +constexpr RefactorActionView TO_NAMED_TEMPLATE_ACTION {"Convert to template string", "Convert to template string", + "refactor.rewrite.string"}; +class ConvertTemplateRefactor : public Refactor { +public: + ConvertTemplateRefactor(); + ApplicableRefactorInfo GetAvailableActions(const RefactorContext &context) const override; + std::unique_ptr GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const override; +}; +} // namespace ark::es2panda::lsp + +#endif \ No newline at end of file diff --git a/ets2panda/lsp/include/refactors/refactor_types.h b/ets2panda/lsp/include/refactors/refactor_types.h index 72e3dd74ea..513ba22f97 100644 --- a/ets2panda/lsp/include/refactors/refactor_types.h +++ b/ets2panda/lsp/include/refactors/refactor_types.h @@ -49,10 +49,10 @@ struct TextRange { }; struct RefactorContext { - ark::es2panda::lsp::CancellationToken *cancellationToken; - ark::es2panda::lsp::UserPreferences *preferences; - TextRange span; - es2panda_Context *context; + ark::es2panda::lsp::CancellationToken *cancellationToken = nullptr; + ark::es2panda::lsp::UserPreferences *preferences = nullptr; + TextRange span = {0, 0}; + es2panda_Context *context = nullptr; std::string kind; }; @@ -76,10 +76,16 @@ using ApplicableRefactorInfo = struct ApplicableRefactorInfo { namespace refactor_name { constexpr std::string_view CONVERT_FUNCTION_REFACTOR_NAME = "Convert arrow function or function expression"; +constexpr std::string_view CONVERT_EXPORT_REFACTOR_NAME = "Convert export"; +constexpr std::string_view CONVERT_IMPORT_REFACTOR_NAME = "Convert import"; +constexpr std::string_view CONVERT_TEMPLATE_REFACTOR_NAME = "Convert to template string"; +constexpr std::string_view CONVERT_CHAIN_REFACTOR_NAME = "Convert to optional chain expression"; } // namespace refactor_name namespace refactor_description { constexpr std::string_view CONVERT_FUNCTION_REFACTOR_DESC = "Convert arrow function or function expression"; +constexpr std::string_view CONVERT_TEMPLATE_REFACTOR_DESC = "Convert to template string"; +constexpr std::string_view CONVERT_CHAIN_REFACTOR_DESC = "Convert to optional chain expression"; } // namespace refactor_description class Refactor { diff --git a/ets2panda/lsp/src/api.cpp b/ets2panda/lsp/src/api.cpp index 01fbfa3e38..117f6e4912 100644 --- a/ets2panda/lsp/src/api.cpp +++ b/ets2panda/lsp/src/api.cpp @@ -354,9 +354,13 @@ LineAndCharacter ToLineColumnOffsetWrapper(es2panda_Context *context, size_t pos // Returns type of refactoring and action that can be performed based // on the input kind information and cursor position -std::vector GetApplicableRefactors(const RefactorContext *context) +std::vector GetApplicableRefactors(es2panda_Context *context, const char *kind, size_t position) { - auto result = GetApplicableRefactorsImpl(context); + RefactorContext refactorContext; + refactorContext.context = context; + refactorContext.kind = kind; + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); return result; } diff --git a/ets2panda/lsp/src/internal_api.cpp b/ets2panda/lsp/src/internal_api.cpp index 795777e89e..efeee45bfd 100644 --- a/ets2panda/lsp/src/internal_api.cpp +++ b/ets2panda/lsp/src/internal_api.cpp @@ -652,6 +652,17 @@ void FindAllChild(const ir::AstNode *ast, const ir::NodePredicate &cb, ArenaVect ast->Iterate([&results, cb](ir::AstNode *child) { FindAllChildHelper(child, cb, results); }); } +ir::AstNode *FindAncestor(ir::AstNode *node, const ir::NodePredicate &cb) +{ + while (node != nullptr) { + if (cb(node)) { + return node; + } + node = node->Parent(); + } + return node; +} + ArenaVector FindReferencesByName(ir::AstNode *ast, ir::AstNode *decl, ir::AstNode *node, ArenaAllocator *allocator) { diff --git a/ets2panda/lsp/src/refactors/convert_chain.cpp b/ets2panda/lsp/src/refactors/convert_chain.cpp new file mode 100644 index 0000000000..1d76ecaee2 --- /dev/null +++ b/ets2panda/lsp/src/refactors/convert_chain.cpp @@ -0,0 +1,79 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "refactors/convert_chain.h" +#include "refactor_provider.h" +#include "internal_api.h" + +namespace ark::es2panda::lsp { + +ark::es2panda::ir::AstNode *FindType(ark::es2panda::ir::AstNode *node); + +ConvertChainRefactor::ConvertChainRefactor() +{ + AddKind(std::string(TO_NAMED_CHAIN_ACTION.kind)); +} + +ark::es2panda::ir::AstNode *FindType(ark::es2panda::ir::AstNode *node) +{ + if ((node != nullptr) && (node->Parent() != nullptr)) { + if (node->Parent()->IsExpression()) { + return node; + } + auto cb = [](ir::AstNode *ancestorNode) { return ancestorNode->IsConditionalExpression(); }; + node = FindAncestor(node, cb); + return node; + } + return node; +} + +ApplicableRefactorInfo ConvertChainRefactor::GetAvailableActions(const RefactorContext &refContext) const +{ + es2panda_Context *context = refContext.context; + size_t position = refContext.span.pos; + + ApplicableRefactorInfo res; + + if (!IsKind(refContext.kind)) { + return res; + } + auto node = GetTouchingToken(context, position, false); + if (node == nullptr) { + return res; + } + + auto nodedec1 = FindType(node); + if (nodedec1 != nullptr && (nodedec1->IsConditionalExpression() || nodedec1->IsExpression())) { + res.name = refactor_name::CONVERT_CHAIN_REFACTOR_NAME; + res.description = refactor_description::CONVERT_CHAIN_REFACTOR_DESC; + res.action.kind = std::string(TO_NAMED_CHAIN_ACTION.kind); + res.action.name = std::string(TO_NAMED_CHAIN_ACTION.name); + res.action.description = std::string(TO_NAMED_CHAIN_ACTION.description); + } + return res; +} + +std::unique_ptr ConvertChainRefactor::GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const +{ + (void)context; + (void)actionName; + return std::make_unique(); +} +// NOLINTNEXTLINE(fuchsia-statically-constructed-objects, cert-err58-cpp) +AutoRefactorRegister g_convertChainRefactorRegister("ConvertChainRefactor"); + +} // namespace ark::es2panda::lsp \ No newline at end of file diff --git a/ets2panda/lsp/src/refactors/convert_export.cpp b/ets2panda/lsp/src/refactors/convert_export.cpp new file mode 100644 index 0000000000..3c76a57609 --- /dev/null +++ b/ets2panda/lsp/src/refactors/convert_export.cpp @@ -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. + */ + +#include +#include "refactors/convert_export.h" +#include "refactor_provider.h" +#include "internal_api.h" + +namespace ark::es2panda::lsp { + +ConvertExportRefactor::ConvertExportRefactor() +{ + AddKind(std::string(TO_NAMED_EXPORT_ACTION.kind)); + AddKind(std::string(TO_DEFAULT_EXPORT_ACTION.kind)); +} + +ApplicableRefactorInfo ConvertExportRefactor::GetAvailableActions(const RefactorContext &refContext) const +{ + es2panda_Context *context = refContext.context; + size_t position = refContext.span.pos; + + ApplicableRefactorInfo res; + + if (!IsKind(refContext.kind)) { + return res; + } + + auto node = GetTouchingToken(context, position, false); + if (node == nullptr) { + return res; + } + auto cb = [](ir::AstNode *ancestorNode) { return ancestorNode->IsDefaultExported() || ancestorNode->IsExported(); }; + auto ancestor = FindAncestor(node, cb); + if (ancestor == nullptr) { + return res; + } + if (ancestor->IsDefaultExported()) { + res.name = refactor_name::CONVERT_EXPORT_REFACTOR_NAME; + res.description = std::string(TO_NAMED_EXPORT_ACTION.description); + res.action.kind = std::string(TO_NAMED_EXPORT_ACTION.kind); + res.action.name = std::string(TO_NAMED_EXPORT_ACTION.name); + res.action.description = std::string(TO_NAMED_EXPORT_ACTION.description); + } else if (ancestor->IsExported()) { + res.name = refactor_name::CONVERT_EXPORT_REFACTOR_NAME; + res.description = std::string(TO_DEFAULT_EXPORT_ACTION.description); + res.action.kind = std::string(TO_DEFAULT_EXPORT_ACTION.kind); + res.action.name = std::string(TO_DEFAULT_EXPORT_ACTION.name); + res.action.description = std::string(TO_DEFAULT_EXPORT_ACTION.description); + } + + return res; +} + +std::unique_ptr ConvertExportRefactor::GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const +{ + (void)context; + (void)actionName; + return std::make_unique(); +} +// NOLINTNEXTLINE(fuchsia-statically-constructed-objects, cert-err58-cpp) +AutoRefactorRegister g_convertExportRefactorRegister("ConvertExportRefactor"); + +} // namespace ark::es2panda::lsp diff --git a/ets2panda/lsp/src/refactors/convert_function.cpp b/ets2panda/lsp/src/refactors/convert_function.cpp index e594fa230a..097fe6fe65 100644 --- a/ets2panda/lsp/src/refactors/convert_function.cpp +++ b/ets2panda/lsp/src/refactors/convert_function.cpp @@ -16,7 +16,6 @@ #include #include "refactors/convert_function.h" #include "refactor_provider.h" -#include "compiler/lowering/util.h" #include "internal_api.h" namespace ark::es2panda::lsp { @@ -28,6 +27,28 @@ ConvertFunctionRefactor::ConvertFunctionRefactor() AddKind(std::string(TO_ARROW_FUNCTION_ACTION.kind)); } +bool HasArrowFunction(ark::es2panda::ir::AstNode *node) +{ + if (!node->IsCallExpression() && !node->IsClassProperty() && !node->IsVariableDeclarator()) { + return false; + } + if ((node->IsClassProperty() && node->AsClassProperty()->Value() != nullptr && + node->AsClassProperty()->Value()->IsArrowFunctionExpression()) || + (node->IsVariableDeclarator() && node->AsVariableDeclarator()->Init() != nullptr && + node->AsVariableDeclarator()->Init()->IsArrowFunctionExpression())) { + return true; + } + if (node->IsCallExpression()) { + auto arguments = node->AsCallExpression()->Arguments(); + for (auto argument : arguments) { + if (argument->IsArrowFunctionExpression()) { + return true; + } + } + } + return false; +} + ApplicableRefactorInfo ConvertFunctionRefactor::GetAvailableActions(const RefactorContext &refContext) const { es2panda_Context *context = refContext.context; @@ -40,13 +61,12 @@ ApplicableRefactorInfo ConvertFunctionRefactor::GetAvailableActions(const Refact } auto node = GetTouchingToken(context, position, false); - if (node == nullptr || !node->IsIdentifier()) { + if (node == nullptr) { return res; } - - auto nodeDecl = compiler::DeclarationFromIdentifier(node->AsIdentifier()); - if (nodeDecl != nullptr && nodeDecl->IsClassProperty() && nodeDecl->AsClassProperty()->Value() != nullptr && - nodeDecl->AsClassProperty()->Value()->IsArrowFunctionExpression()) { + auto cb = [](ir::AstNode *ancestorNode) { return HasArrowFunction(ancestorNode); }; + auto ancestor = FindAncestor(node, cb); + if (ancestor != nullptr && ancestor->IsClassProperty()) { res.name = refactor_name::CONVERT_FUNCTION_REFACTOR_NAME; res.description = refactor_description::CONVERT_FUNCTION_REFACTOR_DESC; res.action.kind = std::string(TO_NAMED_FUNCTION_ACTION.kind); diff --git a/ets2panda/lsp/src/refactors/convert_import.cpp b/ets2panda/lsp/src/refactors/convert_import.cpp new file mode 100644 index 0000000000..fbe48a59f9 --- /dev/null +++ b/ets2panda/lsp/src/refactors/convert_import.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 "refactors/convert_import.h" +#include "refactor_provider.h" +#include "internal_api.h" + +namespace ark::es2panda::lsp { + +ConvertImportRefactor::ConvertImportRefactor() +{ + AddKind(std::string(TO_NAMED_IMPORT_ACTION.kind)); + AddKind(std::string(TO_NAMESPACE_IMPORT_ACTION.kind)); + AddKind(std::string(TO_DEFAULT_IMPORT_ACTION.kind)); +} + +ApplicableRefactorInfo ConvertImportRefactor::GetAvailableActions(const RefactorContext &refContext) const +{ + es2panda_Context *context = refContext.context; + size_t position = refContext.span.pos; + + ApplicableRefactorInfo res; + + if (!IsKind(refContext.kind)) { + return res; + } + + auto node = GetTouchingToken(context, position, false); + if (node == nullptr) { + return res; + } + auto cb = [](ir::AstNode *ancestorNode) { + return ancestorNode->IsETSImportDeclaration() || ancestorNode->IsImportNamespaceSpecifier() || + ancestorNode->IsImportSpecifier(); + }; + auto ancestor = FindAncestor(node, cb); + if (ancestor != nullptr && ancestor->IsETSImportDeclaration()) { + auto specifiers = ancestor->AsETSImportDeclaration()->Specifiers(); + if (!specifiers.empty()) { + ancestor = specifiers[0]; + } + } + if (ancestor == nullptr) { + return res; + } + if (ancestor->IsImportNamespaceSpecifier()) { + res.name = refactor_name::CONVERT_IMPORT_REFACTOR_NAME; + res.description = std::string(TO_NAMED_IMPORT_ACTION.description); + res.action.kind = std::string(TO_NAMED_IMPORT_ACTION.kind); + res.action.name = std::string(TO_NAMED_IMPORT_ACTION.name); + res.action.description = std::string(TO_NAMED_IMPORT_ACTION.description); + } else if (ancestor->IsImportSpecifier()) { + res.name = refactor_name::CONVERT_IMPORT_REFACTOR_NAME; + res.description = std::string(TO_NAMESPACE_IMPORT_ACTION.description); + res.action.kind = std::string(TO_NAMESPACE_IMPORT_ACTION.kind); + res.action.name = std::string(TO_NAMESPACE_IMPORT_ACTION.name); + res.action.description = std::string(TO_NAMESPACE_IMPORT_ACTION.description); + } + + return res; +} + +std::unique_ptr ConvertImportRefactor::GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const +{ + (void)context; + (void)actionName; + return std::make_unique(); +} +// NOLINTNEXTLINE(fuchsia-statically-constructed-objects, cert-err58-cpp) +AutoRefactorRegister g_convertImportRefactorRegister("ConvertImportRefactor"); + +} // namespace ark::es2panda::lsp diff --git a/ets2panda/lsp/src/refactors/convert_template.cpp b/ets2panda/lsp/src/refactors/convert_template.cpp new file mode 100644 index 0000000000..ed3e76f0e7 --- /dev/null +++ b/ets2panda/lsp/src/refactors/convert_template.cpp @@ -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. + */ + +#include +#include "refactors/convert_template.h" +#include "refactor_provider.h" +#include "internal_api.h" + +namespace ark::es2panda::lsp { + +ConvertTemplateRefactor::ConvertTemplateRefactor() +{ + AddKind(std::string(TO_NAMED_TEMPLATE_ACTION.kind)); +} + +ApplicableRefactorInfo ConvertTemplateRefactor::GetAvailableActions(const RefactorContext &refContext) const +{ + es2panda_Context *context = refContext.context; + size_t position = refContext.span.pos; + + ApplicableRefactorInfo res; + + if (!IsKind(refContext.kind)) { + return res; + } + auto node = GetTouchingToken(context, position, false); + if (node == nullptr) { + return res; + } + + if (node != nullptr && node->Parent() != nullptr && + (node->Parent()->IsExpression() && node->Parent()->IsBinaryExpression())) { + res.name = refactor_name::CONVERT_TEMPLATE_REFACTOR_NAME; + res.description = refactor_description::CONVERT_TEMPLATE_REFACTOR_DESC; + res.action.kind = std::string(TO_NAMED_TEMPLATE_ACTION.kind); + res.action.name = std::string(TO_NAMED_TEMPLATE_ACTION.name); + res.action.description = std::string(TO_NAMED_TEMPLATE_ACTION.description); + } + + return res; +} + +std::unique_ptr ConvertTemplateRefactor::GetEditsForAction(const RefactorContext &context, + const std::string &actionName) const +{ + (void)context; + (void)actionName; + return std::make_unique(); +} +// NOLINTNEXTLINE(fuchsia-statically-constructed-objects, cert-err58-cpp) +AutoRefactorRegister g_convertTemplateRefactorRegister("ConvertTemplateRefactor"); + +} // namespace ark::es2panda::lsp diff --git a/ets2panda/test/unit/lsp/CMakeLists.txt b/ets2panda/test/unit/lsp/CMakeLists.txt index 8314f1cb93..7c300f8dc0 100644 --- a/ets2panda/test/unit/lsp/CMakeLists.txt +++ b/ets2panda/test/unit/lsp/CMakeLists.txt @@ -99,6 +99,26 @@ ets2panda_add_gtest(lsp_api_test_class_hierarchies CPP_SOURCES class_hierarchys_test.cpp ) +ets2panda_add_gtest(lsp_api_test_refactors_convert_chain CPP_SOURCES + refactors_convert_chain_test.cpp +) + +ets2panda_add_gtest(lsp_api_test_refactors_convert_export CPP_SOURCES + refactors_convert_export_test.cpp +) + +ets2panda_add_gtest(lsp_api_test_refactors_convert_function CPP_SOURCES + refactors_convert_function_test.cpp +) + +ets2panda_add_gtest(lsp_api_test_refactors_convert_import CPP_SOURCES + refactors_convert_import_test.cpp +) + +ets2panda_add_gtest(lsp_api_test_refactors_convert_template CPP_SOURCES + refactors_convert_template_test.cpp +) + ets2panda_add_gtest(lsp_api_diagnostics_test CPP_SOURCES get_compiler_options_diagnostics_test.cpp get_diagnostics.cpp diff --git a/ets2panda/test/unit/lsp/refactors_convert_chain_test.cpp b/ets2panda/test/unit/lsp/refactors_convert_chain_test.cpp new file mode 100644 index 0000000000..67e51357ec --- /dev/null +++ b/ets2panda/test/unit/lsp/refactors_convert_chain_test.cpp @@ -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. + */ + +#include +#include +#include +#include "lsp_api_test.h" +#include "lsp/include/applicable_refactors.h" + +const size_t REFACTOR_CHAIN_POSITION_OFFSET = 8; + +namespace { +using ark::es2panda::lsp::Initializer; + +class LspChainRefTests : public LSPAPITests { +public: + static constexpr std::string_view TO_NAMED_CHAIN_KIND = "refactor.rewrite.expression.optionalChain"; + static constexpr std::string_view TO_NAMED_CHAIN_NAME = "Convert to optional chain expression"; +}; + +TEST_F(LspChainRefTests, ConvertChainRefactor1) +{ + std::vector files = {"ConvertChainRefactor1.ets"}; + std::vector texts = {R"(let a = {b: ()=>{return () =>{c:0}}}/*1*/a&&a.b&&a.b()().c/*2*/;)"}; + + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_CHAIN_KIND); + refactorContext.span.pos = pos + REFACTOR_CHAIN_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_CHAIN_NAME), result[0].action.name); +} + +TEST_F(LspChainRefTests, ConvertChainRefactor2) +{ + std::vector files = {"ConvertChainRefactor2.ets"}; + std::vector texts = {R"(interface Foo{ +bar?:{ +baz?:string | null; +} +} +declare let foo: Foo; +let ccc = /*1*/foo.bar ? +foo.bar.baz : "whenFalse";/*2*/ + )"}; + + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_CHAIN_KIND); + refactorContext.span.pos = pos + REFACTOR_CHAIN_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_CHAIN_NAME), result[0].action.name); +} + +TEST_F(LspChainRefTests, ConvertChainRefactor3) +{ + std::vector files = {"ConvertChainRefactor3.ets"}; + std::vector texts = {R"(interface Foo{ +bar?:{ +baz: string; +} +} +declare let foo: Foo; +let ccc = /*1*/foo.bar? +foo.bar.baz: "whenFalse";/*2*/ + )"}; + + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_CHAIN_KIND); + refactorContext.span.pos = pos + REFACTOR_CHAIN_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_CHAIN_NAME), result[0].action.name); +} + +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/refactors_convert_export_test.cpp b/ets2panda/test/unit/lsp/refactors_convert_export_test.cpp new file mode 100644 index 0000000000..3cf7a64c12 --- /dev/null +++ b/ets2panda/test/unit/lsp/refactors_convert_export_test.cpp @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "lsp_api_test.h" +#include "lsp/include/applicable_refactors.h" + +namespace { +using ark::es2panda::lsp::Initializer; + +class LspConvExpTests : public LSPAPITests { +public: + static constexpr std::string_view TO_NAMED_EXPORT_KIND = "refactor.rewrite.export.named"; + static constexpr std::string_view TO_NAMED_EXPORT_NAME = "Convert default export to named export"; + static constexpr std::string_view TO_DEFAULT_EXPORT_KIND = "refactor.rewrite.export.default"; + static constexpr std::string_view TO_DEFAULT_EXPORT_NAME = "Convert named export to default export"; +}; + +TEST_F(LspConvExpTests, ConvertExportRefactor1) +{ + std::vector files = {"convertExportRefactor1.ets"}; + std::vector texts = {R"(export default function add(a: number, b: number): number { + return a + b; +})"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 26; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_EXPORT_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_EXPORT_NAME), result[0].action.name); +} + +TEST_F(LspConvExpTests, ConvertExportRefactor2) +{ + std::vector files = {"convertExportRefactor2.ets"}; + std::vector texts = {R"(export default class User { + name: string = ""; +})"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 24; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_EXPORT_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_EXPORT_NAME), result[0].action.name); +} + +TEST_F(LspConvExpTests, ConvertExportRefactor5) +{ + std::vector files = {"convertExportRefactor5.ets"}; + std::vector texts = {R"(export function add(a: number, b: number): number { + return a + b; +})"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 19; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_DEFAULT_EXPORT_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_DEFAULT_EXPORT_NAME), result[0].action.name); +} +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/refactors_convert_function_test.cpp b/ets2panda/test/unit/lsp/refactors_convert_function_test.cpp new file mode 100644 index 0000000000..854e59a483 --- /dev/null +++ b/ets2panda/test/unit/lsp/refactors_convert_function_test.cpp @@ -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. + */ + +#include +#include +#include +#include "lsp_api_test.h" +#include "lsp/include/applicable_refactors.h" + +namespace { +using ark::es2panda::lsp::Initializer; + +class LspConvFuncTests : public LSPAPITests { +public: + static constexpr std::string_view TO_NAMED_FUNCTION_KIND = "refactor.rewrite.function.named"; + static constexpr std::string_view INVALID_KIND = "aaabbbccc"; + static constexpr std::string_view TO_NAMED_FUNCTION_NAME = "Convert to named function"; +}; + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor1) +{ + std::vector files = {"convertFunctionRefactor1.ets"}; + std::vector texts = {R"(const add = (x: number, y: number): number => { + return x + y; + };)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 8; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_FUNCTION_NAME), result[0].action.name); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor2) +{ + std::vector files = {"convertFunctionRefactor2.ets"}; + std::vector texts = {R"(function sub(a: number, b: number): number{ + return a - b; + };)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 11; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor3) +{ + std::vector files = {"convertFunctionRefactor3.ets"}; + std::vector texts = {R"(const add = (x: number, y: number): number => { + return x + y; + };)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 8; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(INVALID_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor4) +{ + std::vector files = {"convertFunctionRefactor4.ets"}; + std::vector texts = {R"(const foo = a => { +let b = 1; +return a + b; +};)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + size_t const position = 13; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_FUNCTION_NAME), result[0].action.name); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor5) +{ + std::vector files = {"convertFunctionRefactor5.ets"}; + std::vector texts = {R"(function doSomething(a){} +doSomething(() => 1 + 1);)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 41; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor6) +{ + std::vector files = {"convertFunctionRefactor6.ets"}; + std::vector texts = {R"(const foo = (a,b,c) => a + 1;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 14; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_FUNCTION_NAME), result[0].action.name); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor7) +{ + std::vector files = {"convertFunctionRefactor7.ets"}; + std::vector texts = {R"(const foo = () => //comment +1)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 14; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_FUNCTION_NAME), result[0].action.name); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor8) +{ + std::vector files = {"convertFunctionRefactor8.ets"}; + std::vector texts = {R"(function func() { +const test = () => { +} +})"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 28; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor9) +{ + std::vector files = {"convertFunctionRefactor9.ets"}; + std::vector texts = {R"(class AA { +func() { +const test = () => {} +} +})"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 31; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor10) +{ + std::vector files = {"convertFunctionRefactor10.ets"}; + std::vector texts = {R"(const func = () => { +const test = () => {} +})"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 31; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspConvFuncTests, ConvertFunctionRefactor11) +{ + std::vector files = {"convertFunctionRefactor11.ets"}; + std::vector texts = {R"(@Component +struct Index { +build() { +Text().onClick(()=>{ +const test = () =>{} +}) +} +})"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 70; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_FUNCTION_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/refactors_convert_import_test.cpp b/ets2panda/test/unit/lsp/refactors_convert_import_test.cpp new file mode 100644 index 0000000000..f2945334e0 --- /dev/null +++ b/ets2panda/test/unit/lsp/refactors_convert_import_test.cpp @@ -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. + */ + +#include +#include +#include +#include "lsp_api_test.h" +#include "lsp/include/applicable_refactors.h" + +namespace { +using ark::es2panda::lsp::Initializer; + +class LspConvImpTests : public LSPAPITests { +public: + static constexpr std::string_view TO_NAMED_IMPORT_KIND = "refactor.rewrite.import.named"; + static constexpr std::string_view TO_NAMED_IMPORT_NAME = "Convert namespace import to named imports"; + static constexpr std::string_view TO_NAMESPACE_IMPORT_KIND = "refactor.rewrite.import.namespace"; + static constexpr std::string_view TO_NAMESPACE_IMPORT_NAME = "Convert named imports to namespace import"; +}; + +TEST_F(LspConvImpTests, ConvertImportRefactor1) +{ + std::vector files = {"convertImportRefactor1.ets"}; + std::vector texts = {R"(import { add, subtract, multiply } from './math'; + +const result = add(1, subtract(5, multiply(2, 3)));)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 28; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMESPACE_IMPORT_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMESPACE_IMPORT_NAME), result[0].action.name); +} + +TEST_F(LspConvImpTests, ConvertImportRefactor2) +{ + std::vector files = {"convertImportRefactor2.ets"}; + std::vector texts = {R"(import * as math from './math'; + +const result = math.add(1, math.subtract(5, math.multiply(2, 3)));)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + size_t const position = 15; + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_IMPORT_KIND); + refactorContext.span.pos = position; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_IMPORT_NAME), result[0].action.name); +} +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/refactors_convert_template_test.cpp b/ets2panda/test/unit/lsp/refactors_convert_template_test.cpp new file mode 100644 index 0000000000..7ed519dbde --- /dev/null +++ b/ets2panda/test/unit/lsp/refactors_convert_template_test.cpp @@ -0,0 +1,234 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "lsp_api_test.h" +#include "lsp/include/applicable_refactors.h" + +const size_t REFACTOR_TEMPLATE_POSITION_OFFSET = 8; + +namespace { +using ark::es2panda::lsp::Initializer; + +class LspTemplateRefTests : public LSPAPITests { +public: + static constexpr std::string_view TO_NAMED_TEMPLATE_KIND = "refactor.rewrite.string"; + static constexpr std::string_view TO_NAMED_TEMPLATE_NAME = "Convert to template string"; +}; + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor1) +{ + std::vector files = {"ConvertTemplateRefactor1.ets"}; + std::vector texts = {R"(let a = /*1*/"\\0\\b\\f\\t\\r\\n" +text + "\\n"/*2*/;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_TEMPLATE_NAME), result[0].action.name); +} + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor2) +{ + std::vector files = {"ConvertTemplateRefactor2.ets"}; + std::vector texts = {R"(let b = /*3*/"" + text + ""/*4*/;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*3*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_TEMPLATE_NAME), result[0].action.name); +} + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor3) +{ + std::vector files = {"ConvertTemplateRefactor3.ets"}; + std::vector texts = {R"(let c = /*5*/'\$' + text + "\\\\/*6*/";)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*5*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_TEMPLATE_NAME), result[0].action.name); +} + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor4) +{ + std::vector files = {"ConvertTemplateRefactor4.ets"}; + std::vector texts = {R"(let d = /*7*/\'\$\' + text + \'\\\\\'/*8*/;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*7*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor5) +{ + std::vector files = {"ConvertTemplateRefactor5.ets"}; + std::vector texts = {R"(let e = /*9*/'\$\{' + text + "\}"/*10*/;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*9*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_TEMPLATE_NAME), result[0].action.name); +} + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor6) +{ + std::vector files = {"ConvertTemplateRefactor6.ets"}; + std::vector texts = {R"(let f = /*11*/ \'\\\$\{\' + text + \'\}\'/*12*/;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*11*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor7) +{ + std::vector files = {"ConvertTemplateRefactor7.ets"}; + std::vector texts = {R"(let g = /*13*/'\\\\$ + text + "\\\\"/*14*/;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*13*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + + initializer.DestroyContext(ctx); + ASSERT_EQ(0, result.size()); +} + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor8) +{ + std::vector files = {"ConvertTemplateRefactor8.ets"}; + std::vector texts = {R"(let h = /*15*/"\\u0041\\u0061" + text + "\\0\\u0000"/*16*/;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*15*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_TEMPLATE_NAME), result[0].action.name); +} + +TEST_F(LspTemplateRefTests, ConvertTemplateRefactor9) +{ + std::vector files = {"ConvertTemplateRefactor9.ets"}; + std::vector texts = {R"(let i = /*17*/'\$\`' + text + "\`\\\\"/*18*/;)"}; + auto filePaths = CreateTempFile(files, texts); + size_t const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + auto pos = texts[0].find("/*17*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + ark::es2panda::lsp::RefactorContext refactorContext; + refactorContext.context = ctx; + refactorContext.kind = std::string(TO_NAMED_TEMPLATE_KIND); + refactorContext.span.pos = pos + REFACTOR_TEMPLATE_POSITION_OFFSET; + auto result = GetApplicableRefactorsImpl(&refactorContext); + initializer.DestroyContext(ctx); + ASSERT_EQ(1, result.size()); + ASSERT_EQ(std::string(TO_NAMED_TEMPLATE_NAME), result[0].action.name); +} + +} // namespace \ No newline at end of file -- Gitee From 4dfbe242a418002311cf542b9e31f9b5f3cc352e Mon Sep 17 00:00:00 2001 From: leo9001 Date: Tue, 17 Jun 2025 10:41:28 +0800 Subject: [PATCH 060/145] support getSafeDeleteInfo new function support getSafeDeleteInfo new function Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICFLY3 Signed-off-by: leo9001 --- ets2panda/bindings/native/src/lsp.cpp | 7 +- .../bindings/src/Es2pandaNativeModule.ts | 2 +- ets2panda/bindings/src/lsp_helper.ts | 2 +- ets2panda/lsp/include/api.h | 2 +- ets2panda/lsp/include/get_safe_delete_info.h | 2 +- ets2panda/lsp/src/api.cpp | 4 +- ets2panda/lsp/src/get_safe_delete_info.cpp | 157 ++++++++----- .../unit/lsp/get_safe_delete_info_test.cpp | 222 +++++++++++++++--- 8 files changed, 302 insertions(+), 96 deletions(-) diff --git a/ets2panda/bindings/native/src/lsp.cpp b/ets2panda/bindings/native/src/lsp.cpp index 09ed313d06..3e3c0245c2 100644 --- a/ets2panda/bindings/native/src/lsp.cpp +++ b/ets2panda/bindings/native/src/lsp.cpp @@ -1217,13 +1217,12 @@ KNativePointer impl_getLocationFromList(KNativePointer listPtr) } TS_INTEROP_1(getLocationFromList, KNativePointer, KNativePointer) -KBoolean impl_getSafeDeleteInfo(KNativePointer context, KInt position, KStringPtr &path) +KBoolean impl_getSafeDeleteInfo(KNativePointer context, KInt position) { LSPAPI const *ctx = GetImpl(); - return static_cast( - ctx->getSafeDeleteInfo(reinterpret_cast(context), position, GetStringCopy(path))); + return static_cast(ctx->getSafeDeleteInfo(reinterpret_cast(context), position)); } -TS_INTEROP_3(getSafeDeleteInfo, KBoolean, KNativePointer, KInt, KStringPtr) +TS_INTEROP_2(getSafeDeleteInfo, KBoolean, KNativePointer, KInt) KNativePointer impl_toLineColumnOffset(KNativePointer context, KInt position) { diff --git a/ets2panda/bindings/src/Es2pandaNativeModule.ts b/ets2panda/bindings/src/Es2pandaNativeModule.ts index 07f5b0c4f4..9f7caa6ab6 100644 --- a/ets2panda/bindings/src/Es2pandaNativeModule.ts +++ b/ets2panda/bindings/src/Es2pandaNativeModule.ts @@ -728,7 +728,7 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } - _getSafeDeleteInfo(context: KNativePointer, position: KInt, path: String): boolean { + _getSafeDeleteInfo(context: KNativePointer, position: KInt): boolean { throw new Error('Not implemented'); } diff --git a/ets2panda/bindings/src/lsp_helper.ts b/ets2panda/bindings/src/lsp_helper.ts index fed04cb4a6..1731499f55 100644 --- a/ets2panda/bindings/src/lsp_helper.ts +++ b/ets2panda/bindings/src/lsp_helper.ts @@ -676,7 +676,7 @@ export class Lsp { lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_PARSED); PluginDriver.getInstance().runPluginHook(PluginHook.PARSED); lspDriverHelper.proceedToState(localCtx, Es2pandaContextState.ES2PANDA_STATE_CHECKED); - let result = global.es2panda._getSafeDeleteInfo(localCtx, position, path.resolve(__dirname, '../../..')); + let result = global.es2panda._getSafeDeleteInfo(localCtx, position); PluginDriver.getInstance().runPluginHook(PluginHook.CLEAN); lspDriverHelper.destroyContext(localCtx); lspDriverHelper.destroyConfig(localCfg); diff --git a/ets2panda/lsp/include/api.h b/ets2panda/lsp/include/api.h index 900e80c1a8..e29015558d 100644 --- a/ets2panda/lsp/include/api.h +++ b/ets2panda/lsp/include/api.h @@ -503,7 +503,7 @@ typedef struct LSPAPI { std::vector (*getClassHierarchiesImpl)(es2panda_Context *context, const char *fileName, size_t pos); - bool (*getSafeDeleteInfo)(es2panda_Context *context, size_t position, const char *path); + bool (*getSafeDeleteInfo)(es2panda_Context *context, size_t position); References (*getReferencesAtPosition)(es2panda_Context *context, DeclInfo *declInfo); es2panda_AstNode *(*getPrecedingToken)(es2panda_Context *context, const size_t pos); std::string (*getCurrentTokenValue)(es2panda_Context *context, size_t position); diff --git a/ets2panda/lsp/include/get_safe_delete_info.h b/ets2panda/lsp/include/get_safe_delete_info.h index 8988c5b14e..b1d9979cd6 100644 --- a/ets2panda/lsp/include/get_safe_delete_info.h +++ b/ets2panda/lsp/include/get_safe_delete_info.h @@ -17,6 +17,6 @@ #include "public/es2panda_lib.h" namespace ark::es2panda::lsp { // This function judge whether indicated part can be deleted. -bool GetSafeDeleteInfoImpl(es2panda_Context *context, size_t position, const std::string &path); +bool GetSafeDeleteInfoImpl(es2panda_Context *context, size_t position); } // namespace ark::es2panda::lsp #endif \ No newline at end of file diff --git a/ets2panda/lsp/src/api.cpp b/ets2panda/lsp/src/api.cpp index 117f6e4912..182700b017 100644 --- a/ets2panda/lsp/src/api.cpp +++ b/ets2panda/lsp/src/api.cpp @@ -112,9 +112,9 @@ std::vector GetClassHierarchies(es2panda_Context *contex return GetClassHierarchiesImpl(context, std::string(fileName), pos); } -bool GetSafeDeleteInfo(es2panda_Context *context, size_t position, const char *path) +bool GetSafeDeleteInfo(es2panda_Context *context, size_t position) { - return GetSafeDeleteInfoImpl(context, position, path); + return GetSafeDeleteInfoImpl(context, position); } References GetReferencesAtPosition(es2panda_Context *context, DeclInfo *declInfo) diff --git a/ets2panda/lsp/src/get_safe_delete_info.cpp b/ets2panda/lsp/src/get_safe_delete_info.cpp index b21f5d949d..ddeeb93dde 100644 --- a/ets2panda/lsp/src/get_safe_delete_info.cpp +++ b/ets2panda/lsp/src/get_safe_delete_info.cpp @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include #include #include @@ -22,89 +23,129 @@ #include "public/public.h" #include "references.h" +namespace { +constexpr size_t BUILTIN_TYPE_COUNT = 9; +constexpr std::array BUILTIN_TYPES = { + "Number", "String", "Boolean", "void", "BigInt", "Never", "undefined", "null", "Object"}; +} // namespace + namespace ark::es2panda::lsp { -bool NodeIsEligibleForSafeDelete(ir::AstNode *astNode) + +bool IsBuiltinTypeReference(ir::AstNode *node) { - if (astNode == nullptr) { + if (node == nullptr || node->Type() != ir::AstNodeType::IDENTIFIER) { return false; } - switch (astNode->Type()) { - case ir::AstNodeType::THIS_EXPRESSION: - case ir::AstNodeType::TS_CONSTRUCTOR_TYPE: - case ir::AstNodeType::IDENTIFIER: - return true; - default: - return false; + auto *parent = node->Parent(); + while (parent != nullptr) { + if (parent->Type() == ir::AstNodeType::ETS_TYPE_REFERENCE_PART || + parent->Type() == ir::AstNodeType::ETS_TYPE_REFERENCE) { + std::string nameStr(node->AsIdentifier()->Name()); + auto it = + std::find_if(BUILTIN_TYPES.begin(), BUILTIN_TYPES.end(), [&](const char *s) { return nameStr == s; }); + if (it != BUILTIN_TYPES.end()) { + return true; + } + } + parent = parent->Parent(); } + return false; } -DeclInfo GetDeclInfoCur(es2panda_Context *context, size_t position) +bool IsDeletableDecl(ir::AstNode *node) { - DeclInfo result; - if (context == nullptr) { - return result; - } - auto astNode = GetTouchingToken(context, position, false); - auto declInfo = GetDeclInfoImpl(astNode); - result.fileName = std::get<0>(declInfo); - result.fileText = std::get<1>(declInfo); - return result; + return node->IsFunctionDeclaration() || node->IsVariableDeclarator() || node->IsClassProperty() || + node->Type() == ir::AstNodeType::METHOD_DEFINITION || node->Type() == ir::AstNodeType::CLASS_DECLARATION || + node->IsTSTypeParameterDeclaration() || node->IsImportDefaultSpecifier() || + node->Type() == ir::AstNodeType::ETS_TYPE_REFERENCE_PART || node->IsCallExpression() || + node->IsETSImportDeclaration() || node->IsImportSpecifier() || node->IsBinaryExpression() || + node->IsTSInterfaceDeclaration() || node->IsETSTypeReferencePart() || node->IsImportNamespaceSpecifier() || + node->IsTSTypeAliasDeclaration() || node->IsExpressionStatement() || node->IsMemberExpression() || + node->IsTypeofExpression(); } -// This function judge whether type is standard library file defined type. -bool IsLibrayFile(ir::AstNode *node, const std::string &path) +ir::AstNode *FindNearestDeletableDecl(ir::AstNode *node) { - auto declInfo = GetDeclInfoImpl(node); - auto fileName = std::get<0>(declInfo); - if (fileName.empty()) { - return false; - } - if (fileName.find("ets1.2") != std::string::npos) { - return fileName.find(path) != std::string::npos; + ir::AstNode *cur = node; + while (cur != nullptr) { + if (IsDeletableDecl(cur)) { + return cur; + } + cur = cur->Parent(); } - return true; + return nullptr; } -bool IsAllowToDeleteDeclaration(ir::AstNode *node, const std::string &path) +std::string NormalizeFilePath(const std::string &filePath) { - return (node->IsETSModule() && node->AsETSModule()->IsNamespace()) || node->IsTSTypeParameterDeclaration() || - (node->Type() == ir::AstNodeType::IDENTIFIER && node->Parent()->IsTSModuleDeclaration()) || - IsLibrayFile(node, path) || node->IsArrowFunctionExpression() || node->IsETSStringLiteralType(); + std::string normPath = filePath; + std::transform(normPath.begin(), normPath.end(), normPath.begin(), ::tolower); + std::replace(normPath.begin(), normPath.end(), '\\', '/'); + return normPath; } -bool GetSafeDeleteInfoForNode(es2panda_Context *context, size_t position, const std::string &path) +/** + * Distinguish a namespace from a class by checking whether the class body contains only the $init$ method and has + * no constructor + */ +bool IsNamespaceClass(ir::AstNode *astNode) { - auto declInfoData = GetDeclInfoCur(context, position); - DeclInfoType declInfo = {declInfoData.fileName, declInfoData.fileText}; - std::vector nodes; - - auto ctx = reinterpret_cast(context); - if (ctx->parserProgram == nullptr || ctx->parserProgram->Ast() == nullptr) { + if (astNode->Type() != ir::AstNodeType::CLASS_DECLARATION) { return false; } - auto astNode = reinterpret_cast(ctx->parserProgram->Ast()); - astNode->IterateRecursively([declInfo, &nodes](ir::AstNode *child) { - auto info = GetDeclInfoImpl(child); - if (info == declInfo) { - nodes.push_back(child); - } - }); - std::vector filterNodes; - std::for_each(nodes.begin(), nodes.end(), [&filterNodes, path](ir::AstNode *node) { - if (IsAllowToDeleteDeclaration(node, path)) { - filterNodes.push_back(node); + auto *classDecl = static_cast(astNode); + const auto &body = classDecl->Definition()->Body(); + bool hasConstructor = false; + bool onlyInit = true; + for (auto *member : body) { + if (member->Type() == ir::AstNodeType::METHOD_DEFINITION) { + auto *method = static_cast(member); + util::StringView keyName = method->Key()->AsIdentifier()->Name(); + if (keyName == "constructor") { + hasConstructor = true; + } + if (keyName != "_$init$_") { + onlyInit = false; + } } - }); - - return !filterNodes.empty(); + } + return !hasConstructor && onlyInit; } -bool GetSafeDeleteInfoImpl(es2panda_Context *context, size_t position, const std::string &path) +bool GetSafeDeleteInfoImpl(es2panda_Context *context, size_t position) { auto astNode = GetTouchingToken(context, position, false); - if (NodeIsEligibleForSafeDelete(astNode)) { - return GetSafeDeleteInfoForNode(context, position, path); + if (astNode == nullptr) { + return false; } - return false; + + auto declInfo = GetDeclInfoImpl(astNode); + auto fileName = std::get<0>(declInfo); + std::string normFileName = NormalizeFilePath(fileName); + if (!normFileName.empty() && normFileName.find("ets1.2/build-tools/ets2panda/lib/stdlib") != std::string::npos) { + return false; + } + if (!normFileName.empty() && normFileName.find("/sdk/") != std::string::npos) { + return false; + } + + if (IsBuiltinTypeReference(astNode)) { + return false; + } + + astNode = FindNearestDeletableDecl(astNode); + if (astNode == nullptr) { + return false; + } + + if (IsNamespaceClass(astNode)) { + return false; + } + + if (astNode->IsTSTypeParameterDeclaration()) { + return false; + } + + return true; } } // namespace ark::es2panda::lsp diff --git a/ets2panda/test/unit/lsp/get_safe_delete_info_test.cpp b/ets2panda/test/unit/lsp/get_safe_delete_info_test.cpp index ac249130b6..6ffb8d648e 100644 --- a/ets2panda/test/unit/lsp/get_safe_delete_info_test.cpp +++ b/ets2panda/test/unit/lsp/get_safe_delete_info_test.cpp @@ -22,31 +22,29 @@ #include "lsp/include/api.h" #include "public/es2panda_lib.h" -using ark::es2panda::lsp::Initializer; namespace { +using ark::es2panda::lsp::Initializer; class LspGetSafeDeleteInfoTest : public LSPAPITests {}; TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase1) { - using ark::es2panda::public_lib::Context; + std::vector files = {"get-safe-delete-info-case1.ets"}; + std::vector texts = {R"(function a(): Number { return 1; } a())"}; + auto filePaths = CreateTempFile(files, texts); - std::vector fileNames = {"firstFile.ets", "secondFile.ets"}; - std::vector fileContents = { - "const greet = (name: string) => {\n" - "return 'Hello, ${name}!';\n};\n" - "export default greet;\n", - "import greet from \"./firstFile.ets\""}; + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); - auto filePaths = CreateTempFile(fileNames, fileContents); - const int fileIndex = 1; + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 16; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); + ASSERT_EQ(result, false); - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext(filePaths[fileIndex].c_str(), ES2PANDA_STATE_CHECKED); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - size_t const offset = 7; - bool result = lspApi->getSafeDeleteInfo(ctx, offset, ""); + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offsetT2 = 35; + result = lspApi->getSafeDeleteInfo(ctx, offsetT2); ASSERT_EQ(result, true); initializer.DestroyContext(ctx); @@ -54,27 +52,195 @@ TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase1) TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase2) { - Initializer initializer = Initializer(); - es2panda_Context *ctx = - initializer.CreateContext("get-safe-delete-info-case2.ets", ES2PANDA_STATE_CHECKED, "class A {\n\n}"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + std::vector files = {"get-safe-delete-info-case2.ets"}; + std::vector texts = {R"(export const PI = 3.1415926;)"}; + auto filePaths = CreateTempFile(files, texts); + + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); LSPAPI const *lspApi = GetImpl(); - size_t const offset = 8; - bool result = lspApi->getSafeDeleteInfo(ctx, offset, ""); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 14; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); ASSERT_EQ(result, true); + initializer.DestroyContext(ctx); } TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase3) { - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("get-safe-delete-info-case3.ets", ES2PANDA_STATE_CHECKED, - "let arr: Array;\n"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + std::vector files = {"get-safe-delete-info-case3.ets"}; + std::vector texts = {R"( + function setAlarmDefaultTime(alarmItem?: AlarmItem) { + let hour; + let minute; + })"}; + auto filePaths = CreateTempFile(files, texts); + + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); LSPAPI const *lspApi = GetImpl(); - size_t const offset = 10; - bool result = lspApi->getSafeDeleteInfo(ctx, offset, "stdlib/escompat/Array.ets"); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 71; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); ASSERT_EQ(result, true); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offsetT2 = 89; + result = lspApi->getSafeDeleteInfo(ctx, offsetT2); + ASSERT_EQ(result, true); + + initializer.DestroyContext(ctx); +} + +TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase4) +{ + std::vector files = {"get-safe-delete-info-namespace.ets"}; + std::vector texts = {R"( + namespace Foo {} + class Foo2 {} + )"}; + auto filePaths = CreateTempFile(files, texts); + + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 14; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); + ASSERT_EQ(result, false); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offsetT2 = 31; + result = lspApi->getSafeDeleteInfo(ctx, offsetT2); + ASSERT_EQ(result, true); + + initializer.DestroyContext(ctx); +} + +TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase5) +{ + std::vector files = {"get-safe-delete-info-typeparam.ets"}; + std::vector texts = {R"( + function foo(a: T) { return a; } + )"}; + auto filePaths = CreateTempFile(files, texts); + + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 17; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); + ASSERT_EQ(result, false); + + initializer.DestroyContext(ctx); +} + +TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase6) +{ + std::vector files = {"get-safe-delete-info-import.ets"}; + std::vector texts = {R"(import { foo } from "./mod";)"}; + auto filePaths = CreateTempFile(files, texts); + + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 9; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); + ASSERT_EQ(result, true); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offsetT2 = 23; + result = lspApi->getSafeDeleteInfo(ctx, offsetT2); + ASSERT_EQ(result, true); + + initializer.DestroyContext(ctx); +} + +TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase7) +{ + std::vector files = {"get-safe-delete-info-arrow.ets"}; + std::vector texts = {R"( + export const calcDistance = (time: number) => { + const ret = 0.5 * time * time; + return ret; + }; + )"}; + auto filePaths = CreateTempFile(files, texts); + + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 28; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); + ASSERT_EQ(result, true); + + initializer.DestroyContext(ctx); +} + +TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase8) +{ + std::vector files = {"get-safe-delete-info-interface.ets"}; + std::vector texts = {R"( + export interface VideoPlayer { + prepare(): Promise; + } + + function bar(parameter: VideoPlayer) { + parameter.prepare(); + } + )"}; + auto filePaths = CreateTempFile(files, texts); + + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 31; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); + ASSERT_EQ(result, true); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offsetT2 = 143; + result = lspApi->getSafeDeleteInfo(ctx, offsetT2); + ASSERT_EQ(result, true); + + initializer.DestroyContext(ctx); +} + +TEST_F(LspGetSafeDeleteInfoTest, GetSafeDeleteInfoCase9) +{ + std::vector files = {"get-safe-delete-info-importdefault.ets"}; + std::vector texts = {R"( + import BuildProfile from 'BuildProfile'; + BuildProfile.bundleName + )"}; + auto filePaths = CreateTempFile(files, texts); + + Initializer initializer; + es2panda_Context *ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offset = 15; + bool result = lspApi->getSafeDeleteInfo(ctx, offset); + ASSERT_EQ(result, true); + + // NOLINTNEXTLINE(readability-identifier-naming,-warnings-as-errors) + constexpr size_t offsetT2 = 52; + result = lspApi->getSafeDeleteInfo(ctx, offsetT2); + ASSERT_EQ(result, true); + initializer.DestroyContext(ctx); } } // namespace -- Gitee From 291cbc6ebde238e267957728e77c226e83000871 Mon Sep 17 00:00:00 2001 From: leo9001 Date: Tue, 17 Jun 2025 16:26:29 +0800 Subject: [PATCH 061/145] support GetAliasScriptElementKind support GetAliasScriptElementKind Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICFTA0 Signed-off-by: leo9001 --- ets2panda/bindings/src/lspNode.ts | 3 +- ets2panda/lsp/include/completions.h | 3 +- ets2panda/lsp/src/script_element_kind.cpp | 49 +++- .../unit/lsp/script_element_kind_test.cpp | 233 +++++++++++++++++- 4 files changed, 269 insertions(+), 19 deletions(-) diff --git a/ets2panda/bindings/src/lspNode.ts b/ets2panda/bindings/src/lspNode.ts index 9f9319e52b..ff74913d6a 100644 --- a/ets2panda/bindings/src/lspNode.ts +++ b/ets2panda/bindings/src/lspNode.ts @@ -489,7 +489,8 @@ export enum LspCompletionEntryKind { STRUCT = 22, EVENT = 23, OPERATOR = 24, - TYPE_PARAMETER = 25 + TYPE_PARAMETER = 25, + ALIAS_TYPE = 26 } export enum ResolutionStatus { diff --git a/ets2panda/lsp/include/completions.h b/ets2panda/lsp/include/completions.h index 1f5ddc21e2..2aa0f39252 100644 --- a/ets2panda/lsp/include/completions.h +++ b/ets2panda/lsp/include/completions.h @@ -52,7 +52,8 @@ enum class CompletionEntryKind { STRUCT = 22, EVENT = 23, OPERATOR = 24, - TYPE_PARAMETER = 25 + TYPE_PARAMETER = 25, + ALIAS_TYPE = 26 }; namespace sort_text { diff --git a/ets2panda/lsp/src/script_element_kind.cpp b/ets2panda/lsp/src/script_element_kind.cpp index eba06f4421..f31e8d5e06 100644 --- a/ets2panda/lsp/src/script_element_kind.cpp +++ b/ets2panda/lsp/src/script_element_kind.cpp @@ -30,7 +30,6 @@ std::tuple GetTargetTokenKindIfETSType(ir::AstNodeTyp return std::make_tuple(true, CompletionEntryKind::VALUE); case ir::AstNodeType::ETS_PRIMITIVE_TYPE: case ir::AstNodeType::ETS_CLASS_LITERAL: - case ir::AstNodeType::ETS_UNION_TYPE: case ir::AstNodeType::ETS_KEYOF_TYPE: return std::make_tuple(true, CompletionEntryKind::KEYWORD); case ir::AstNodeType::ETS_NEW_ARRAY_INSTANCE_EXPRESSION: @@ -50,10 +49,12 @@ std::tuple GetTargetTokenKindIfETSType(ir::AstNodeTyp return std::make_tuple(true, CompletionEntryKind::REFERENCE); case ir::AstNodeType::ETS_WILDCARD_TYPE: return std::make_tuple(true, CompletionEntryKind::TEXT); + case ir::AstNodeType::ETS_UNION_TYPE: + return std::make_tuple(true, CompletionEntryKind::TYPE_PARAMETER); default: break; } - return std::make_tuple(false, CompletionEntryKind::TEXT); + return std::make_tuple(false, CompletionEntryKind::ALIAS_TYPE); } bool IsTSParameterKind(ir::AstNodeType type) @@ -97,7 +98,7 @@ bool IsTSMoudleKind(ir::AstNodeType type) std::tuple GetTargetTokenKindIfTSType(ir::AstNodeType type) { - auto reuslt = std::make_tuple(false, CompletionEntryKind::TEXT); + auto reuslt = std::make_tuple(false, CompletionEntryKind::ALIAS_TYPE); if (IsValidAncestorType(type)) { reuslt = std::make_tuple(true, CompletionEntryKind::KEYWORD); } else if (IsTSParameterKind(type)) { @@ -251,7 +252,7 @@ bool IsModule(ir::AstNodeType type) CompletionEntryKind GetTargetTokenKind(const ir::AstNode *node) { - CompletionEntryKind normalResult = CompletionEntryKind::TEXT; + CompletionEntryKind normalResult = CompletionEntryKind::ALIAS_TYPE; if (node == nullptr) { return normalResult; } @@ -300,13 +301,47 @@ CompletionEntryKind GetTargetTokenKind(const ir::AstNode *node) return normalResult; } +const ir::TSTypeAliasDeclaration *GetAliasDeclFromCurrentToken(const ir::AstNode *node) +{ + if (node == nullptr) { + return nullptr; + } + const ir::TSTypeAliasDeclaration *aliasDecl = nullptr; + if (node->IsTSTypeAliasDeclaration()) { + aliasDecl = node->AsTSTypeAliasDeclaration(); + } else if (node->IsIdentifier()) { + auto decl = compiler::DeclarationFromIdentifier(node->AsIdentifier()); + if (decl == nullptr) { + return nullptr; + } + aliasDecl = decl->AsTSTypeAliasDeclaration(); + } + return aliasDecl; +} + CompletionEntryKind GetAliasScriptElementKindImpl(es2panda_Context *context, size_t position) { auto touchingToken = GetTouchingToken(context, position, false); - if (touchingToken == nullptr) { + auto aliasDecl = GetAliasDeclFromCurrentToken(touchingToken); + if (aliasDecl == nullptr) { return CompletionEntryKind::TEXT; } - auto result = GetTargetTokenKind(touchingToken); - return result; + auto typeAnnotation = aliasDecl->TypeAnnotation(); + if (typeAnnotation == nullptr) { + return CompletionEntryKind::ALIAS_TYPE; + } + if (typeAnnotation->IsETSTypeReference()) { + auto part = typeAnnotation->AsETSTypeReference()->Part()->AsETSTypeReferencePart(); + if (part == nullptr) { + return CompletionEntryKind::ALIAS_TYPE; + } + auto targetIdent = part->GetIdent(); + auto decl = compiler::DeclarationFromIdentifier(targetIdent); + if (compiler::ClassDefinitionIsEnumTransformed(decl)) { + return CompletionEntryKind::ENUM; + } + return GetTargetTokenKind(decl); + } + return GetTargetTokenKind(typeAnnotation); } } // namespace ark::es2panda::lsp diff --git a/ets2panda/test/unit/lsp/script_element_kind_test.cpp b/ets2panda/test/unit/lsp/script_element_kind_test.cpp index dd461cd45d..6e41c0ed9e 100644 --- a/ets2panda/test/unit/lsp/script_element_kind_test.cpp +++ b/ets2panda/test/unit/lsp/script_element_kind_test.cpp @@ -25,7 +25,7 @@ namespace { class LspScriptElementKindTests : public LSPAPITests {}; -TEST_F(LSPAPITests, GetAliasScriptElementKind_1) +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_1) { LSPAPI const *lspApi = GetImpl(); ASSERT_TRUE(lspApi != nullptr); @@ -41,13 +41,13 @@ TEST_F(LSPAPITests, GetAliasScriptElementKind_1) size_t const stringLiteralOffset = 96; // 96: position of first 'o' in 'foo' auto result = lspApi->getAliasScriptElementKind(context, numberLiteralOffset); - ASSERT_EQ(result, CompletionEntryKind::VALUE); // Literal is VALUE + ASSERT_EQ(result, CompletionEntryKind::TEXT); // Literal is VALUE result = lspApi->getAliasScriptElementKind(context, stringLiteralOffset); - ASSERT_EQ(result, CompletionEntryKind::VALUE); + ASSERT_EQ(result, CompletionEntryKind::TEXT); initializer.DestroyContext(context); } -TEST_F(LSPAPITests, GetAliasScriptElementKind_2) +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_2) { LSPAPI const *lspApi = GetImpl(); Initializer initializer = Initializer(); @@ -61,13 +61,14 @@ TEST_F(LSPAPITests, GetAliasScriptElementKind_2) size_t const stringLiteralOffset = 50; // 50: position of 'h' in 'hello' ASSERT_EQ(lspApi->getAliasScriptElementKind(context, startOfFile), CompletionEntryKind::TEXT); - ASSERT_EQ(lspApi->getAliasScriptElementKind(context, firstleftCurlyBrance), CompletionEntryKind::SNIPPET); - ASSERT_EQ(lspApi->getAliasScriptElementKind(context, numberLiteralOffset), CompletionEntryKind::VALUE); - ASSERT_EQ(lspApi->getAliasScriptElementKind(context, stringLiteralOffset), CompletionEntryKind::VALUE); + ASSERT_EQ(lspApi->getAliasScriptElementKind(context, firstleftCurlyBrance), CompletionEntryKind::TEXT); + ASSERT_EQ(lspApi->getAliasScriptElementKind(context, numberLiteralOffset), CompletionEntryKind::TEXT); + ASSERT_EQ(lspApi->getAliasScriptElementKind(context, stringLiteralOffset), CompletionEntryKind::TEXT); + initializer.DestroyContext(context); } -TEST_F(LSPAPITests, GetAliasScriptElementKind_3) +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_3) { LSPAPI const *lspApi = GetImpl(); Initializer initializer = Initializer(); @@ -81,9 +82,221 @@ let notAssigned: undefined = undefined;)"; size_t const etsNullType = 25; // 25: position of the second let. size_t const undefinedLiteral = 54; // 54: position of the second undefined. - ASSERT_EQ(lspApi->getAliasScriptElementKind(context, nullLiteral), CompletionEntryKind::VALUE); + ASSERT_EQ(lspApi->getAliasScriptElementKind(context, nullLiteral), CompletionEntryKind::TEXT); ASSERT_EQ(lspApi->getAliasScriptElementKind(context, etsNullType), CompletionEntryKind::TEXT); - ASSERT_EQ(lspApi->getAliasScriptElementKind(context, undefinedLiteral), CompletionEntryKind::VALUE); + ASSERT_EQ(lspApi->getAliasScriptElementKind(context, undefinedLiteral), CompletionEntryKind::TEXT); + + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_4) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(class Person { + private body_ : string = '1'; +} + +type alias/*1*/ = Person;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_4.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::CLASS); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_5) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"( +interface MockInterface { + parameter1: number; + parameter2: string; + parameter3: boolean; +} + +type alias/*1*/ = MockInterface;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_5.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::INTERFACE); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_6) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"( +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + + build() { + RelativeContainer() { + Text(this.message) + .id('HelloWorld') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(() => { + this.message = 'Welcome'; + }) + } + .height('100%') + .width('100%') + } +} + +type alias/*1*/ = Index;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_6.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::CLASS); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_7) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(type alias/*1*/ = '2';)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_7.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::VALUE); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_8) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(type alias/*1*/ = undefinedType11;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_8.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::ALIAS_TYPE); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_9) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(type TestUnion/*1*/ = string | number;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_9.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::TYPE_PARAMETER); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_10) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(type Callback/*1*/ = (result: string) => void;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_10.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::FUNCTION); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_11) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(type Callback/*1*/ = () => {};)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_11.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::FUNCTION); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_12) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + const std::string text = R"(class Person { + private body_ : string = '1'; + private body_ : string = 'ad'; +} +type alias/*1*/ = Person;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_12.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::CLASS); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_13) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + + const std::string text = R"(type TestA/*1*/ = Array>;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_13.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::CLASS); + initializer.DestroyContext(context); +} + +TEST_F(LspScriptElementKindTests, GetAliasScriptElementKind_14) +{ + LSPAPI const *lspApi = GetImpl(); + ASSERT_TRUE(lspApi != nullptr); + + const std::string text = R"(type TestB/*1*/ = string | Array>;)"; + + auto pos = text.find("/*1*/"); + ASSERT_NE(pos, std::string::npos); + Initializer initializer = Initializer(); + auto context = initializer.CreateContext("aliasScriptElementKind_14.ets", ES2PANDA_STATE_CHECKED, text.c_str()); + auto result = lspApi->getAliasScriptElementKind(context, pos); + EXPECT_EQ(result, CompletionEntryKind::TYPE_PARAMETER); initializer.DestroyContext(context); } -- Gitee From 580d19e57bbb0ee9d898bd72a3a9adc00b5b8f00 Mon Sep 17 00:00:00 2001 From: leo9001 Date: Thu, 19 Jun 2025 11:27:39 +0800 Subject: [PATCH 062/145] support getApplicableRefactors chain support getApplicableRefactors chain Issue:https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICG9YO Signed-off-by: leo9001 --- ets2panda/lsp/src/refactors/convert_chain.cpp | 38 +++++++++++-------- .../unit/lsp/refactors_convert_chain_test.cpp | 4 +- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/ets2panda/lsp/src/refactors/convert_chain.cpp b/ets2panda/lsp/src/refactors/convert_chain.cpp index 1d76ecaee2..6923a02fe9 100644 --- a/ets2panda/lsp/src/refactors/convert_chain.cpp +++ b/ets2panda/lsp/src/refactors/convert_chain.cpp @@ -17,27 +17,26 @@ #include "refactors/convert_chain.h" #include "refactor_provider.h" #include "internal_api.h" +#include "public/public.h" namespace ark::es2panda::lsp { - -ark::es2panda::ir::AstNode *FindType(ark::es2panda::ir::AstNode *node); - ConvertChainRefactor::ConvertChainRefactor() { AddKind(std::string(TO_NAMED_CHAIN_ACTION.kind)); } -ark::es2panda::ir::AstNode *FindType(ark::es2panda::ir::AstNode *node) +ark::es2panda::ir::AstNode *FindETSNullType(ark::es2panda::ir::AstNode *node, es2panda_Context *context) { - if ((node != nullptr) && (node->Parent() != nullptr)) { - if (node->Parent()->IsExpression()) { - return node; - } - auto cb = [](ir::AstNode *ancestorNode) { return ancestorNode->IsConditionalExpression(); }; - node = FindAncestor(node, cb); - return node; - } - return node; + auto consequent = node->AsConditionalExpression()->Consequent(); + auto nodeproperty = consequent->AsMemberExpression()->Property(); + auto ctx = reinterpret_cast(context); + auto targetNode = ctx->parserProgram->Ast()->FindChild([&nodeproperty](ir::AstNode *childNode) { + return childNode->IsScriptFunction() && + childNode->AsScriptFunction()->Id()->AsIdentifier()->Name() == nodeproperty->AsIdentifier()->Name(); + }); + auto etc = targetNode->FindChild([](ir::AstNode *childNode) { return childNode->IsETSNullType(); }); + + return etc; } ApplicableRefactorInfo ConvertChainRefactor::GetAvailableActions(const RefactorContext &refContext) const @@ -55,8 +54,17 @@ ApplicableRefactorInfo ConvertChainRefactor::GetAvailableActions(const RefactorC return res; } - auto nodedec1 = FindType(node); - if (nodedec1 != nullptr && (nodedec1->IsConditionalExpression() || nodedec1->IsExpression())) { + auto parent = node->Parent(); + if (parent == nullptr) { + return res; + } + if (parent->IsExpression()) { + if (parent->IsConditionalExpression()) { + auto etc = FindETSNullType(parent, context); + if (etc != nullptr) { + return res; + } + } res.name = refactor_name::CONVERT_CHAIN_REFACTOR_NAME; res.description = refactor_description::CONVERT_CHAIN_REFACTOR_DESC; res.action.kind = std::string(TO_NAMED_CHAIN_ACTION.kind); diff --git a/ets2panda/test/unit/lsp/refactors_convert_chain_test.cpp b/ets2panda/test/unit/lsp/refactors_convert_chain_test.cpp index 67e51357ec..514202b21a 100644 --- a/ets2panda/test/unit/lsp/refactors_convert_chain_test.cpp +++ b/ets2panda/test/unit/lsp/refactors_convert_chain_test.cpp @@ -80,10 +80,8 @@ foo.bar.baz : "whenFalse";/*2*/ refactorContext.kind = std::string(TO_NAMED_CHAIN_KIND); refactorContext.span.pos = pos + REFACTOR_CHAIN_POSITION_OFFSET; auto result = GetApplicableRefactorsImpl(&refactorContext); - initializer.DestroyContext(ctx); - ASSERT_EQ(1, result.size()); - ASSERT_EQ(std::string(TO_NAMED_CHAIN_NAME), result[0].action.name); + ASSERT_EQ(0, result.size()); } TEST_F(LspChainRefTests, ConvertChainRefactor3) -- Gitee From 6da091a7335c50f3ee17aae9fd3543b9a284ac84 Mon Sep 17 00:00:00 2001 From: Zhelyapov Aleksey Date: Thu, 3 Jul 2025 09:04:49 +0300 Subject: [PATCH 063/145] Implemented lambda spread param type inference Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJPDR Signed-off-by: Zhelyapov Aleksey --- ets2panda/checker/ets/function.cpp | 12 ++++++--- .../compiler/lowering/ets/lambdaLowering.cpp | 10 +++++--- .../ast/compiler/ets/restvar_type_infer.ets | 2 ++ .../ets/FixedArray/unexpected_token_31.ets | 1 + .../annotationUsage_bad_param07.ets | 1 + .../ast/parser/ets/unexpected_token_31.ets | 1 + .../ets/lambdaRestParamTypeInference.ets | 25 +++++++++++++++++++ 7 files changed, 45 insertions(+), 7 deletions(-) create mode 100644 ets2panda/test/runtime/ets/lambdaRestParamTypeInference.ets diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 432e97432f..94cbc1c8e1 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1435,17 +1435,21 @@ SignatureInfo *ETSChecker::ComposeSignatureInfo(ir::TSTypeParameterDeclaration * if (!params.empty()) { if (auto param = params.back()->AsETSParameterExpression(); param->IsRestParameter()) { - if (param->TypeAnnotation() == nullptr) { // #23134 - ES2PANDA_ASSERT(IsAnyError()); + checker::Type *restParamType = nullptr; + if (param->TypeAnnotation() != nullptr) { + restParamType = param->RestParameter()->TypeAnnotation()->GetType(this); + } else if (param->Ident()->TsType() != nullptr) { + restParamType = param->Ident()->TsType(); + } else { + ES2PANDA_ASSERT(IsAnyError()); // #23134 return nullptr; } - auto restParamType = param->RestParameter()->TypeAnnotation()->GetType(this); if (!restParamType->IsETSTupleType() && !restParamType->IsETSArrayType() && !restParamType->IsETSResizableArrayType()) { LogError(diagnostic::ONLY_ARRAY_OR_TUPLE_FOR_REST, {}, param->Start()); return nullptr; } - signatureInfo->restVar = SetupSignatureParameter(param, param->TypeAnnotation()->GetType(this)); + signatureInfo->restVar = SetupSignatureParameter(param, restParamType); ES2PANDA_ASSERT(signatureInfo->restVar != nullptr); } } diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index c513801d30..8231a17c35 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -190,15 +190,19 @@ ParamsAndVarMap CreateLambdaCalleeParameters(public_lib::Context *ctx, ir::Arrow newParam->SetOptional(false); newParamType = checker->CreateETSUnionType({newParamType, checker->GlobalETSUndefinedType()}); } - newParam->Ident()->SetTsTypeAnnotation(allocator->New(newParamType, allocator)); - newParam->Ident()->TypeAnnotation()->SetParent(newParam->Ident()); - newParam->Ident()->SetVariable(nullptr); // Remove the cloned variable. + newParam->SetTypeAnnotation(allocator->New(newParamType, allocator)); auto *var = varBinder->AddParamDecl(newParam); var->SetTsType(newParamType); var->SetScope(paramScope); newParam->SetVariable(var); newParam->SetTsType(newParamType); newParam->Ident()->SetTsType(newParamType); + if (newParam->IsRestParameter()) { + newParam->TypeAnnotation()->SetParent(newParam->RestParameter()); + newParam->RestParameter()->SetTsType(newParamType); + } else { + newParam->TypeAnnotation()->SetParent(newParam->Ident()); + } resParams.push_back(newParam); varMap[oldParam->AsETSParameterExpression()->Variable()] = var; diff --git a/ets2panda/test/ast/compiler/ets/restvar_type_infer.ets b/ets2panda/test/ast/compiler/ets/restvar_type_infer.ets index 578567a54a..42f7062c07 100644 --- a/ets2panda/test/ast/compiler/ets/restvar_type_infer.ets +++ b/ets2panda/test/ast/compiler/ets/restvar_type_infer.ets @@ -19,4 +19,6 @@ function main() { } /* @@? 17:16 Error TypeError: The type of parameter 'args' cannot be inferred */ +/* @@? 17:16 Error SyntaxError: Rest parameter should be either array or tuple type. */ /* @@? 18:26 Error TypeError: The type of parameter 'args' cannot be inferred */ +/* @@? 18:26 Error SyntaxError: Rest parameter should be either array or tuple type. */ 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 e53b749a07..37de6fe998 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_31.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/unexpected_token_31.ets @@ -18,6 +18,7 @@ function foo(...^number: FixedArray): int { } /* @@? 16:10 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 16:14 Error SyntaxError: Rest parameter should be either array or tuple type. */ /* @@? 16:17 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 16:18 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 16:18 Error SyntaxError: Rest parameter must be the last formal parameter. */ diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets index 93b781dc7b..439897e7a6 100644 --- a/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotationUsage_bad_param07.ets @@ -24,3 +24,4 @@ function foo(@MyAnno ...a/* @@ label */){} /* @@@ label Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 22:15 Error TypeError: The required field 'testProperty1' must be specified. Fields without default values cannot be omitted. */ /* @@? 22:22 Error TypeError: The type of parameter 'a' cannot be inferred */ +/* @@? 22:22 Error SyntaxError: Rest parameter should be either array or tuple type. */ diff --git a/ets2panda/test/ast/parser/ets/unexpected_token_31.ets b/ets2panda/test/ast/parser/ets/unexpected_token_31.ets index 13151518a2..01374410c3 100644 --- a/ets2panda/test/ast/parser/ets/unexpected_token_31.ets +++ b/ets2panda/test/ast/parser/ets/unexpected_token_31.ets @@ -18,6 +18,7 @@ function foo(...^number: int[]): int { } /* @@? 16:10 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 16:14 Error SyntaxError: Rest parameter should be either array or tuple type. */ /* @@? 16:17 Error SyntaxError: Unexpected token, expected an identifier. */ /* @@? 16:18 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 16:18 Error SyntaxError: Rest parameter must be the last formal parameter. */ diff --git a/ets2panda/test/runtime/ets/lambdaRestParamTypeInference.ets b/ets2panda/test/runtime/ets/lambdaRestParamTypeInference.ets new file mode 100644 index 0000000000..5d9adf75e2 --- /dev/null +++ b/ets2panda/test/runtime/ets/lambdaRestParamTypeInference.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. + */ + +const sum1: ((...numbers: number[]) => number) = ((...numbers) => { + return numbers.reduce((a, b) => a + b, 0) +}) + +const sum2: ((n: int, ...numbers: number[]) => number) = ((n, ...numbers) => { + return numbers.reduce((a, b) => a + b, 0) +}) + +arktest.assertEQ(sum1(1,2,3,4), 10) +arktest.assertEQ(sum2(1,2,3,4), 9) -- Gitee From 35de2c34b9054e1115f7b0c5daa0b38174fd8d36 Mon Sep 17 00:00:00 2001 From: ekkoruse Date: Tue, 24 Jun 2025 00:08:31 +0800 Subject: [PATCH 064/145] Compile simultaneously support compile simultaneously Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICDR65?from=project-issue Change-Id: I4c3b7fc48469c2cc1cc6febb1113f4467a2a2eb6 Signed-off-by: ekkoruse Signed-off-by: huyunhui1 --- ets2panda/checker/ETSchecker.cpp | 6 + ets2panda/checker/ets/helpers.cpp | 5 +- ets2panda/checker/ets/object.cpp | 6 +- ets2panda/checker/ets/typeCheckingHelpers.cpp | 11 + ets2panda/checker/ets/utilityTypeHandlers.cpp | 6 +- ets2panda/compiler/core/ETSemitter.cpp | 47 +++- ets2panda/compiler/core/compilerImpl.cpp | 13 +- ets2panda/compiler/core/emitter.cpp | 6 +- .../compiler/lowering/ets/lambdaLowering.cpp | 3 +- ets2panda/compiler/lowering/phase.cpp | 70 +++--- ets2panda/compiler/scripts/signatures.yaml | 6 + ets2panda/driver/build_system/package.json | 11 +- .../build_system/src/build/build_mode.ts | 2 +- ets2panda/es2panda.h | 1 + ets2panda/parser/ETSparser.cpp | 50 ++++- ets2panda/parser/ETSparser.h | 3 + ets2panda/parser/parserImpl.h | 15 ++ ets2panda/parser/program/program.cpp | 7 + ets2panda/parser/program/program.h | 10 +- ets2panda/public/es2panda_lib.cpp | 108 +++++++++- ets2panda/public/es2panda_lib.h | 2 + ets2panda/public/es2panda_lib.idl.erb | 1 + ets2panda/public/public.h | 34 ++- .../ets/import_export/eitest_export_A_1.ets | 16 ++ .../ets/import_export/eitest_export_A_2.ets | 18 ++ .../ets/import_export/eitest_export_B_1.ets | 16 ++ .../import_export/eitest_export_B_as_A_1.ets | 18 ++ .../eitest_export_default_A_1.ets | 16 ++ .../eitest_export_default_A_2.ets | 18 ++ .../eitest_export_default_B_1.ets | 16 ++ .../eitest_export_default_B_2.ets | 18 ++ ...test_export_default_import_default_A_1.ets | 18 ++ .../eitest_export_import_A_1.ets | 18 ++ .../eitest_export_import_A_2.ets | 18 ++ .../eitest_export_import_A_3.ets | 18 ++ .../eitest_export_import_default_A_1.ets | 18 ++ .../eitest_export_import_default_A_B_1.ets | 19 ++ .../import_export/eitest_export_type_A_1.ets | 19 ++ .../ets/import_export/eitest_import_A_1.ets | 20 ++ .../import_export/eitest_import_A_1_ne.ets} | 29 +-- .../ets/import_export/eitest_import_A_2.ets | 20 ++ .../import_export/eitest_import_A_2_ne.ets | 24 +++ .../ets/import_export/eitest_import_A_3.ets | 20 ++ .../import_export/eitest_import_A_3_ne.ets | 24 +++ .../ets/import_export/eitest_import_A_4.ets | 20 ++ .../import_export/eitest_import_A_4_ne.ets | 24 +++ .../ets/import_export/eitest_import_A_5.ets | 20 ++ .../import_export/eitest_import_A_5_ne.ets | 24 +++ .../ets/import_export/eitest_import_A_6.ets | 20 ++ .../import_export/eitest_import_A_6_ne.ets | 24 +++ .../ets/import_export/eitest_import_A_7.ets | 20 ++ .../import_export/eitest_import_A_7_ne.ets | 24 +++ .../ets/import_export/eitest_import_A_B_1.ets | 21 ++ .../import_export/eitest_import_A_B_1_ne.ets | 24 +++ .../eitest_import_default_A_1.ets | 20 ++ .../eitest_import_default_A_1_ne.ets} | 19 +- .../eitest_import_default_A_2.ets | 20 ++ .../eitest_import_default_A_2_ne.ets | 24 +++ .../eitest_import_default_A_3.ets | 20 ++ .../eitest_import_default_A_3_ne.ets | 22 ++ .../import_export/eitest_import_type_A_1.ets | 20 ++ .../eitest_import_type_A_1_ne.ets | 22 ++ .../ets/import_export/external_export.ets | 16 ++ .../compiler/ets/import_export/test1_1.ets | 17 ++ .../compiler/ets/import_export/test2_1.ets | 18 ++ .../compiler/ets/import_export/test3_1.ets | 17 ++ .../srcdumper/srcdumper-ets-ignored.txt | 29 +++ .../test/unit/union_normalisation_test.h | 1 + ets2panda/test/utils/checker_test.h | 1 + ets2panda/util/diagnostic/fatal.yaml | 4 + ets2panda/util/importPathManager.cpp | 2 +- ets2panda/util/importPathManager.h | 7 +- ets2panda/util/options.cpp | 6 +- ets2panda/util/options.h | 1 + ets2panda/util/options.yaml | 7 +- ets2panda/varbinder/ETSBinder.cpp | 201 +++++++++++++++--- ets2panda/varbinder/ETSBinder.h | 18 +- 77 files changed, 1429 insertions(+), 128 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_A_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_A_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_B_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_B_as_A_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_A_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_A_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_B_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_B_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_import_default_A_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_3.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_default_A_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_default_A_B_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_export_type_A_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_1.ets rename ets2panda/test/{runtime/ets/27016.ets => ast/compiler/ets/import_export/eitest_import_A_1_ne.ets} (64%) create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_2_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_3.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_3_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_4.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_4_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_5.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_5_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_6.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_6_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_7.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_7_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_B_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_B_1_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_1.ets rename ets2panda/test/{runtime/ets/27016_2.ets => ast/compiler/ets/import_export/eitest_import_default_A_1_ne.ets} (75%) create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_2_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_3.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_3_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_type_A_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/eitest_import_type_A_1_ne.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/external_export.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/test1_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/test2_1.ets create mode 100644 ets2panda/test/ast/compiler/ets/import_export/test3_1.ets diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index 227ef17874..658fb4a498 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -367,10 +367,16 @@ void ETSChecker::CheckProgram(parser::Program *program, bool runAnalysis) if (extProg->IsASTChecked()) { continue; } + + auto *savedProgram2 = VarBinder()->AsETSBinder()->Program(); + VarBinder()->AsETSBinder()->SetProgram(extProg); + VarBinder()->AsETSBinder()->ResetTopScope(extProg->GlobalScope()); checker::SavedCheckerContext savedContext(this, Context().Status(), Context().ContainingClass()); AddStatus(checker::CheckerStatus::IN_EXTERNAL); CheckProgram(extProg, VarBinder()->IsGenStdLib()); extProg->SetFlag(parser::ProgramFlags::AST_CHECK_PROCESSED); + VarBinder()->AsETSBinder()->SetProgram(savedProgram2); + VarBinder()->AsETSBinder()->ResetTopScope(savedProgram2->GlobalScope()); } } diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index a9b83658ec..e14451ae26 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -2861,6 +2861,8 @@ void ETSChecker::SetupGetterSetterFlags(ir::ClassProperty *originalProp, ETSObje ir::MethodDefinition *getter, ir::MethodDefinition *setter, const bool inExternal) { + auto getProgram = [](ir::AstNode *node) { return node->Range().start.Program(); }; + auto *const classDef = classType->GetDeclNode()->AsClassDefinition(); for (auto &method : {getter, setter}) { if (method == nullptr) { @@ -2876,7 +2878,7 @@ void ETSChecker::SetupGetterSetterFlags(ir::ClassProperty *originalProp, ETSObje method->Function()->AddModifier(ir::ModifierFlags::OVERRIDE); } - if (inExternal) { + if (inExternal && !getProgram(originalProp)->IsGenAbcForExternal()) { method->Function()->AddFlag(ir::ScriptFunctionFlags::EXTERNAL); } @@ -3000,6 +3002,7 @@ bool ETSChecker::TryTransformingToStaticInvoke(ir::Identifier *const ident, cons callExpr->SetCallee(transformedCallee); if (instantiateMethod != nullptr) { + auto lexScope {varbinder::LexicalScope::Enter(VarBinder(), compiler::NearestScope(callExpr))}; // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *argExpr = GenerateImplicitInstantiateArg(std::string(className)); diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 7f957d9fa1..2b6cfeac48 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -1880,7 +1880,11 @@ varbinder::Variable *ETSChecker::GetExtensionFuncVarInGlobalFunction(const ir::M { auto propertyName = memberExpr->Property()->AsIdentifier()->Name(); auto *globalFunctionVar = Scope()->FindInGlobal(propertyName, VO::STATIC_METHODS).variable; - if (globalFunctionVar == nullptr || !IsExtensionETSFunctionType(globalFunctionVar->TsType())) { + if (globalFunctionVar == nullptr) { + return nullptr; + } + + if (!IsExtensionETSFunctionType(GetTypeOfVariable(globalFunctionVar))) { return nullptr; } diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 2848d1fa2b..f43c3daf55 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -772,8 +772,14 @@ Type *ETSChecker::GetTypeFromInterfaceReference(varbinder::Variable *var) return var->TsType(); } + CheckerStatus status = CheckerStatus::IN_STATIC_CONTEXT; + status &= this->Context().Status(); + this->Context().Status() &= ~CheckerStatus::IN_STATIC_CONTEXT; + auto *interfaceType = BuildBasicInterfaceProperties(var->Declaration()->Node()->AsTSInterfaceDeclaration()); var->SetTsType(interfaceType); + + this->Context().Status() |= status; return interfaceType; } @@ -785,8 +791,13 @@ Type *ETSChecker::GetTypeFromClassReference(varbinder::Variable *var) auto classDef = var->Declaration()->Node()->AsClassDefinition(); + CheckerStatus status = CheckerStatus::IN_STATIC_CONTEXT; + status &= this->Context().Status(); + this->Context().Status() &= ~CheckerStatus::IN_STATIC_CONTEXT; + auto *classType = BuildBasicClassProperties(classDef); var->SetTsType(classType); + this->Context().Status() |= status; return classType; } diff --git a/ets2panda/checker/ets/utilityTypeHandlers.cpp b/ets2panda/checker/ets/utilityTypeHandlers.cpp index 6f74238afc..3b44ea5941 100644 --- a/ets2panda/checker/ets/utilityTypeHandlers.cpp +++ b/ets2panda/checker/ets/utilityTypeHandlers.cpp @@ -98,7 +98,7 @@ static std::pair GetPartialClassPro ir::AstNode *typeNode) { auto classDefProgram = typeNode->GetTopStatement()->AsETSModule()->Program(); - if (classDefProgram == checker->VarBinder()->Program()) { + if (classDefProgram == checker->VarBinder()->AsETSBinder()->GetGlobalRecordTable()->Program()) { return {classDefProgram, checker->VarBinder()->AsETSBinder()->GetGlobalRecordTable()}; } return {classDefProgram, checker->VarBinder()->AsETSBinder()->GetExternalRecordTable().at(classDefProgram)}; @@ -144,7 +144,9 @@ Type *ETSChecker::CreatePartialTypeClass(ETSObjectType *typeToBePartial, ir::Ast // Check if we've already generated the partial class, then don't do it again const auto classNameToFind = - partialProgram == VarBinder()->Program() || VarBinder()->IsGenStdLib() ? partialName : partialQualifiedName; + partialProgram == VarBinder()->Program() || VarBinder()->IsGenStdLib() || partialProgram->IsGenAbcForExternal() + ? partialName + : partialQualifiedName; if (auto *var = SearchNamesInMultiplePrograms({partialProgram, VarBinder()->Program()}, {classNameToFind, partialName}); var != nullptr) { diff --git a/ets2panda/compiler/core/ETSemitter.cpp b/ets2panda/compiler/core/ETSemitter.cpp index 66a81912f4..29fa171f9e 100644 --- a/ets2panda/compiler/core/ETSemitter.cpp +++ b/ets2panda/compiler/core/ETSemitter.cpp @@ -262,10 +262,35 @@ static std::vector> StoreExportNodes( return result; } +void FilterForSimultaneous(varbinder::ETSBinder *varbinder) +{ + ArenaSet &classDefinitions = varbinder->GetGlobalRecordTable()->ClassDefinitions(); + for (auto it = classDefinitions.begin(); it != classDefinitions.end(); ++it) { + if ((*it)->InternalName().Is(Signatures::ETS_GLOBAL)) { + classDefinitions.erase(it); + break; + } + } + std::vector filterFunctions = { + Signatures::UNUSED_ETSGLOBAL_CTOR, Signatures::UNUSED_ETSGLOBAL_INIT, Signatures::UNUSED_ETSGLOBAL_MAIN}; + auto &functions = varbinder->Functions(); + functions.erase(std::remove_if(functions.begin(), functions.end(), + [&filterFunctions](varbinder::FunctionScope *scope) -> bool { + return std::any_of( + filterFunctions.begin(), filterFunctions.end(), + [&scope](std::string_view &s) { return scope->InternalName().Is(s); }); + }), // CC-OFF(G.FMT.02) + functions.end()); +} + void ETSEmitter::GenAnnotation() { Program()->lang = EXTENSION; - const auto *varbinder = static_cast(Context()->parserProgram->VarBinder()); + auto *varbinder = static_cast(Context()->parserProgram->VarBinder()); + + if (Context()->config->options->GetCompilationMode() == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { + FilterForSimultaneous(varbinder); + } auto *globalRecordTable = varbinder->GetGlobalRecordTable(); auto baseName = varbinder->GetRecordTable()->RecordName().Mutf8(); @@ -324,29 +349,37 @@ static bool IsFromSelfHeadFile(const std::string &name, const parser::Program *c void ETSEmitter::GenExternalRecord(varbinder::RecordTable *recordTable, const parser::Program *extProg) { - bool isGenStdLib = recordTable->Program()->VarBinder()->IsGenStdLib(); + bool isExternalFromCompile = + !recordTable->Program()->VarBinder()->IsGenStdLib() && !recordTable->Program()->IsGenAbcForExternal(); const auto *varbinder = static_cast(Context()->parserProgram->VarBinder()); auto baseName = varbinder->GetRecordTable()->RecordName().Mutf8(); for (auto *annoDecl : recordTable->AnnotationDeclarations()) { auto newBaseName = GenerateMangledName(baseName, annoDecl->GetBaseName()->Name().Mutf8()); - GenCustomAnnotationRecord(annoDecl, newBaseName, !isGenStdLib); + GenCustomAnnotationRecord(annoDecl, newBaseName, isExternalFromCompile || annoDecl->IsDeclare()); } for (auto *classDecl : recordTable->ClassDefinitions()) { - GenClassRecord(classDecl, !isGenStdLib); + GenClassRecord(classDecl, isExternalFromCompile || classDecl->IsDeclare()); } for (auto *interfaceDecl : recordTable->InterfaceDeclarations()) { - GenInterfaceRecord(interfaceDecl, !isGenStdLib); + GenInterfaceRecord(interfaceDecl, isExternalFromCompile || interfaceDecl->IsDeclare()); } for (auto *signature : recordTable->Signatures()) { - auto func = GenScriptFunction(signature->Node()->AsScriptFunction(), this); + auto scriptFunc = signature->Node()->AsScriptFunction(); + auto func = GenScriptFunction(scriptFunc, this); - if (!isGenStdLib) { + if (isExternalFromCompile || scriptFunc->IsDeclare()) { func.metadata->SetAttribute(Signatures::EXTERNAL); } + if (extProg->IsGenAbcForExternal() && scriptFunc->IsAsyncFunc()) { + std::vector annotations; + annotations.push_back(GenAnnotationAsync(scriptFunc)); + func.metadata->AddAnnotations(annotations); + } + if (func.metadata->IsForeign() && IsFromSelfHeadFile(func.name, Context()->parserProgram, extProg)) { return; } diff --git a/ets2panda/compiler/core/compilerImpl.cpp b/ets2panda/compiler/core/compilerImpl.cpp index af038f7485..0f206c0f0d 100644 --- a/ets2panda/compiler/core/compilerImpl.cpp +++ b/ets2panda/compiler/core/compilerImpl.cpp @@ -397,7 +397,17 @@ static bool ExecuteParsingAndCompiling(const CompilationUnit &unit, public_lib:: AddExternalPrograms(context, unit, program); } - context->parser->ParseScript(unit.input, unit.options.GetCompilationMode() == CompilationMode::GEN_STD_LIB); + if (context->config->options->GetCompilationMode() == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE && + context->config->options->GetExtension() == ScriptExtension::ETS) { + std::unordered_set sourceFileNamesSet; + util::UString absolutePath(os::GetAbsolutePath(context->sourceFile->filePath), context->allocator); + sourceFileNamesSet.insert(absolutePath.View().Mutf8()); + context->sourceFileNames.emplace_back(absolutePath.View().Utf8()); + parser::ETSParser::AddGenExtenralSourceToParseList(context); + context->MarkGenAbcForExternal(sourceFileNamesSet, context->parserProgram->ExternalSources()); + } else { + context->parser->ParseScript(unit.input, unit.options.GetCompilationMode() == CompilationMode::GEN_STD_LIB); + } // We have to check the return status of 'RunVerifierAndPhase` and 'RunPhases` separately because there can be // some internal errors (say, in Post-Conditional check) or terminate options (say in 'CheckOptionsAfterPhase') @@ -434,6 +444,7 @@ static pandasm::Program *Compile(const CompilationUnit &unit, CompilerImpl *comp : nullptr); auto parser = Parser(&program, unit.options, unit.diagnosticEngine, static_cast(unit.rawParserStatus)); + parser.SetContext(context); context->parser = &parser; auto checker = Checker(unit.diagnosticEngine, context->allocator); context->checker = &checker; diff --git a/ets2panda/compiler/core/emitter.cpp b/ets2panda/compiler/core/emitter.cpp index 95b7d45aee..91ee21b4fb 100644 --- a/ets2panda/compiler/core/emitter.cpp +++ b/ets2panda/compiler/core/emitter.cpp @@ -438,6 +438,9 @@ static void UpdateLiteralBufferId([[maybe_unused]] ark::pandasm::Ins *ins, [[may void Emitter::AddProgramElement(ProgramElement *programElement) { + if (programElement->Function() == nullptr) { + return; + } prog_->strings.insert(programElement->Strings().begin(), programElement->Strings().end()); uint32_t newLiteralBufferIndex = literalBufferIndex_; @@ -535,7 +538,8 @@ pandasm::Program *Emitter::Finalize(bool dumpDebugInfo, std::string_view globalC dumper.Dump(); } - if (context_->parserProgram->VarBinder()->IsGenStdLib()) { + if (context_->parserProgram->VarBinder()->IsGenStdLib() || + context_->parserProgram->VarBinder()->Program()->IsGenAbcForExternal()) { auto it = prog_->recordTable.find(std::string(globalClass)); if (it != prog_->recordTable.end()) { prog_->recordTable.erase(it); diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index c513801d30..0ea93f02a8 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -1265,7 +1265,8 @@ bool LambdaConversionPhase::PerformForModule(public_lib::Context *ctx, parser::P // For reproducibility of results when several compilation sessions are executed during // the same process's lifetime. - if (program == ctx->parserProgram) { + if (program == ctx->parserProgram && + ctx->config->options->GetCompilationMode() != CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { ResetCalleeCount(); } diff --git a/ets2panda/compiler/lowering/phase.cpp b/ets2panda/compiler/lowering/phase.cpp index 6cd559f27d..12383fd94c 100644 --- a/ets2panda/compiler/lowering/phase.cpp +++ b/ets2panda/compiler/lowering/phase.cpp @@ -14,6 +14,7 @@ */ #include "phase.h" + #include "checker/checker.h" #include "compiler/lowering/checkerPhase.h" #include "compiler/lowering/ets/asyncMethodLowering.h" @@ -307,62 +308,81 @@ bool PhaseForDeclarations::Postcondition(public_lib::Context *ctx, const parser: return PostconditionForModule(ctx, program); } +// CC-OFFNXT(huge_method, huge_depth) solid logic bool PhaseForBodies::Precondition(public_lib::Context *ctx, const parser::Program *program) { - auto checkExternalPrograms = [this, ctx](const ArenaVector &programs) { - for (auto *p : programs) { - if (!Precondition(ctx, p)) { - return false; + auto cMode = ctx->config->options->GetCompilationMode(); + + auto iterateExternal = [&cMode, this](public_lib::Context *context, const parser::Program *localProgram) { + for (auto &[_, extPrograms] : localProgram->ExternalSources()) { + (void)_; + for (auto *prog : extPrograms) { + if (!prog->IsGenAbcForExternal() && cMode == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { + continue; + } + + if (!Precondition(context, prog)) { + return false; + } } } return true; }; - - if (ctx->config->options->GetCompilationMode() == CompilationMode::GEN_STD_LIB) { - for (auto &[_, extPrograms] : program->ExternalSources()) { - (void)_; - if (!checkExternalPrograms(extPrograms)) { - return false; - }; + if (cMode == CompilationMode::GEN_STD_LIB || cMode == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { + if (!iterateExternal(ctx, program)) { + return false; } } return PreconditionForModule(ctx, program); } +// CC-OFFNXT(huge_method, huge_depth) solid logic bool PhaseForBodies::Perform(public_lib::Context *ctx, parser::Program *program) { bool result = true; - if (ctx->config->options->GetCompilationMode() == CompilationMode::GEN_STD_LIB) { - for (auto &[_, extPrograms] : program->ExternalSources()) { + auto cMode = ctx->config->options->GetCompilationMode(); + auto iterateExternal = [&result, &cMode, this](public_lib::Context *context, parser::Program *localProgram) { + for (auto &[_, extPrograms] : localProgram->ExternalSources()) { (void)_; for (auto *extProg : extPrograms) { - result &= Perform(ctx, extProg); + if (!extProg->IsGenAbcForExternal() && cMode == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { + continue; + } + result &= Perform(context, extProg); } } + }; + if (cMode == CompilationMode::GEN_STD_LIB || cMode == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { + iterateExternal(ctx, program); } result &= PerformForModule(ctx, program); return result; } +// CC-OFFNXT(huge_method, huge_depth) solid logic bool PhaseForBodies::Postcondition(public_lib::Context *ctx, const parser::Program *program) { - auto checkExternalPrograms = [this, ctx](const ArenaVector &programs) { - for (auto *p : programs) { - if (!Postcondition(ctx, p)) { - return false; + auto cMode = ctx->config->options->GetCompilationMode(); + auto iterateExternal = [&cMode, this](public_lib::Context *context, const parser::Program *localProgram) { + for (auto &[_, extPrograms] : localProgram->ExternalSources()) { + (void)_; + for (auto *prog : extPrograms) { + if (!prog->IsGenAbcForExternal() && cMode == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { + continue; + } + + if (!Postcondition(context, prog)) { + return false; + } } } return true; }; - - if (ctx->config->options->GetCompilationMode() == CompilationMode::GEN_STD_LIB) { - for (auto &[_, extPrograms] : program->ExternalSources()) { - (void)_; - if (!checkExternalPrograms(extPrograms)) { - return false; - }; + if (cMode == CompilationMode::GEN_STD_LIB || cMode == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { + if (!iterateExternal(ctx, program)) { + return false; } } diff --git a/ets2panda/compiler/scripts/signatures.yaml b/ets2panda/compiler/scripts/signatures.yaml index 496aa8e961..c72828883c 100644 --- a/ets2panda/compiler/scripts/signatures.yaml +++ b/ets2panda/compiler/scripts/signatures.yaml @@ -218,6 +218,12 @@ defines: - name: 'InterfaceObjectLiteral' ref: INTERFACE_OBJ_LITERAL comment: ETS annotation type + - name: 'ETSGLOBAL.:void;' + ref: UNUSED_ETSGLOBAL_CTOR + - name: 'ETSGLOBAL._$init$_:void;' + ref: UNUSED_ETSGLOBAL_INIT + - name: 'ETSGLOBAL.main:void;' + ref: UNUSED_ETSGLOBAL_MAIN packages: - name: 'std.core' diff --git a/ets2panda/driver/build_system/package.json b/ets2panda/driver/build_system/package.json index 5d9fe607cc..597e3abe96 100644 --- a/ets2panda/driver/build_system/package.json +++ b/ets2panda/driver/build_system/package.json @@ -8,15 +8,20 @@ "clean": "rimraf dist", "build": "npm run clean && tsc", "build_debug": "npm run clean && tsc --sourceMap", + "mixed_hap:gen_decl": "npm run build && node ./dist/entry.js test/demo_mix_hap/build_config_decl.json", "mixed_hap:gen_abc": "node ./dist/entry.js test/demo_mix_hap/build_config.json", "mixed_hap:run": "npm run mixed_hap:gen_decl && npm run mixed_hap:gen_abc", + "demo_hap:gen_abc": "npm run build && node ./dist/entry.js test/demo_hap/build_config.json" }, "devDependencies": { - "@tsconfig/recommended": "1.0.8", + "typescript": "^5.0.0", "@types/node": "22.10.7", - "rimraf": "^6.0.1", - "typescript": "^5.0.0" + "@tsconfig/recommended": "1.0.8", + "rimraf": "6.0.1" + }, + "dependencies": { + } } diff --git a/ets2panda/driver/build_system/src/build/build_mode.ts b/ets2panda/driver/build_system/src/build/build_mode.ts index b1643a8d9c..59bdb759ab 100644 --- a/ets2panda/driver/build_system/src/build/build_mode.ts +++ b/ets2panda/driver/build_system/src/build/build_mode.ts @@ -26,6 +26,6 @@ export class BuildMode extends BaseMode { } public async run(): Promise { - await super.run(); + await super.runParallell(); } } \ No newline at end of file diff --git a/ets2panda/es2panda.h b/ets2panda/es2panda.h index 21c202e405..b7e93a6cbd 100644 --- a/ets2panda/es2panda.h +++ b/ets2panda/es2panda.h @@ -61,6 +61,7 @@ enum class CompilationMode { GEN_STD_LIB, PROJECT, SINGLE_FILE, + GEN_ABC_FOR_EXTERNAL_SOURCE, }; // CC-OFFNXT(G.FUD.06) switch-case, ODR inline Language ToLanguage(ScriptExtension ext) diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 39c9f511e4..d45233034c 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -187,6 +187,22 @@ ir::ETSModule *ETSParser::ParseImportsOnly(lexer::SourcePosition startLoc, Arena return etsModule; } +bool ETSParser::CheckDupAndReplace(Program *&oldProg, Program *newProg) +{ + if (!importPathManager_->ArkTSConfig()->UseUrl() && oldProg->FileName() == newProg->FileName() && + oldProg->FileNameWithExtension() != newProg->FileNameWithExtension()) { + bool oldIsDeclare = oldProg->FileNameWithExtension().Length() > newProg->FileNameWithExtension().Length(); + if (oldIsDeclare) { + Context()->dupPrograms.emplace(oldProg->AbsoluteName(), newProg); + oldProg = newProg; + } else { + Context()->dupPrograms.emplace(newProg->AbsoluteName(), oldProg); + } + return true; + } + return false; +} + void ETSParser::AddExternalSource(const std::vector &programs) { auto &extSources = globalProgram_->ExternalSources(); @@ -197,11 +213,16 @@ void ETSParser::AddExternalSource(const std::vector &programs) extSources.try_emplace(name, Allocator()->Adapter()); } bool found = false; - for (auto *prog : extSources.at(name)) { + auto &extProgs = extSources.at(name); + for (auto prog : extProgs) { if (prog->SourceFilePath() == newProg->SourceFilePath()) { found = true; break; } + if (CheckDupAndReplace(prog, newProg)) { + found = true; + break; + } } if (!found) { extSources.at(name).emplace_back(newProg); @@ -241,7 +262,7 @@ void ETSParser::AddDirectImportsToDirectExternalSources( return; } - const util::StringView name = newProg->Ast()->Statements().empty() ? newProg->FileName() : newProg->ModuleName(); + auto name = newProg->ModuleName(); if (GetProgram()->DirectExternalSources().count(name) == 0) { GetProgram()->DirectExternalSources().try_emplace(name, Allocator()->Adapter()); } @@ -263,6 +284,25 @@ void ETSParser::ParseParseListElement(const util::ImportPathManager::ParseInfo & } } +void ETSParser::AddGenExtenralSourceToParseList(public_lib::Context *ctx) +{ + auto allocator = ctx->allocator; + auto ident = allocator->New(compiler::Signatures::ETS_GLOBAL, allocator); + ArenaVector stmts(allocator->Adapter()); + auto etsModule = allocator->New(allocator, std::move(stmts), ident, ir::ModuleFlag::ETSSCRIPT, + ctx->parserProgram); + ctx->parserProgram->SetAst(etsModule); + for (auto &sourceName : ctx->sourceFileNames) { + util::ImportPathManager::ImportMetadata importData {util::ImportFlags::NONE}; + importData.resolvedSource = sourceName; + importData.lang = Language::Id::ETS; + importData.declPath = util::ImportPathManager::DUMMY_PATH; + importData.ohmUrl = util::ImportPathManager::DUMMY_PATH; + ctx->parser->AsETSParser()->GetImportPathManager()->AddToParseList(importData); + } + ctx->parser->AsETSParser()->AddExternalSource(ctx->parser->AsETSParser()->ParseSources(true)); +} + static bool SearchImportedExternalSources(ETSParser *parser, const std::string_view &path) { auto *ctx = parser->GetGlobalProgram()->VarBinder()->GetContext(); @@ -368,7 +408,13 @@ parser::Program *ETSParser::ParseSource(const SourceFile &sourceFile) ir::ETSModule *script = nullptr; if (decl != nullptr) { statements.emplace_back(decl); + if (Context()->config->options->GetCompilationMode() == CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE) { + importPathManager_->AddImplicitPackageImportToParseList(program->SourceFile().GetAbsoluteParentFolder(), + Lexer()->GetToken().Start()); + importPathManager_->MarkAsParsed(program->AbsoluteName()); + } SavedParserContext contextAfterParseDecl(this, GetContext().Status() |= ParserStatus::IN_PACKAGE); + script = ParseETSGlobalScript(startLoc, statements); } else { script = ParseETSGlobalScript(startLoc, statements); diff --git a/ets2panda/parser/ETSparser.h b/ets2panda/parser/ETSparser.h index f038afa6f2..6a2e718765 100644 --- a/ets2panda/parser/ETSparser.h +++ b/ets2panda/parser/ETSparser.h @@ -70,6 +70,7 @@ public: void AddDirectImportsToDirectExternalSources(const ArenaVector &directImportsFromMainSource, parser::Program *newProg) const; + bool CheckDupAndReplace(Program *&oldProg, Program *newProg); ArenaVector ParseDefaultSources(std::string_view srcFile, std::string_view importSrc); lexer::LexerPosition HandleJsDocLikeComments(); @@ -142,8 +143,10 @@ public: void AddExternalSource(const std::vector &programs); std::vector ParseSources(bool firstSource = false); + static void AddGenExtenralSourceToParseList(public_lib::Context *ctx); private: + void ParseAndSetStdlib(); NodeFormatType GetFormatPlaceholderType(); ir::Statement *ParseStatementFormatPlaceholder() override; ir::Expression *ParseExpressionFormatPlaceholder(); diff --git a/ets2panda/parser/parserImpl.h b/ets2panda/parser/parserImpl.h index d64de90591..c71ad06628 100644 --- a/ets2panda/parser/parserImpl.h +++ b/ets2panda/parser/parserImpl.h @@ -37,6 +37,10 @@ class Options; class SourcePositionHelper; } // namespace ark::es2panda::util +namespace ark::es2panda::public_lib { +struct Context; +} // namespace ark::es2panda::public_lib + namespace ark::es2panda::parser { using ENUMBITOPS_OPERATORS; @@ -101,6 +105,16 @@ public: lexer::SourcePosition GetPositionForDiagnostic() const; + void SetContext(public_lib::Context *ctx) + { + ctx_ = ctx; + } + + public_lib::Context *Context() + { + return ctx_; + } + protected: virtual void ParseProgram(ScriptKind kind); static ExpressionParseFlags CarryExpressionParserFlag(ExpressionParseFlags origin, ExpressionParseFlags carry); @@ -569,6 +583,7 @@ private: lexer::Lexer *lexer_ {}; const util::Options *options_; util::DiagnosticEngine &diagnosticEngine_; + public_lib::Context *ctx_ {nullptr}; }; } // namespace ark::es2panda::parser diff --git a/ets2panda/parser/program/program.cpp b/ets2panda/parser/program/program.cpp index 3d6ecb19e6..fa9263c325 100644 --- a/ets2panda/parser/program/program.cpp +++ b/ets2panda/parser/program/program.cpp @@ -39,6 +39,13 @@ Program::Program(ArenaAllocator *allocator, varbinder::VarBinder *varbinder) { } +bool Program::IsGenAbcForExternal() const +{ + return VarBinder()->GetContext()->config->options->GetCompilationMode() == + CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE && + genAbcForExternalSource_; +} + std::string Program::Dump() const { ir::AstDumper dumper {ast_, SourceCode()}; diff --git a/ets2panda/parser/program/program.h b/ets2panda/parser/program/program.h index d3e0ac67a6..7bee07ed09 100644 --- a/ets2panda/parser/program/program.h +++ b/ets2panda/parser/program/program.h @@ -42,7 +42,7 @@ class CFG; } // namespace ark::es2panda::compiler namespace ark::es2panda::parser { -enum class ScriptKind { SCRIPT, MODULE, STDLIB }; +enum class ScriptKind { SCRIPT, MODULE, STDLIB, GENEXTERNAL }; enum EntityType { CLASS_PROPERTY = 0, METHOD_DEFINITION = 1, CLASS_DEFINITION = 2, TS_INTERFACE_DECLARATION = 3 }; #ifndef NDEBUG @@ -296,6 +296,13 @@ public: (FileName().Is("etsstdlib")); } + bool IsGenAbcForExternal() const; + + void SetGenAbcForExternalSources(bool genAbc = true) + { + genAbcForExternalSource_ = genAbc; + } + varbinder::ClassScope *GlobalClassScope(); const varbinder::ClassScope *GlobalClassScope() const; @@ -379,6 +386,7 @@ private: ExternalSource externalSources_; DirectExternalSource directExternalSources_; ScriptKind kind_ {}; + bool genAbcForExternalSource_ {false}; ScriptExtension extension_ {}; ETSNolintsCollectionMap etsnolintCollection_; util::ModuleInfo moduleInfo_; diff --git a/ets2panda/public/es2panda_lib.cpp b/ets2panda/public/es2panda_lib.cpp index 968ce30073..1706d0d40a 100644 --- a/ets2panda/public/es2panda_lib.cpp +++ b/ets2panda/public/es2panda_lib.cpp @@ -311,27 +311,63 @@ static void CompileJob(public_lib::Context *context, varbinder::FunctionScope *s funcEmitter.Generate(); } -__attribute__((unused)) static es2panda_Context *CreateContext(es2panda_Config *config, std::string &&source, - const char *fileName) +static void InitializeContext(Context *res) +{ + res->phaseManager = new compiler::PhaseManager(ScriptExtension::ETS, res->allocator); + res->queue = new compiler::CompileQueue(res->config->options->GetThread()); + + auto *varbinder = res->allocator->New(res->allocator); + res->parserProgram = res->allocator->New(res->allocator, varbinder); + res->parser = new parser::ETSParser(res->parserProgram, *res->config->options, *res->diagnosticEngine, + parser::ParserStatus::NO_OPTS); + res->parser->SetContext(res); + + res->checker = res->allocator->New(*res->diagnosticEngine, res->allocator); + res->analyzer = res->allocator->New(res->checker); + res->checker->SetAnalyzer(res->analyzer); + + varbinder->SetProgram(res->parserProgram); + varbinder->SetContext(res); + res->codeGenCb = CompileJob; + res->emitter = new compiler::ETSEmitter(res); + res->program = nullptr; + res->state = ES2PANDA_STATE_NEW; +} + +static Context *InitContext(es2panda_Config *config) { auto *cfg = reinterpret_cast(config); auto *res = new Context; - res->input = std::move(source); - res->sourceFileName = fileName; - res->config = cfg; if (cfg == nullptr) { res->errorMessage = "Config is nullptr."; res->state = ES2PANDA_STATE_ERROR; - return reinterpret_cast(res); + return res; } if (cfg->options->GetExtension() != ScriptExtension::ETS) { res->errorMessage = "Invalid extension. Plugin API supports only ETS."; res->state = ES2PANDA_STATE_ERROR; + res->diagnosticEngine = cfg->diagnosticEngine; + return res; + } + + res->config = cfg; + res->diagnosticEngine = cfg->diagnosticEngine; + return res; +} + +__attribute__((unused)) static es2panda_Context *CreateContext(es2panda_Config *config, std::string &&source, + const char *fileName) +{ + auto res = InitContext(config); + if (res->state == ES2PANDA_STATE_ERROR) { return reinterpret_cast(res); } + auto *cfg = reinterpret_cast(config); + res->input = std::move(source); + res->sourceFileName = fileName; res->sourceFile = new SourceFile(res->sourceFileName, res->input, cfg->options->IsModule()); res->allocator = new ArenaAllocator(SpaceType::SPACE_TYPE_COMPILER, nullptr, true); res->queue = new compiler::CompileQueue(cfg->options->GetThread()); @@ -341,6 +377,7 @@ __attribute__((unused)) static es2panda_Context *CreateContext(es2panda_Config * res->diagnosticEngine = cfg->diagnosticEngine; res->parser = new parser::ETSParser(res->parserProgram, *cfg->options, *cfg->diagnosticEngine, parser::ParserStatus::NO_OPTS); + res->parser->SetContext(res); res->checker = new checker::ETSChecker(*res->diagnosticEngine); res->isolatedDeclgenChecker = new checker::IsolatedDeclgenChecker(*res->diagnosticEngine, *(res->parserProgram)); res->analyzer = new checker::ETSAnalyzer(res->checker); @@ -379,6 +416,12 @@ extern "C" __attribute__((unused)) es2panda_Context *CreateContextFromFile(es2pa return CreateContext(config, ss.str(), sourceFileName); } +extern "C" __attribute__((unused)) es2panda_Context *CreateContextFromMultiFile(es2panda_Config *config, + char const *sourceFileNames) +{ + return CreateContext(config, "", sourceFileNames); +} + extern "C" __attribute__((unused)) es2panda_Context *CreateContextFromString(es2panda_Config *config, const char *source, char const *fileName) { @@ -386,6 +429,31 @@ extern "C" __attribute__((unused)) es2panda_Context *CreateContextFromString(es2 return CreateContext(config, std::string(source), fileName); } +extern __attribute__((unused)) es2panda_Context *CreateContextGenerateAbcForExternalSourceFiles( + es2panda_Config *config, int fileNamesCount, char const *const *fileNames) +{ + auto res = InitContext(config); + if (res->state == ES2PANDA_STATE_ERROR) { + return reinterpret_cast(res); + } + auto *cfg = reinterpret_cast(config); + + ES2PANDA_ASSERT(cfg->options->IsSimultaneous()); + for (size_t i = 0; i < static_cast(fileNamesCount); ++i) { + const char *cName = *(fileNames + i); + std::string fileName(cName); + res->sourceFileNames.emplace_back(std::move(fileName)); + } + + res->input = ""; + res->sourceFileName = ""; + res->sourceFile = new SourceFile(res->sourceFileName, res->input, cfg->options->IsModule()); + res->allocator = new ArenaAllocator(SpaceType::SPACE_TYPE_COMPILER, nullptr, true); + + InitializeContext(res); + return reinterpret_cast(res); +} + __attribute__((unused)) static Context *Parse(Context *ctx) { if (ctx->state != ES2PANDA_STATE_NEW) { @@ -394,13 +462,34 @@ __attribute__((unused)) static Context *Parse(Context *ctx) return ctx; } - ctx->phaseManager->Restart(); - ctx->parser->ParseScript(*ctx->sourceFile, - ctx->config->options->GetCompilationMode() == CompilationMode::GEN_STD_LIB); + if (ctx->config->options->IsSimultaneous()) { + parser::ETSParser::AddGenExtenralSourceToParseList(ctx); + std::unordered_set sourceFileNamesSet(ctx->sourceFileNames.begin(), ctx->sourceFileNames.end()); + ctx->MarkGenAbcForExternal(sourceFileNamesSet, ctx->parserProgram->ExternalSources()); + } else { + ctx->parser->ParseScript(*ctx->sourceFile, + ctx->config->options->GetCompilationMode() == CompilationMode::GEN_STD_LIB); + } ctx->state = ES2PANDA_STATE_PARSED; return ctx; } +__attribute__((unused)) static bool SetProgramGenAbc(Context *ctx, const char *path) +{ + util::StringView pathView(path); + public_lib::Context *context = reinterpret_cast(ctx); + for (auto &[_, extPrograms] : context->externalSources) { + (void)_; + for (auto *prog : extPrograms) { + if (prog->AbsoluteName() == pathView) { + prog->SetGenAbcForExternalSources(); + return true; + } + } + } + return false; +} + __attribute__((unused)) static Context *Bind(Context *ctx) { if (ctx->state < ES2PANDA_STATE_PARSED) { @@ -1068,6 +1157,7 @@ es2panda_Impl g_impl = { ConfigGetOptions, CreateContextFromFile, CreateContextFromString, + CreateContextGenerateAbcForExternalSourceFiles, ProceedToState, DestroyContext, ContextState, diff --git a/ets2panda/public/es2panda_lib.h b/ets2panda/public/es2panda_lib.h index 2c4e3fc202..84d44b022e 100644 --- a/ets2panda/public/es2panda_lib.h +++ b/ets2panda/public/es2panda_lib.h @@ -182,6 +182,8 @@ struct CAPI_EXPORT es2panda_Impl { es2panda_Context *(*CreateContextFromFile)(es2panda_Config *config, char const *source_file_name); es2panda_Context *(*CreateContextFromString)(es2panda_Config *config, const char *source, char const *file_name); + es2panda_Context *(*CreateContextGenerateAbcForExternalSourceFiles)(es2panda_Config *config, int fileNamesCount, + char const *const *fileNames); es2panda_Context *(*ProceedToState)(es2panda_Context *context, es2panda_ContextState state); // context is consumed void (*DestroyContext)(es2panda_Context *context); diff --git a/ets2panda/public/es2panda_lib.idl.erb b/ets2panda/public/es2panda_lib.idl.erb index e4a957106d..327c34723f 100644 --- a/ets2panda/public/es2panda_lib.idl.erb +++ b/ets2panda/public/es2panda_lib.idl.erb @@ -173,6 +173,7 @@ interface es2panda_Impl { es2panda_Context CreateContextFromFile(es2panda_Config config, String source_file_name); es2panda_Context CreateContextFromString(es2panda_Config config, String source, String file_name); + es2panda_Context CreateContextGenerateAbcForExternalSourceFiles(es2panda_Config config, i32 fileNamesCount, sequence fileNames); es2panda_Context ProceedToState(es2panda_Context context, es2panda_ContextState state); // context is consumed void DestroyContext(es2panda_Context context); diff --git a/ets2panda/public/public.h b/ets2panda/public/public.h index fdb18d9ca6..2e6fa5dba8 100644 --- a/ets2panda/public/public.h +++ b/ets2panda/public/public.h @@ -52,7 +52,7 @@ struct ConfigImpl { }; using ExternalSources = std::unordered_map>; - +using ExternalSource = ArenaUnorderedMap>; using ComputedAbstracts = ArenaUnorderedMap, ArenaUnorderedSet>>; @@ -160,6 +160,36 @@ struct Context { return util::NodeAllocator::ForceSetParent(Allocator(), std::forward(args)...); } + void MarkGenAbcForExternal(std::unordered_set &genAbcList, public_lib::ExternalSource &extSources) + { + size_t genCount = 0; + std::unordered_set genAbcListAbsolute; + + for (auto &path : genAbcList) { + genAbcListAbsolute.insert(os::GetAbsolutePath(path)); + } + for (auto &[_, extPrograms] : extSources) { + (void)_; + bool setFlag = false; + for (auto *prog : extPrograms) { + if (auto it = genAbcListAbsolute.find(prog->AbsoluteName().Mutf8()); it != genAbcListAbsolute.end()) { + ++genCount; + setFlag = true; + } + } + if (!setFlag) { + continue; + } + for (auto *prog : extPrograms) { + prog->SetGenAbcForExternalSources(); + } + } + + if (genCount != genAbcListAbsolute.size()) { + diagnosticEngine->LogFatalError(diagnostic::SIMULTANEOUSLY_MARK_FAILED.Message()); + } + } + ConfigImpl *config = nullptr; std::string sourceFileName; std::string input; @@ -188,6 +218,8 @@ struct Context { CompilingState compilingState {CompilingState::NONE_COMPILING}; ExternalSources externalSources; TransitionMemory *transitionMemory {nullptr}; + std::vector sourceFileNames; + std::map dupPrograms {}; // NOLINTEND(misc-non-private-member-variables-in-classes) }; } // namespace ark::es2panda::public_lib diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_A_1.ets new file mode 100644 index 0000000000..6780a05eb1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_A_1.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 class A{} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_A_2.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_A_2.ets new file mode 100644 index 0000000000..a12a108de3 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_A_2.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{} + +export A; \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_B_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_B_1.ets new file mode 100644 index 0000000000..e94062d246 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_B_1.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 class B{} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_B_as_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_B_as_A_1.ets new file mode 100644 index 0000000000..2e2d5ca5aa --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_B_as_A_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. + */ + +class B{} + +export {B as A} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_A_1.ets new file mode 100644 index 0000000000..e7d776f8ed --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_A_1.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 default class A{} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_A_2.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_A_2.ets new file mode 100644 index 0000000000..e3948e3dfb --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_A_2.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{} + +export default A; \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_B_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_B_1.ets new file mode 100644 index 0000000000..c3d22a7b65 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_B_1.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 default class B{} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_B_2.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_B_2.ets new file mode 100644 index 0000000000..85a9380fbf --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_B_2.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 B{} + +export default B; \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_import_default_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_import_default_A_1.ets new file mode 100644 index 0000000000..8ed966ae30 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_default_import_default_A_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. + */ + +import A from "./eitest_export_default_A_1" + +export default A \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_1.ets new file mode 100644 index 0000000000..472711f075 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_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. + */ + +import {A} from "./eitest_export_A_1" + +export A \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_2.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_2.ets new file mode 100644 index 0000000000..b815742961 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_2.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 {B} from "./eitest_export_B_1" + +export {B as A} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_3.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_3.ets new file mode 100644 index 0000000000..9d1da0fa43 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_A_3.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 as B} from "./eitest_export_A_1" + +export {B as A} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_default_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_default_A_1.ets new file mode 100644 index 0000000000..b30c26cbbe --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_default_A_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. + */ + +import A from "./eitest_export_default_A_1" + +export A \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_default_A_B_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_default_A_B_1.ets new file mode 100644 index 0000000000..6fccdc60da --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_import_default_A_B_1.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 "./eitest_export_default_A_1" +import B from "./eitest_export_default_B_1" + +export {A,B} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_export_type_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_type_A_1.ets new file mode 100644 index 0000000000..efebe3f5c0 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_export_type_A_1.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 {} + +export default type CLASS_A = A; \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_1.ets new file mode 100644 index 0000000000..16412b6e62 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_1.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 "./eitest_export_A_1" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/27016.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_1_ne.ets similarity index 64% rename from ets2panda/test/runtime/ets/27016.ets rename to ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_1_ne.ets index fa618d9c23..3fed30fb92 100644 --- a/ets2panda/test/runtime/ets/27016.ets +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_1_ne.ets @@ -13,29 +13,12 @@ * limitations under the License. */ -class NNBB { - static f(a: Object) { - return a instanceof B - } -} +import A from "./eitest_export_A_1" -interface A { - get(): TA -} -interface B extends A { +function main(){ + let a :A = new A() } -class D implements B { - constructor(d: TD) { - this.d = d - } - get(): TD { - return this.d - } - d: TD -} - -function main() { - let a: A = new D(5) - arktest.assertEQ(a.get(), 5) -} +/* @@? 16:15 Error TypeError: Cannot find default imported element in the target */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_2.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_2.ets new file mode 100644 index 0000000000..4eb9ea3c1e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_2.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 "./eitest_export_A_2" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_2_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_2_ne.ets new file mode 100644 index 0000000000..a1da533413 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_2_ne.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 "./eitest_export_A_2" + +function main(){ + let a :A = new A() +} + +/* @@? 16:15 Error TypeError: Cannot find default imported element in the target */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_3.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_3.ets new file mode 100644 index 0000000000..d17ac7f13b --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_3.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 "./eitest_export_B_as_A_1" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_3_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_3_ne.ets new file mode 100644 index 0000000000..5b0fa10162 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_3_ne.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 "./eitest_export_B_as_A_1" + +function main(){ + let a :A = new A() +} + +/* @@? 16:15 Error TypeError: Cannot find default imported element in the target */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_4.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_4.ets new file mode 100644 index 0000000000..48563cfcfb --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_4.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 "./eitest_export_import_A_1" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_4_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_4_ne.ets new file mode 100644 index 0000000000..aa8c172b1f --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_4_ne.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 "./eitest_export_import_A_1" + +function main(){ + let a :A = new A() +} + +/* @@? 16:15 Error TypeError: Cannot find default imported element in the target */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_5.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_5.ets new file mode 100644 index 0000000000..036f643c19 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_5.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 "./eitest_export_import_A_2" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_5_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_5_ne.ets new file mode 100644 index 0000000000..38e266873e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_5_ne.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 "./eitest_export_import_A_2" + +function main(){ + let a :A = new A() +} + +/* @@? 16:15 Error TypeError: Cannot find default imported element in the target */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_6.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_6.ets new file mode 100644 index 0000000000..2ad8f1ce31 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_6.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 "./eitest_export_import_A_3" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_6_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_6_ne.ets new file mode 100644 index 0000000000..06251d9939 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_6_ne.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 "./eitest_export_import_A_3" + +function main(){ + let a :A = new A() +} + +/* @@? 16:15 Error TypeError: Cannot find default imported element in the target */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_7.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_7.ets new file mode 100644 index 0000000000..43b3cbfb6e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_7.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 "./eitest_export_import_default_A_1" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_7_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_7_ne.ets new file mode 100644 index 0000000000..2aa03a66a4 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_7_ne.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 "./eitest_export_import_default_A_1" + +function main(){ + let a :A = new A() +} + +/* @@? 16:15 Error TypeError: Cannot find default imported element in the target */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_B_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_B_1.ets new file mode 100644 index 0000000000..ad032143e5 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_B_1.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 {A,B} from "./eitest_export_import_default_A_B_1" + +function main(){ + let a :A = new A() + let b :B = new B() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_B_1_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_B_1_ne.ets new file mode 100644 index 0000000000..259a491d0a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_A_B_1_ne.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 "./eitest_export_import_default_A_B_1" + +function main(){ + let a :A = new A() +} + +/* @@? 16:15 Error TypeError: Cannot find default imported element in the target */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_1.ets new file mode 100644 index 0000000000..5fa1751e6b --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_1.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 "./eitest_export_default_A_1" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/27016_2.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_1_ne.ets similarity index 75% rename from ets2panda/test/runtime/ets/27016_2.ets rename to ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_1_ne.ets index 9e95ee41cd..da65463362 100644 --- a/ets2panda/test/runtime/ets/27016_2.ets +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_1_ne.ets @@ -13,21 +13,10 @@ * limitations under the License. */ -class A { - f(b: object) { - b instanceof B - let c: B = {v: 1} - return c - } -} - -type B = C +import {A} from "./eitest_export_default_A_1" -interface C { - v: T +function main(){ + let a :A = new A() } -function main() { - let a = new A - arktest.assertEQ(a.f(a).v, 1) -} +/* @@? 16:17 Error TypeError: Use the default import syntax to import a default exported element */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_2.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_2.ets new file mode 100644 index 0000000000..47bcf30f29 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_2.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 B from "./eitest_export_default_A_2" + +function main(){ + let a :B = new B() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_2_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_2_ne.ets new file mode 100644 index 0000000000..6758e4fdde --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_2_ne.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 {B} from "./eitest_export_default_A_2" + +function main(){ + let a :B = new B() +} + +/* @@? 16:17 Error TypeError: Cannot find imported element 'B' */ +/* @@? 19:12 Error TypeError: Cannot find type 'B'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'B'. */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_3.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_3.ets new file mode 100644 index 0000000000..988105af2c --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_3.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 "./eitest_export_default_import_default_A_1" + +function main(){ + let a :A = new A() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_3_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_3_ne.ets new file mode 100644 index 0000000000..95df0589cc --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_default_A_3_ne.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. + */ + +import {A} from "./eitest_export_default_import_default_A_1" + +function main(){ + let a :A = new A() +} + +/* @@? 16:17 Error TypeError: Use the default import syntax to import a default exported element */ \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_type_A_1.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_type_A_1.ets new file mode 100644 index 0000000000..2de45482ea --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_type_A_1.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 CLASS_A from "./eitest_export_type_A_1" + +function main(){ + let a :CLASS_A = new CLASS_A() +} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/eitest_import_type_A_1_ne.ets b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_type_A_1_ne.ets new file mode 100644 index 0000000000..a5e1725a38 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/eitest_import_type_A_1_ne.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. + */ + +import {CLASS_A} from "./eitest_export_type_A_1" + +function main(){ + let a :CLASS_A = new CLASS_A() +} + +/* @@? 16:23 Error TypeError: Use the default import syntax to import a default exported element */ diff --git a/ets2panda/test/ast/compiler/ets/import_export/external_export.ets b/ets2panda/test/ast/compiler/ets/import_export/external_export.ets new file mode 100644 index 0000000000..01ac01d4e9 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/external_export.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 {TT} from "./test1_1" diff --git a/ets2panda/test/ast/compiler/ets/import_export/test1_1.ets b/ets2panda/test/ast/compiler/ets/import_export/test1_1.ets new file mode 100644 index 0000000000..1fb57059d7 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/test1_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. + */ + +import VAR_t from "./test2_1" +export class TT{} \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/test2_1.ets b/ets2panda/test/ast/compiler/ets/import_export/test2_1.ets new file mode 100644 index 0000000000..bcfbd1fa61 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/test2_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. + */ + +import {VAR_i as VAR_o} from "./test3_1" +export default VAR_o +export type VAR_j = string; \ No newline at end of file diff --git a/ets2panda/test/ast/compiler/ets/import_export/test3_1.ets b/ets2panda/test/ast/compiler/ets/import_export/test3_1.ets new file mode 100644 index 0000000000..7ce9d1c5be --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/import_export/test3_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. + */ + +export {VAR_j as VAR_xj} from "./test2_1" +export type VAR_i = int; \ 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 cff206ab65..93f5508e79 100644 --- a/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt +++ b/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt @@ -192,3 +192,32 @@ runtime/ets/implicit_stringliteral_init.ets # #21051 should be log warnings, but there aren't ast/compiler/ets/not_initialized_variable/import_types.ets + +#Issue 22182 +ast/compiler/ets/implicit_package_import/package_test_5/package_module_1.sts + +#import tests, not test cases(path problem) +ast/compiler/ets/import_export/test1_1.ets +ast/compiler/ets/import_export/test1_1.ets +ast/compiler/ets/import_export/eitest_export_default_import_default_A_1.ets +ast/compiler/ets/import_export/eitest_export_import_A_1.ets +ast/compiler/ets/import_export/eitest_export_import_A_2.ets +ast/compiler/ets/import_export/eitest_export_import_A_3.ets +ast/compiler/ets/import_export/eitest_export_import_default_A_1.ets +ast/compiler/ets/import_export/eitest_export_import_default_A_B_1.ets +ast/compiler/ets/import_export/eitest_import_A_1.ets +ast/compiler/ets/import_export/eitest_import_A_2.ets +ast/compiler/ets/import_export/eitest_import_A_3.ets +ast/compiler/ets/import_export/eitest_import_A_4.ets +ast/compiler/ets/import_export/eitest_import_A_5.ets +ast/compiler/ets/import_export/eitest_import_A_6.ets +ast/compiler/ets/import_export/eitest_import_A_7.ets +ast/compiler/ets/import_export/eitest_import_A_B_1.ets +ast/compiler/ets/import_export/eitest_import_default_A_1.ets +ast/compiler/ets/import_export/eitest_import_default_A_2.ets +ast/compiler/ets/import_export/eitest_import_default_A_3.ets +ast/compiler/ets/import_export/eitest_import_type_A_1.ets +ast/compiler/ets/import_export/external_export.ets +ast/compiler/ets/import_export/test1_1.ets +ast/compiler/ets/import_export/test2_1.ets +ast/compiler/ets/import_export/test3_1.ets \ No newline at end of file diff --git a/ets2panda/test/unit/union_normalisation_test.h b/ets2panda/test/unit/union_normalisation_test.h index 0a7312aa66..b91dd9f27a 100644 --- a/ets2panda/test/unit/union_normalisation_test.h +++ b/ets2panda/test/unit/union_normalisation_test.h @@ -94,6 +94,7 @@ public: auto parser = Parser(program, unit.options, diagnosticEngine_, static_cast(unit.rawParserStatus)); + parser.SetContext(publicContext_.get()); auto analyzer = Analyzer(checker); checker->SetAnalyzer(&analyzer); diff --git a/ets2panda/test/utils/checker_test.h b/ets2panda/test/utils/checker_test.h index cd41db0d66..178f764c0c 100644 --- a/ets2panda/test/utils/checker_test.h +++ b/ets2panda/test/utils/checker_test.h @@ -101,6 +101,7 @@ public: compiler_alias::CompilationUnit unit {input, *options, 0, options->GetExtension(), diagnosticEngine_}; auto parser = Parser(program, unit.options, diagnosticEngine_, static_cast(unit.rawParserStatus)); + parser.SetContext(publicContext_.get()); auto analyzer = Analyzer(checker); checker->SetAnalyzer(&analyzer); diff --git a/ets2panda/util/diagnostic/fatal.yaml b/ets2panda/util/diagnostic/fatal.yaml index 0bc08c8af6..5cd4141733 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: SIMULTANEOUSLY_MARK_FAILED + id: 26 + message: "simultaneously compile is not work because of input file paths error." diff --git a/ets2panda/util/importPathManager.cpp b/ets2panda/util/importPathManager.cpp index 7cf0466927..e6d8a1e8b1 100644 --- a/ets2panda/util/importPathManager.cpp +++ b/ets2panda/util/importPathManager.cpp @@ -262,7 +262,7 @@ void ImportPathManager::AddToParseList(const ImportMetadata importMetadata) // surely re-parse it. // // If a file was already not implicitly package imported, then it's just a duplicate, return - if (!found->importData.IsImplicitPackageImported()) { + if (!found->importData.IsImplicitPackageImported() || importMetadata.IsImplicitPackageImported()) { return; } diff --git a/ets2panda/util/importPathManager.h b/ets2panda/util/importPathManager.h index 21095663b0..948b315850 100644 --- a/ets2panda/util/importPathManager.h +++ b/ets2panda/util/importPathManager.h @@ -140,6 +140,12 @@ public: void MarkAsParsed(StringView path); util::StringView FormRelativePath(const util::Path &path); + std::shared_ptr ArkTSConfig() const + { + return arktsConfig_; + } + + void AddToParseList(const ImportMetadata importMetadata); private: util::StringView FormModuleNameSolelyByAbsolutePath(const util::Path &path); @@ -161,7 +167,6 @@ private: std::string TryMatchDynamicPath(std::string_view fixedPath) const; StringView GetRealPath(StringView path) const; - void AddToParseList(const ImportMetadata importMetadata); #ifdef USE_UNIX_SYSCALL void UnixWalkThroughDirectoryAndAddToParseList(ImportMetadata importMetadata); #endif diff --git a/ets2panda/util/options.cpp b/ets2panda/util/options.cpp index 9f42bc27ab..699c636e5b 100644 --- a/ets2panda/util/options.cpp +++ b/ets2panda/util/options.cpp @@ -168,7 +168,7 @@ bool Options::ParseInputOutput() return false; } - if (compilationMode_ == CompilationMode::SINGLE_FILE) { + if (compilationMode_ == CompilationMode::SINGLE_FILE || GetExtension() != ScriptExtension::ETS) { std::ifstream inputStream(SourceFileName()); if (inputStream.fail()) { diagnosticEngine_.LogDiagnostic(diagnostic::OPEN_FAILED, @@ -222,10 +222,10 @@ bool Options::Parse(Span args) #endif DetermineCompilationMode(); - if (!ParseInputOutput()) { + if (!DetermineExtension()) { return false; } - if (!DetermineExtension()) { + if (!ParseInputOutput()) { return false; } if (extension_ != ScriptExtension::JS && IsModule()) { diff --git a/ets2panda/util/options.h b/ets2panda/util/options.h index 47e693e74c..f7bf991b9c 100644 --- a/ets2panda/util/options.h +++ b/ets2panda/util/options.h @@ -77,6 +77,7 @@ public: void DetermineCompilationMode() { compilationMode_ = IsGenStdlib() ? CompilationMode::GEN_STD_LIB + : IsSimultaneous() ? CompilationMode::GEN_ABC_FOR_EXTERNAL_SOURCE : inputFile_.WasSet() ? CompilationMode::SINGLE_FILE : CompilationMode::PROJECT; } diff --git a/ets2panda/util/options.yaml b/ets2panda/util/options.yaml index 3dab3459f6..7b57d1927b 100644 --- a/ets2panda/util/options.yaml +++ b/ets2panda/util/options.yaml @@ -376,5 +376,10 @@ options: - name: perm-arena type: bool - default: true + default: false description: Place AST trees in permanent arena + +- name: simultaneous + type: bool + default: false + description: compile all the files to abc in once. diff --git a/ets2panda/varbinder/ETSBinder.cpp b/ets2panda/varbinder/ETSBinder.cpp index 0f9ae6db10..38e6ab7b42 100644 --- a/ets2panda/varbinder/ETSBinder.cpp +++ b/ets2panda/varbinder/ETSBinder.cpp @@ -388,6 +388,11 @@ void ETSBinder::BuildInterfaceDeclaration(ir::TSInterfaceDeclaration *decl) void ETSBinder::BuildMethodDefinition(ir::MethodDefinition *methodDef) { + if (methodDef->BaseOverloadMethod() != nullptr && + methodDef->GetTopStatement()->AsETSModule()->Program() != Program() && + methodDef->BaseOverloadMethod()->GetTopStatement() != methodDef->GetTopStatement()) { + return; + } if (methodDef->Function()->TypeParams() != nullptr) { auto scopeCtx = LexicalScope::Enter(this, methodDef->Function()->TypeParams()->Scope()); ResolveReferences(methodDef->Function()->TypeParams()); @@ -785,11 +790,96 @@ static bool IsExportedVariable(varbinder::Variable *const var) (var->Declaration()->Node()->IsExported() || var->Declaration()->Node()->IsDefaultExported()); } -ir::ETSImportDeclaration *ETSBinder::FindImportDeclInReExports(const ir::ETSImportDeclaration *const import, - const util::StringView &imported, - const ir::StringLiteral *const importPath) +std::pair ETSBinder::FindImportDeclInExports( + const ir::ETSImportDeclaration *const import, const util::StringView &imported, + const ir::StringLiteral *const importPath) +{ + ir::ETSImportDeclaration *implDecl = nullptr; + ir::AstNode *specifier = nullptr; + std::tie(implDecl, specifier) = FindImportDeclInReExports(import, imported, importPath); + if (implDecl != nullptr) { + return std::make_pair(implDecl, specifier); + } + std::tie(implDecl, specifier) = FindImportDeclInNamedExports(import, imported, importPath); + return std::make_pair(implDecl, specifier); +} + +static std::pair FindImportDeclInProgram(parser::Program *program, + const util::StringView &imported) +{ + for (auto stmt : program->Ast()->AsETSModule()->Statements()) { + if (!stmt->IsETSImportDeclaration()) { + continue; + } + for (auto specifier : stmt->AsETSImportDeclaration()->Specifiers()) { + if (specifier->IsImportSpecifier() && specifier->AsImportSpecifier()->Local()->Name() == imported) { + return std::make_pair(stmt->AsETSImportDeclaration(), specifier); + } + if (specifier->IsImportDefaultSpecifier() && + specifier->AsImportDefaultSpecifier()->Local()->Name() == imported) { + return std::make_pair(stmt->AsETSImportDeclaration(), specifier); + } + } + } + return std::make_pair(nullptr, nullptr); +} + +std::pair ETSBinder::FindImportDeclInNamedExports( + const ir::ETSImportDeclaration *const import, [[maybe_unused]] const util::StringView &imported, + const ir::StringLiteral *const importPath) +{ + auto importMapIter = selectiveExportAliasMultimap_.find(import->ImportMetadata().resolvedSource); + if (importMapIter == selectiveExportAliasMultimap_.end()) { + return std::make_pair(nullptr, nullptr); + } + auto pairIter = importMapIter->second.find(imported); + if (pairIter == importMapIter->second.end()) { + return std::make_pair(nullptr, nullptr); + } + auto [localName, declNode] = pairIter->second; + const auto records = GetExternalProgram(import->ImportMetadata().resolvedSource, importPath); + if (records.empty()) { + return std::make_pair(nullptr, nullptr); + } + auto currProgram = records[0]; + if (currProgram == nullptr) { + return std::make_pair(nullptr, nullptr); + } + auto [newImportDecl, specfier] = FindImportDeclInProgram(currProgram, localName); + if (newImportDecl == nullptr) { + return std::make_pair(nullptr, nullptr); + } + return std::make_pair(newImportDecl->AsETSImportDeclaration(), specfier); +} + +static ir::AstNode *GetSpecifier(const util::StringView &importedLocal, ir::ETSImportDeclaration *decl) +{ + for (auto localSpecfier : decl->Specifiers()) { + util::StringView name; + if (localSpecfier->IsImportSpecifier()) { + name = localSpecfier->AsImportSpecifier()->Local()->Name(); + } else if (localSpecfier->IsImportNamespaceSpecifier()) { + name = localSpecfier->AsImportNamespaceSpecifier()->Local()->Name(); + } else { + name = localSpecfier->AsImportDefaultSpecifier()->Local()->Name(); + } + if (name == importedLocal) { + return localSpecfier; + } + } + if (decl->Specifiers().size() == 1 && decl->Specifiers()[0]->IsImportNamespaceSpecifier()) { + return decl->Specifiers()[0]; + } + ES2PANDA_UNREACHABLE(); +}; + +std::pair ETSBinder::FindImportDeclInReExports( + const ir::ETSImportDeclaration *const import, const util::StringView &imported, + const ir::StringLiteral *const importPath) { ir::ETSImportDeclaration *implDecl = nullptr; + ir::AstNode *specifier = nullptr; + for (auto item : ReExportImports()) { if (!ReexportPathMatchesImportPath(item, import)) { continue; @@ -803,6 +893,7 @@ ir::ETSImportDeclaration *ETSBinder::FindImportDeclInReExports(const ir::ETSImpo continue; } implDecl = item->GetETSImportDeclarations(); + specifier = GetSpecifier(imported, implDecl); } else { const auto records = GetExternalProgram(item->GetETSImportDeclarations()->ResolvedSource(), importPath); if (records.empty()) { @@ -812,17 +903,20 @@ ir::ETSImportDeclaration *ETSBinder::FindImportDeclInReExports(const ir::ETSImpo FindImportSpecifiersVariable(imported, records[0]->GlobalScope()->Bindings(), Span {records}); if (IsExportedVariable(var)) { implDecl = item->GetETSImportDeclarations(); + specifier = GetSpecifier(imported, implDecl); continue; } auto reExportImport = item->GetETSImportDeclarations(); auto reExportImportPath = reExportImport->Source(); - auto implDeclOrNullptr = FindImportDeclInReExports(reExportImport, imported, reExportImportPath); + auto [implDeclOrNullptr, localSpecifier] = + FindImportDeclInExports(reExportImport, imported, reExportImportPath); if (implDeclOrNullptr != nullptr) { implDecl = implDeclOrNullptr; + specifier = GetSpecifier(imported, implDecl); } } } - return implDecl; + return std::make_pair(implDecl, specifier); } void ETSBinder::ValidateImportVariable(const ir::AstNode *node, const util::StringView &imported, @@ -856,6 +950,46 @@ bool ETSBinder::DetectNameConflict(const util::StringView localName, Variable *c return true; } +Variable *ETSBinder::AddImportSpecifierFromReExport(ir::AstNode *importSpecifier, + const ir::ETSImportDeclaration *const import, + const util::StringView &imported, + const ir::StringLiteral *const importPath) +{ + auto [implDecl, localSpecifier] = FindImportDeclInExports(import, imported, importPath); + Variable *localVar = nullptr; + auto insertBinding = [this, importSpecifier, import](Variable *var) { + if (importSpecifier->IsImportSpecifier()) { + this->InsertOrAssignForeignBinding(importSpecifier, import, + importSpecifier->AsImportSpecifier()->Local()->Name(), var); + importSpecifier->AsImportSpecifier()->Local()->SetVariable(var); + importSpecifier->AsImportSpecifier()->Imported()->SetVariable(var); + } else if (importSpecifier->IsImportDefaultSpecifier()) { + this->InsertOrAssignForeignBinding(importSpecifier, import, + importSpecifier->AsImportDefaultSpecifier()->Local()->Name(), var); + importSpecifier->AsImportDefaultSpecifier()->Local()->SetVariable(var); + } + }; + if (implDecl != nullptr) { + if (localSpecifier->IsImportSpecifier() || localSpecifier->IsImportDefaultSpecifier()) { + AddSpecifiersToTopBindings(localSpecifier, implDecl); + if (localSpecifier->IsImportSpecifier()) { + localVar = localSpecifier->AsImportSpecifier()->Imported()->Variable(); + insertBinding(localVar); + } else if (localSpecifier->IsImportDefaultSpecifier()) { + localVar = localSpecifier->AsImportDefaultSpecifier()->Local()->Variable(); + insertBinding(localVar); + } + } else { + AddSpecifiersToTopBindings(importSpecifier, implDecl); + } + + return localVar; + } + + ThrowError(importPath->Start(), diagnostic::IMPORT_NOT_FOUND, {imported}); + return nullptr; +} + // CC-OFFNXT(huge_method, G.FUN.01-CPP) solid logic bool ETSBinder::AddImportSpecifiersToTopBindings(Span records, ir::ImportSpecifier *const importSpecifier, @@ -882,18 +1016,14 @@ bool ETSBinder::AddImportSpecifiersToTopBindings(Span re nameToSearchFor = imported; } - auto *const var = FindImportSpecifiersVariable(nameToSearchFor, globalBindings, records); + auto *var = FindImportSpecifiersVariable(nameToSearchFor, globalBindings, records); importSpecifier->Imported()->SetVariable(var); importSpecifier->Local()->SetVariable(var); if (var == nullptr) { - ir::ETSImportDeclaration *implDecl = FindImportDeclInReExports(import, imported, importPath); - if (implDecl != nullptr) { - AddSpecifiersToTopBindings(importSpecifier, implDecl); - return true; - } - - ThrowError(importPath->Start(), diagnostic::IMPORT_NOT_FOUND, {imported}); + var = AddImportSpecifierFromReExport(importSpecifier, import, imported, importPath); + } + if (var == nullptr) { return false; } @@ -938,9 +1068,15 @@ void ETSBinder::AddImportDefaultSpecifiersToTopBindings(Spansecond.begin(), selectMap2->second.end(), isDefaultExpored); if (item1 != selectMap2->second.end()) { - auto item2 = FindImportSpecifiersVariable(item1->first, globalBindings, records); - importDefaultSpecifier->Local()->SetVariable(item2); - InsertForeignBinding(importDefaultSpecifier, import, importDefaultSpecifier->Local()->Name(), item2); + auto var = FindImportSpecifiersVariable(item1->first, globalBindings, records); + if (var == nullptr) { + var = AddImportSpecifierFromReExport(importDefaultSpecifier, import, item1->first, import->Source()); + } + if (var == nullptr) { + return; + } + importDefaultSpecifier->Local()->SetVariable(var); + InsertOrAssignForeignBinding(importDefaultSpecifier, import, importDefaultSpecifier->Local()->Name(), var); return; } } @@ -1192,12 +1328,21 @@ void ETSBinder::InitImplicitThisParam() void ETSBinder::BuildProgram() { + // A tmp solution caused by #23877, needs to check stdlib first to avoid a bug in std/math/math.ets + // After the bug fixed, we can merge these 2 loop. + static const std::string STD_SUFFIX = "std."; + for (auto &[_, extPrograms] : Program()->ExternalSources()) { + if (_.Utf8().substr(0, STD_SUFFIX.length()) == STD_SUFFIX) { + for (auto *extProg : extPrograms) { + BuildExternalProgram(extProg); + } + } + } for (auto &[_, extPrograms] : Program()->ExternalSources()) { (void)_; - for (auto *extProg : extPrograms) { - if (!extProg->GetFlag(parser::ProgramFlags::AST_IDENTIFIER_ANALYZED)) { + if (_.Utf8().substr(0, STD_SUFFIX.length()) != STD_SUFFIX) { + for (auto *extProg : extPrograms) { BuildExternalProgram(extProg); - extProg->SetFlag(parser::ProgramFlags::AST_IDENTIFIER_ANALYZED); } } } @@ -1232,7 +1377,9 @@ void ETSBinder::BuildExternalProgram(parser::Program *extProgram) auto *savedRecordTable = recordTable_; auto *savedTopScope = TopScope(); - auto flags = Program()->VarBinder()->IsGenStdLib() ? RecordTableFlags::NONE : RecordTableFlags::EXTERNAL; + auto flags = Program()->VarBinder()->IsGenStdLib() || (extProgram->IsGenAbcForExternal()) + ? RecordTableFlags::NONE + : RecordTableFlags::EXTERNAL; auto *extRecordTable = Allocator()->New(Allocator(), extProgram, flags); externalRecordTable_.insert({extProgram, extRecordTable}); @@ -1301,7 +1448,7 @@ Variable *ETSBinder::ValidateImportSpecifier(const ir::ImportSpecifier *const sp } // Failed to find variable, go through reexports - const ir::ETSImportDeclaration *const implDecl = FindImportDeclInReExports(import, imported, import->Source()); + auto [implDecl, localSpecifier] = FindImportDeclInExports(import, imported, import->Source()); if (implDecl != nullptr) { return ValidateImportSpecifier(specifier, implDecl); } @@ -1427,24 +1574,28 @@ const DynamicImportData *ETSBinder::DynamicImportDataForVar(const Variable *var) return &it->second; } -ArenaVector ETSBinder::GetProgramList(const util::StringView &path) const noexcept +ArenaVector ETSBinder::GetProgramList(const util::StringView &oldPath) const noexcept { auto const *globalProgram = globalRecordTable_.Program(); + util::StringView newPath = oldPath; + if (auto it = GetContext()->dupPrograms.find(oldPath); it != GetContext()->dupPrograms.end()) { + newPath = it->second->AbsoluteName(); + } for (const auto &extRecords : globalProgram->ExternalSources()) { for (const auto &program : extRecords.second) { - if (program->AbsoluteName() == path) { + if (program->AbsoluteName() == newPath) { return extRecords.second; } // in case of importing a package folder, the path could not be resolved to a specific file - if (program->IsPackage() && program->SourceFileFolder() == path) { + if (program->IsPackage() && program->SourceFileFolder() == newPath) { return extRecords.second; } } } - if (globalProgram->IsPackage() && path.Compare(globalProgram->SourceFileFolder()) == 0) { + if (globalProgram->IsPackage() && newPath.Compare(globalProgram->SourceFileFolder()) == 0) { return ArenaVector({GetContext()->parserProgram}, Allocator()->Adapter()); } diff --git a/ets2panda/varbinder/ETSBinder.h b/ets2panda/varbinder/ETSBinder.h index 6d24b0f3c7..bc0096047f 100644 --- a/ets2panda/varbinder/ETSBinder.h +++ b/ets2panda/varbinder/ETSBinder.h @@ -154,9 +154,18 @@ public: [[nodiscard]] ArenaVector GetExternalProgram(util::StringView sourceName, const ir::StringLiteral *importPath); - ir::ETSImportDeclaration *FindImportDeclInReExports(const ir::ETSImportDeclaration *const import, - const util::StringView &imported, - const ir::StringLiteral *const importPath); + std::pair FindImportDeclInReExports( + const ir::ETSImportDeclaration *const import, const util::StringView &imported, + const ir::StringLiteral *const importPath); + std::pair FindImportDeclInNamedExports( + const ir::ETSImportDeclaration *const import, const util::StringView &imported, + const ir::StringLiteral *const importPath); + std::pair FindImportDeclInExports( + const ir::ETSImportDeclaration *const import, const util::StringView &imported, + const ir::StringLiteral *const importPath); + ir::ETSImportDeclaration *FindImportDeclIn(const ir::ETSImportDeclaration *const import, + const util::StringView &imported, + const ir::StringLiteral *const importPath); void AddImportNamespaceSpecifiersToTopBindings(Span records, ir::ImportNamespaceSpecifier *namespaceSpecifier, const ir::ETSImportDeclaration *import); @@ -171,6 +180,9 @@ public: const varbinder::Scope::VariableMap &globalBindings, Span record); Variable *FindStaticBinding(Span records, const ir::StringLiteral *importPath); + Variable *AddImportSpecifierFromReExport(ir::AstNode *importSpecifier, const ir::ETSImportDeclaration *const import, + const util::StringView &imported, + const ir::StringLiteral *const importPath); void AddSpecifiersToTopBindings(ir::AstNode *const specifier, const ir::ETSImportDeclaration *const import); void AddDynamicSpecifiersToTopBindings(ir::AstNode *const specifier, const ir::ETSImportDeclaration *const import); -- Gitee From 234abbd0551fdf35eef22f635d7c2bfd437d9c30 Mon Sep 17 00:00:00 2001 From: yaohaosen Date: Thu, 3 Jul 2025 16:32:36 +0800 Subject: [PATCH 065/145] [LSP] Pick LSP fix commits from 0328 to 0603 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJKCH Signed-off-by: yaohaosen --- .../test/expected/getSemanticDiagnostics.json | 6 +-- .../expected/getSyntacticDiagnostics.json | 48 +++++++++---------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/ets2panda/bindings/test/expected/getSemanticDiagnostics.json b/ets2panda/bindings/test/expected/getSemanticDiagnostics.json index 679a81c056..851be1ff14 100644 --- a/ets2panda/bindings/test/expected/getSemanticDiagnostics.json +++ b/ets2panda/bindings/test/expected/getSemanticDiagnostics.json @@ -19,7 +19,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 2046, "data": 0, "severity": 1, "codeDescription": { @@ -41,7 +41,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 2127, "data": 0, "severity": 1, "codeDescription": { @@ -63,7 +63,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 2318, "data": 0, "severity": 1, "codeDescription": { diff --git a/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json b/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json index 35b5984191..9383b5339f 100644 --- a/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json +++ b/ets2panda/bindings/test/expected/getSyntacticDiagnostics.json @@ -19,7 +19,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -41,7 +41,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1229, "data": 0, "severity": 1, "codeDescription": { @@ -63,7 +63,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -85,7 +85,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -93,21 +93,21 @@ } }, { - "message": "Unexpected token ':'.", - "source": "*ERROR_LITERAL*", + "message": "Unexpected token 'number'.", + "source": "number", "range": { "start": { "line": 16, - "character": 14 + "character": 16 }, "end": { "line": 16, - "character": 15 + "character": 22 } }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -129,7 +129,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -151,7 +151,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -159,21 +159,21 @@ } }, { - "message": "Unexpected token ','.", - "source": "*ERROR_LITERAL*", + "message": "Unexpected token 'b'.", + "source": "", "range": { "start": { "line": 16, - "character": 22 + "character": 24 }, "end": { "line": 16, - "character": 23 + "character": 24 } }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -195,7 +195,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1038, "data": 0, "severity": 1, "codeDescription": { @@ -217,7 +217,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -239,7 +239,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -252,16 +252,16 @@ "range": { "start": { "line": 16, - "character": 33 + "character": 35 }, "end": { - "line": 16, - "character": 34 + "line": 18, + "character": 2 } }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1227, "data": 0, "severity": 1, "codeDescription": { @@ -283,7 +283,7 @@ }, "tags": [], "relatedInfo": [], - "code": 1, + "code": 1163, "data": 0, "severity": 1, "codeDescription": { -- Gitee From 9f21b3bd73d643923635783e9518cdded98ca83f Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Thu, 3 Jul 2025 20:37:24 +0800 Subject: [PATCH 066/145] Clear program flag before recheck Issue: https://gitee.com/openharmony/developtools_ace_ets2bundle/issues/ICJQJ2 Description: Clear program flag before recheck Reason: because the branch difference, 0603 met an crash while 0328 runs okay, because 0328 contain the ast-cache feature, some logic of program flag handling were omitted 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/compiler/lowering/util.cpp | 1 + ets2panda/parser/program/program.cpp | 5 +++++ ets2panda/parser/program/program.h | 1 + 3 files changed, 7 insertions(+) diff --git a/ets2panda/compiler/lowering/util.cpp b/ets2panda/compiler/lowering/util.cpp index 09fe048e25..83d98e260c 100644 --- a/ets2panda/compiler/lowering/util.cpp +++ b/ets2panda/compiler/lowering/util.cpp @@ -166,6 +166,7 @@ static bool IsGeneratedDynamicClass(ir::AstNode const *ast) static void ClearHelper(parser::Program *prog) { ResetGlobalClass(prog); + prog->ClearASTCheckedStatus(); // #24256 Should be removed when code refactoring on checker is done and no ast node allocated in checker. auto &stmts = prog->Ast()->Statements(); // clang-format off diff --git a/ets2panda/parser/program/program.cpp b/ets2panda/parser/program/program.cpp index 3d6ecb19e6..376d2d76dc 100644 --- a/ets2panda/parser/program/program.cpp +++ b/ets2panda/parser/program/program.cpp @@ -134,6 +134,11 @@ bool Program::GetFlag(ProgramFlags flag) const return (programFlags_ & flag) != 0U; } +void Program::ClearASTCheckedStatus() +{ + programFlags_ &= ~ProgramFlags::AST_CHECKED; +} + void Program::SetASTChecked() { programFlags_ |= ProgramFlags::AST_CHECKED; diff --git a/ets2panda/parser/program/program.h b/ets2panda/parser/program/program.h index d3e0ac67a6..eaee6b9d76 100644 --- a/ets2panda/parser/program/program.h +++ b/ets2panda/parser/program/program.h @@ -287,6 +287,7 @@ public: void SetFlag(ProgramFlags flag); bool GetFlag(ProgramFlags flag) const; void SetASTChecked(); + void ClearASTCheckedStatus(); bool IsASTChecked(); bool IsStdLib() const -- Gitee From 2dc004b6d4457cb902e9b895de483edb43386ba5 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Sun, 29 Jun 2025 17:00:31 +0800 Subject: [PATCH 067/145] Fix interface method cannot be used as value Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJNHU Signed-off-by: tengtengh --- ets2panda/checker/ETSAnalyzer.cpp | 17 ++++- .../compiler/lowering/ets/lambdaLowering.cpp | 66 +++++++++++++------ .../ets/interface_method_as_value_1.ets | 23 +++++++ .../ets/interface_method_as_value_2.ets | 33 ++++++++++ 4 files changed, 116 insertions(+), 23 deletions(-) create mode 100644 ets2panda/test/runtime/ets/interface_method_as_value_1.ets create mode 100644 ets2panda/test/runtime/ets/interface_method_as_value_2.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index f8f1ec7e37..6a3b6e1e60 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -1663,12 +1663,25 @@ static Type *TransformTypeForMethodReference(ETSChecker *checker, ir::Expression return type; // type is actually used as method } - if (type->AsETSFunctionType()->CallSignatures().at(0)->HasSignatureFlag(SignatureFlags::PRIVATE)) { + auto *const functionType = type->AsETSFunctionType(); + auto &signatures = functionType->CallSignatures(); + + if (signatures.at(0)->HasSignatureFlag(SignatureFlags::PRIVATE)) { checker->LogError(diagnostic::PRIVATE_METHOD_AS_VALUE, getUseSite()); return checker->GlobalTypeError(); } - if (type->AsETSFunctionType()->CallSignatures().size() > 1) { + auto it = signatures.begin(); + while (it != signatures.end()) { + if ((*it)->HasSignatureFlag(SignatureFlags::ABSTRACT) && + !(*it)->Owner()->GetDeclNode()->IsTSInterfaceDeclaration()) { + it = signatures.erase(it); + } else { + ++it; + } + } + + if (signatures.size() > 1U) { checker->LogError(diagnostic::OVERLOADED_METHOD_AS_VALUE, getUseSite()); return checker->GlobalTypeError(); } diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index c513801d30..27a4d80197 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -25,6 +25,7 @@ namespace ark::es2panda::compiler { struct LambdaInfo { ir::ClassDeclaration *calleeClass = nullptr; + ir::TSInterfaceDeclaration *calleeInterface = nullptr; ir::ScriptFunction *enclosingFunction = nullptr; util::StringView name = ""; util::StringView originalFuncName = ""; @@ -424,10 +425,12 @@ static void CreateLambdaClassFields(public_lib::Context *ctx, ir::ClassDefinitio auto *checker = ctx->checker->AsETSChecker(); auto props = ArenaVector(allocator->Adapter()); + checker::Type *objectType = + info->calleeClass != nullptr ? info->calleeClass->Definition()->TsType() : info->calleeInterface->TsType(); + if (info->callReceiver != nullptr) { auto *outerThisDeclaration = parser->CreateFormattedClassFieldDefinition( - "@@I1: @@T2", "$this", - info->calleeClass->Definition()->TsType()->Substitute(checker->Relation(), substitution)); + "@@I1: @@T2", "$this", objectType->Substitute(checker->Relation(), substitution)); props.push_back(outerThisDeclaration); } @@ -457,8 +460,11 @@ static void CreateLambdaClassConstructor(public_lib::Context *ctx, ir::ClassDefi params.push_back(param); }; + checker::Type *objectType = + info->calleeClass != nullptr ? info->calleeClass->Definition()->TsType() : info->calleeInterface->TsType(); + if (info->callReceiver != nullptr) { - makeParam("$this", info->calleeClass->Definition()->TsType()); + makeParam("$this", objectType); } for (auto *var : *info->capturedVars) { makeParam(AvoidMandatoryThis(var->Name()), var->TsType()); @@ -805,7 +811,11 @@ static ir::ClassDeclaration *CreateEmptyLambdaClassDeclaration(public_lib::Conte auto *varBinder = ctx->checker->VarBinder()->AsETSBinder(); auto lambdaClassName = util::UString {std::string_view {"LambdaObject-"}, allocator}; - lambdaClassName.Append(info->calleeClass->Definition()->Ident()->Name()).Append("$").Append(info->name); + + util::StringView &objectName = info->calleeClass != nullptr ? info->calleeClass->Definition()->Ident()->Name() + : info->calleeInterface->Id()->Name(); + + lambdaClassName.Append(objectName).Append("$").Append(info->name); auto *providerTypeReference = checker->AllocNode( checker->AllocNode( @@ -924,8 +934,10 @@ static ir::ETSNewClassInstanceExpression *CreateConstructorCall(public_lib::Cont auto lexScope = varbinder::LexicalScope::Enter(varBinder, nearestScope); varBinder->ResolveReferencesForScopeWithContext(newExpr, nearestScope); - auto checkerCtx = checker::SavedCheckerContext(ctx->checker, checker::CheckerStatus::IN_CLASS, - info->calleeClass->Definition()->TsType()->AsETSObjectType()); + checker::Type *objectType = + info->calleeClass != nullptr ? info->calleeClass->Definition()->TsType() : info->calleeInterface->TsType(); + auto checkerCtx = + checker::SavedCheckerContext(ctx->checker, checker::CheckerStatus::IN_CLASS, objectType->AsETSObjectType()); auto scopeCtx = checker::ScopeContext(ctx->checker, nearestScope); newExpr->Check(checker); @@ -1034,9 +1046,34 @@ static ir::ArrowFunctionExpression *CreateWrappingLambda(public_lib::Context *ct return lambda; } -static ir::AstNode *ConvertFunctionReference(public_lib::Context *ctx, ir::Expression *funcRef) +static LambdaInfo GenerateLambdaInfoForFunctionReference(public_lib::Context *ctx, ir::Expression *funcRef, + ir::MethodDefinition *method) { auto *allocator = ctx->allocator; + LambdaInfo info; + if (method->Parent()->Parent()->IsClassDeclaration()) { + info.calleeClass = method->Parent()->Parent()->AsClassDeclaration(); + } else if (method->Parent()->Parent()->IsTSInterfaceDeclaration()) { + info.calleeInterface = method->Parent()->Parent()->AsTSInterfaceDeclaration(); + } else { + ES2PANDA_UNREACHABLE(); + } + info.enclosingFunction = nullptr; + info.name = CreateCalleeName(allocator); + info.originalFuncName = method->Id()->Name(); + info.capturedVars = allocator->New>(allocator->Adapter()); + info.isFunctionReference = true; + if (method->IsStatic()) { + info.callReceiver = nullptr; + } else { + ES2PANDA_ASSERT(funcRef->IsMemberExpression()); + info.callReceiver = funcRef->AsMemberExpression()->Object(); + } + return info; +} + +static ir::AstNode *ConvertFunctionReference(public_lib::Context *ctx, ir::Expression *funcRef) +{ ES2PANDA_ASSERT(funcRef->IsIdentifier() || (funcRef->IsMemberExpression() && funcRef->AsMemberExpression()->Kind() == ir::MemberExpressionKind::PROPERTY_ACCESS && @@ -1071,20 +1108,7 @@ static ir::AstNode *ConvertFunctionReference(public_lib::Context *ctx, ir::Expre return lam == nullptr ? funcRef : ConvertLambda(ctx, lam); } - LambdaInfo info; - info.calleeClass = method->Parent()->Parent()->AsClassDeclaration(); - info.enclosingFunction = nullptr; - info.name = CreateCalleeName(allocator); - info.originalFuncName = method->Id()->Name(); - auto emptySet = ArenaSet(allocator->Adapter()); - info.capturedVars = &emptySet; - info.isFunctionReference = true; - if (method->IsStatic()) { - info.callReceiver = nullptr; - } else { - ES2PANDA_ASSERT(funcRef->IsMemberExpression()); - info.callReceiver = funcRef->AsMemberExpression()->Object(); - } + LambdaInfo info = GenerateLambdaInfoForFunctionReference(ctx, funcRef, method); ES2PANDA_ASSERT(funcRef->TsType()->IsETSArrowType()); auto *lambdaClass = CreateLambdaClass(ctx, funcRef->TsType()->AsETSFunctionType(), method, &info); diff --git a/ets2panda/test/runtime/ets/interface_method_as_value_1.ets b/ets2panda/test/runtime/ets/interface_method_as_value_1.ets new file mode 100644 index 0000000000..a5895a5ec0 --- /dev/null +++ b/ets2panda/test/runtime/ets/interface_method_as_value_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. + */ + +function process(step1: I): void { + let y = step1.evalute + let z = y(); +} + +interface I { + evalute(): number +} diff --git a/ets2panda/test/runtime/ets/interface_method_as_value_2.ets b/ets2panda/test/runtime/ets/interface_method_as_value_2.ets new file mode 100644 index 0000000000..b1a715377f --- /dev/null +++ b/ets2panda/test/runtime/ets/interface_method_as_value_2.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. + */ + +function process(step1: I): void { + let y = step1.evalute + let z = y(); + arktest.assertEQ(z, 123) +} + +interface I { + evalute(): number +} + +class A implements I{ + evalute(): number { + return 123; + } +} + +process(new A()); + -- Gitee From 44cb78510a79f96a3c5cd475ad8e96c76f525a87 Mon Sep 17 00:00:00 2001 From: Boglarka Haag Date: Mon, 30 Jun 2025 13:34:50 +0200 Subject: [PATCH 068/145] Fix crash on callbacks Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJUEE Reason: Fixed crash when generic callback function was called with less params then expected Description: Modified EnchanceSignatureSubstitution Fixes internal issue: #26930 Signed-off-by: Haag Boglarka --- .../checker/types/ets/etsFunctionType.cpp | 2 +- .../ast/compiler/ets/generic_callback.ets | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/generic_callback.ets diff --git a/ets2panda/checker/types/ets/etsFunctionType.cpp b/ets2panda/checker/types/ets/etsFunctionType.cpp index 1df9fd28ea..f6e132065e 100644 --- a/ets2panda/checker/types/ets/etsFunctionType.cpp +++ b/ets2panda/checker/types/ets/etsFunctionType.cpp @@ -162,7 +162,7 @@ static Signature *EnhanceSignatureSubstitution(TypeRelation *relation, Signature auto const enhance = [checker, sub, substitution](Type *param, Type *arg) { return checker->EnhanceSubstitutionForType(sub->GetSignatureInfo()->typeParams, param, arg, substitution); }; - for (size_t ix = 0; ix < super->MinArgCount(); ix++) { + for (size_t ix = 0; ix < sub->ArgCount(); ix++) { if (!enhance(sub->GetSignatureInfo()->params[ix]->TsType(), super->GetSignatureInfo()->params[ix]->TsType())) { return nullptr; } diff --git a/ets2panda/test/ast/compiler/ets/generic_callback.ets b/ets2panda/test/ast/compiler/ets/generic_callback.ets new file mode 100644 index 0000000000..92c4b7ad7e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/generic_callback.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 identity(a: A): A { + return a; +} +let x = [1, 2, 3].map(identity)[0]; + +/* @@? 19:9 Error TypeError: No matching call signature for map((a: A) => A) */ +/* @@? 19:9 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 19:9 Error TypeError: No matching call signature for map((a: A) => A) */ +/* @@? 19:9 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 19:23 Error TypeError: Type '(a: A) => A' is not compatible with type '(value: Int, index: Double, array: Array) => A' at index 1 */ +/* @@? 19:23 Error TypeError: Type '(a: A) => A' is not compatible with type '(value: Int, index: Double, array: ReadonlyArray) => A' at index 1 */ +/* @@? 19:23 Error TypeError: Type '(a: A) => A' is not compatible with type '(value: Int, index: Double, array: Array) => A' at index 1 */ +/* @@? 19:23 Error TypeError: Type '(a: A) => A' is not compatible with type '(value: Int, index: Double, array: ReadonlyArray) => A' at index 1 */ -- Gitee From 7563ba05db4c422525f0f2cdc51c93e5985430b1 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Mon, 30 Jun 2025 11:58:39 +0800 Subject: [PATCH 069/145] Fix bug of async method Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIQHV?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ets/aliveAnalyzer.cpp | 16 +++++--- .../ets/not_all_paths_return_value.ets | 39 +++++++++++++++++++ 2 files changed, 49 insertions(+), 6 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/not_all_paths_return_value.ets diff --git a/ets2panda/checker/ets/aliveAnalyzer.cpp b/ets2panda/checker/ets/aliveAnalyzer.cpp index ff2ba27302..f85ae6b54e 100644 --- a/ets2panda/checker/ets/aliveAnalyzer.cpp +++ b/ets2panda/checker/ets/aliveAnalyzer.cpp @@ -246,15 +246,19 @@ void AliveAnalyzer::AnalyzeMethodDef(const ir::MethodDefinition *methodDef) auto isPromiseVoid = false; - if (returnType->IsETSAsyncFuncReturnType()) { - const auto *asAsync = returnType->AsETSAsyncFuncReturnType(); - isPromiseVoid = asAsync->GetPromiseTypeArg() == checker_->GlobalETSUndefinedType(); + if (returnType->IsETSObjectType() && + returnType->AsETSObjectType()->AssemblerName() == compiler::Signatures::BUILTIN_PROMISE) { + const auto *asAsync = returnType->AsETSObjectType(); + isPromiseVoid = asAsync->TypeArguments().front() == checker_->GlobalETSUndefinedType() || + asAsync->TypeArguments().front() == checker_->GlobalVoidType(); } - if (status_ == LivenessStatus::ALIVE && !isVoid && !isPromiseVoid && !util::Helpers::IsAsyncMethod(methodDef)) { + if (status_ == LivenessStatus::ALIVE && !isVoid && !isPromiseVoid) { if (!methodDef->Function()->HasReturnStatement()) { - checker_->LogError(diagnostic::MISSING_RETURN_STMT, {}, func->Start()); - ClearPendingExits(); + if (!util::Helpers::IsAsyncMethod(methodDef)) { + checker_->LogError(diagnostic::MISSING_RETURN_STMT, {}, func->Start()); + ClearPendingExits(); + } return; } diff --git a/ets2panda/test/ast/compiler/ets/not_all_paths_return_value.ets b/ets2panda/test/ast/compiler/ets/not_all_paths_return_value.ets new file mode 100644 index 0000000000..cf3a75670a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/not_all_paths_return_value.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. + */ + +async function test1(isError: boolean) { + if (isError) { + return 1 + } + // error not all code paths return a value. +} + +async function test(isError: boolean): Promise { + if (isError) { + return Promise.resolve("undefined") + } + // error not all code paths return a value. +} + + +async function test2(isError: boolean): Promise { //ok + if (isError) { + return Promise.resolve(undefined) + } +} + + +/* @@? 16:16 Error TypeError: Not all code paths return a value. */ +/* @@? 23:16 Error TypeError: Not all code paths return a value. */ -- Gitee From 6ea79e99297b095b5dec33d82e02f0093e6b4f12 Mon Sep 17 00:00:00 2001 From: fcc Date: Sat, 28 Jun 2025 10:11:56 +0800 Subject: [PATCH 070/145] Fix for-of string type For-of string type should call string type's iterator. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIF8H Signed-off-by: fcc --- ets2panda/checker/ETSAnalyzer.cpp | 2 +- ets2panda/checker/ETSAnalyzerHelpers.cpp | 2 +- .../compiler/lowering/ets/objectIterator.cpp | 6 +-- .../test/ast/compiler/ets/func_as_param.ets | 2 +- .../ast/parser/ets/FixedArray/for_of_02.ets | 6 +-- ets2panda/test/ast/parser/ets/for_of_02.ets | 6 +-- ets2panda/test/parser/ets/for_of-expected.txt | 44 ++++++++++++++++--- ets2panda/test/parser/ets/for_of.ets | 4 +- ets2panda/test/runtime/ets/ForOfBoxing.ets | 2 +- ets2panda/test/runtime/ets/ForOfUnion.ets | 4 +- ets2panda/test/runtime/ets/forOfString.ets | 25 +++++++++++ 11 files changed, 80 insertions(+), 23 deletions(-) create mode 100644 ets2panda/test/runtime/ets/forOfString.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index f8f1ec7e37..2fe276487a 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -3005,7 +3005,7 @@ checker::Type *ETSAnalyzer::Check(ir::ForOfStatement *const st) const checker::Type *elemType = checker->GlobalTypeError(); if (exprType->IsETSStringType()) { - elemType = checker->GetGlobalTypesHolder()->GlobalCharType(); + elemType = checker->GlobalBuiltinETSStringType(); } else if (exprType->IsETSArrayType() || exprType->IsETSResizableArrayType()) { elemType = checker->GetElementTypeOfArray(exprType); } else if (exprType->IsETSObjectType() || exprType->IsETSUnionType() || exprType->IsETSTypeParameter()) { diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index f652f68e78..6b4208e562 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -611,7 +611,7 @@ checker::Type *GetIteratorType(ETSChecker *checker, checker::Type *elemType, ir: checker->LogError(diagnostic::ITERATOR_TYPE_ABSENT, {}, left->Start()); return checker->GlobalTypeError(); } - return iterType; + return checker->GetNonConstantType(iterType); } bool CheckArgumentVoidType(checker::Type *&funcReturnType, ETSChecker *checker, const std::string &name, diff --git a/ets2panda/compiler/lowering/ets/objectIterator.cpp b/ets2panda/compiler/lowering/ets/objectIterator.cpp index cf43ac31d1..ebaf767866 100644 --- a/ets2panda/compiler/lowering/ets/objectIterator.cpp +++ b/ets2panda/compiler/lowering/ets/objectIterator.cpp @@ -157,7 +157,8 @@ ir::Statement *ObjectIteratorLowering::ProcessObjectIterator(public_lib::Context declaration->Kind() != ir::VariableDeclaration::VariableDeclarationKind::CONST ? "let " : "const "; loopVariableIdent = declaration->Declarators().at(0U)->Id()->AsIdentifier()->Clone(allocator, nullptr); } else if (left->IsIdentifier()) { - loopVariableIdent = left->AsIdentifier()->Clone(allocator, nullptr); + loopVariableIdent = Gensym(allocator); + loopVariableIdent->SetName(left->AsIdentifier()->Name()); } else { ES2PANDA_UNREACHABLE(); } @@ -189,8 +190,7 @@ ir::Statement *ObjectIteratorLowering::ProcessObjectIterator(public_lib::Context bool ObjectIteratorLowering::PerformForModule(public_lib::Context *ctx, parser::Program *program) { auto hasIterator = [](checker::Type const *const exprType) -> bool { - return exprType != nullptr && - ((exprType->IsETSObjectType() && !exprType->IsETSStringType()) || exprType->IsETSTypeParameter()); + return exprType != nullptr && (exprType->IsETSObjectType() || exprType->IsETSTypeParameter()); }; program->Ast()->TransformChildrenRecursively( diff --git a/ets2panda/test/ast/compiler/ets/func_as_param.ets b/ets2panda/test/ast/compiler/ets/func_as_param.ets index 43f1c47d80..cccaa0f81b 100644 --- a/ets2panda/test/ast/compiler/ets/func_as_param.ets +++ b/ets2panda/test/ast/compiler/ets/func_as_param.ets @@ -27,7 +27,7 @@ function getFunctionArgumentsCount(funcStr: string): number { const regex = new RegExp("^[0123456789]$", "g") let count = "" for(let ch of funcStr) { - let str = new Char(ch).toString(); + let str = ch; if(regex.test(str)) { count = str } diff --git a/ets2panda/test/ast/parser/ets/FixedArray/for_of_02.ets b/ets2panda/test/ast/parser/ets/FixedArray/for_of_02.ets index fd74b049d9..36cb1a26db 100644 --- a/ets2panda/test/ast/parser/ets/FixedArray/for_of_02.ets +++ b/ets2panda/test/ast/parser/ets/FixedArray/for_of_02.ets @@ -15,11 +15,11 @@ let a: FixedArray = [1, 2, 3]; -function forins(): int { - for (let i: int of "abcdef") { +function forins(): string { + for (let i: string of "abcdef") { return i; } - return c'*'; + return '*'; } function main(): void { diff --git a/ets2panda/test/ast/parser/ets/for_of_02.ets b/ets2panda/test/ast/parser/ets/for_of_02.ets index 535270a596..2a4fd2ce83 100644 --- a/ets2panda/test/ast/parser/ets/for_of_02.ets +++ b/ets2panda/test/ast/parser/ets/for_of_02.ets @@ -15,11 +15,11 @@ let a: int[] = [1, 2, 3]; -function forins(): int { - for (let i: int of "abcdef") { +function forins(): string { + for (let i: string of "abcdef") { return i; } - return c'*'; + return '*'; } function main(): void { diff --git a/ets2panda/test/parser/ets/for_of-expected.txt b/ets2panda/test/parser/ets/for_of-expected.txt index 2a62e69595..149a169895 100644 --- a/ets2panda/test/parser/ets/for_of-expected.txt +++ b/ets2panda/test/parser/ets/for_of-expected.txt @@ -981,7 +981,39 @@ "expression": false, "params": [], "returnType": { - "type": "ETSPrimitiveType", + "type": "ETSTypeReference", + "part": { + "type": "ETSTypeReferencePart", + "name": { + "type": "Identifier", + "name": "string", + "decorators": [], + "loc": { + "start": { + "line": 28, + "column": 20, + "program": "for_of.ets" + }, + "end": { + "line": 28, + "column": 26, + "program": "for_of.ets" + } + } + }, + "loc": { + "start": { + "line": 28, + "column": 20, + "program": "for_of.ets" + }, + "end": { + "line": 28, + "column": 28, + "program": "for_of.ets" + } + } + }, "loc": { "start": { "line": 28, @@ -990,7 +1022,7 @@ }, "end": { "line": 28, - "column": 24, + "column": 28, "program": "for_of.ets" } } @@ -1133,7 +1165,7 @@ { "type": "ReturnStatement", "argument": { - "type": "CharLiteral", + "type": "StringLiteral", "value": "*", "loc": { "start": { @@ -1143,7 +1175,7 @@ }, "end": { "line": 32, - "column": 14, + "column": 13, "program": "for_of.ets" } } @@ -1156,7 +1188,7 @@ }, "end": { "line": 32, - "column": 15, + "column": 14, "program": "for_of.ets" } } @@ -1165,7 +1197,7 @@ "loc": { "start": { "line": 28, - "column": 25, + "column": 27, "program": "for_of.ets" }, "end": { diff --git a/ets2panda/test/parser/ets/for_of.ets b/ets2panda/test/parser/ets/for_of.ets index 66d3ee60eb..ddbb5b4e82 100644 --- a/ets2panda/test/parser/ets/for_of.ets +++ b/ets2panda/test/parser/ets/for_of.ets @@ -25,9 +25,9 @@ function main(): void { } } -function forins(): char { +function forins(): string { for (let i of "abcdef") { return i; } - return c'*'; + return '*'; } diff --git a/ets2panda/test/runtime/ets/ForOfBoxing.ets b/ets2panda/test/runtime/ets/ForOfBoxing.ets index 4a7d4d02cd..45c0e3a150 100644 --- a/ets2panda/test/runtime/ets/ForOfBoxing.ets +++ b/ets2panda/test/runtime/ets/ForOfBoxing.ets @@ -97,7 +97,7 @@ function check6() { function check7() { let str = ""; let a7 : string = "ffff" - for (let idx7 : char of a7) { + for (let idx7 : string of a7) { let b7 = idx7 str += b7; } diff --git a/ets2panda/test/runtime/ets/ForOfUnion.ets b/ets2panda/test/runtime/ets/ForOfUnion.ets index 3e6929ee0e..08f2c4958d 100644 --- a/ets2panda/test/runtime/ets/ForOfUnion.ets +++ b/ets2panda/test/runtime/ets/ForOfUnion.ets @@ -16,8 +16,8 @@ function check1() { let a8 : string|Int[] = "abc" let str = ""; - for (let character : Char|Int of a8) { - if (character instanceof Char) { + for (let character : string|Int of a8) { + if (character instanceof string) { str += character; } } diff --git a/ets2panda/test/runtime/ets/forOfString.ets b/ets2panda/test/runtime/ets/forOfString.ets new file mode 100644 index 0000000000..98c4437010 --- /dev/null +++ b/ets2panda/test/runtime/ets/forOfString.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 main() { + let str = '\ud801\udc28\ud801\udc28'; + let expected = '𐐨'; + + // for-of string type should call string's iterator in std library + for(const s of str) { + arktest.assertTrue(s instanceof string); + arktest.assertEQ(s, expected); + } +} \ No newline at end of file -- Gitee From fff37e55d4d11e6c757df03705f32f90bbc6254f Mon Sep 17 00:00:00 2001 From: fcc Date: Thu, 12 Jun 2025 10:59:10 +0800 Subject: [PATCH 071/145] fix union type index access Avoid compiler crash when index access for union type. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICEKQA Signed-off-by: fcc --- ets2panda/checker/ets/typeCheckingHelpers.cpp | 3 +- .../ast/compiler/ets/union_field_access.ets | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/union_field_access.ets diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 2848d1fa2b..0b4190cf63 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -660,7 +660,8 @@ Type *ETSChecker::GuaranteedTypeForUnionFieldAccess(ir::MemberExpression *member { const auto &types = etsUnionType->ConstituentTypes(); ArenaVector apparentTypes {ProgramAllocator()->Adapter()}; - const auto &propertyName = memberExpression->Property()->AsIdentifier()->Name(); + const auto *prop = memberExpression->Property(); + const auto &propertyName = prop->IsIdentifier() ? prop->AsIdentifier()->Name() : prop->AsStringLiteral()->Str(); for (auto *type : types) { auto searchFlags = PropertySearchFlags::SEARCH_FIELD | PropertySearchFlags::SEARCH_METHOD | PropertySearchFlags::SEARCH_IN_BASE; diff --git a/ets2panda/test/ast/compiler/ets/union_field_access.ets b/ets2panda/test/ast/compiler/ets/union_field_access.ets new file mode 100644 index 0000000000..33cb90075f --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_field_access.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. + */ + +type U = TypeA | TypeB; + +interface TypeA { + kind: 'A'; + a: number; +} +interface TypeB { + kind: 'B'; + b: string; +} + +function IfWithString(val: U) { + return /* @@ label */val['kind'] === 'B' +} + +/* @@@ label Error TypeError: Indexed access is not supported for such expression type. */ -- Gitee From 93db21277bc2a300278acc55bcae54c2c40cbb0a Mon Sep 17 00:00:00 2001 From: fcc Date: Mon, 23 Jun 2025 10:49:26 +0800 Subject: [PATCH 072/145] remove local class feature Local class has been removed from spec. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGF3Z Signed-off-by: fcc --- ets2panda/BUILD.gn | 1 - ets2panda/CMakeLists.txt | 1 - ets2panda/REVIEWERS | 1 - .../lowering/ets/localClassLowering.h | 52 -- ets2panda/compiler/lowering/phase.cpp | 3 - ets2panda/parser/ETSparserStatements.cpp | 15 +- ets2panda/parser/statementParser.cpp | 2 +- .../test/ast/parser/ets/InvalidClasses.ets | 1 + .../ast/parser/ets/InvalidStatements1.ets | 3 +- .../ast/parser/ets/class_variable_empty.ets | 7 +- ...-class-member-access-modifier-private1.ets | 5 +- ...-class-member-access-modifier-private2.ets | 6 +- ...lass-member-access-modifier-protected1.ets | 6 +- ...lass-member-access-modifier-protected2.ets | 7 +- ...l-class-member-access-modifier-public1.ets | 5 +- ...l-class-member-access-modifier-public2.ets | 7 +- .../parser/ets/local_class_already_class.ets | 4 +- .../ets/local_class_already_interface.ets | 3 +- .../ets/local_class_already_variable.ets | 3 +- .../ets/local_class_in_classfunction.ets | 20 +- .../ets/local_interface_already_class.ets | 3 +- .../test/parser/ets/local-class-expected.txt | 481 ------------- ets2panda/test/parser/ets/local-class.ets | 20 - .../ets/localClassIsPermitted-expected.txt | 672 ------------------ .../test/parser/ets/localClassIsPermitted.ets | 22 - .../test/runtime/ets/InterfaceInBlock.ets | 31 - .../ets/lambdaWithLocalClassAccess.ets | 26 - .../test/runtime/ets/lambda_with_default.ets | 25 - .../ets/local-class-capture-boxing.ets | 218 ------ .../ets/local-class-capture-not-boxing.ets | 151 ---- .../ets/local-class-capture-parameter.ets | 39 - .../ets/local-class-in-local-class.ets | 54 -- .../runtime/ets/local-class-mixed-capture.ets | 46 -- .../local-class-modify-captured-parameter.ets | 41 -- .../ets/local-class-standard-example1.ets | 49 -- .../ets/local-class-standard-example2.ets | 82 --- .../ets/local_class_in_classfunction.ets | 64 -- .../runtime/ets/local_class_in_function.ets | 60 -- .../ets/statement_after_local_class.ets | 29 - ets2panda/util/diagnostic/syntax.yaml | 4 +- 40 files changed, 57 insertions(+), 2212 deletions(-) delete mode 100644 ets2panda/compiler/lowering/ets/localClassLowering.h delete mode 100644 ets2panda/test/parser/ets/local-class-expected.txt delete mode 100644 ets2panda/test/parser/ets/local-class.ets delete mode 100644 ets2panda/test/parser/ets/localClassIsPermitted-expected.txt delete mode 100644 ets2panda/test/parser/ets/localClassIsPermitted.ets delete mode 100644 ets2panda/test/runtime/ets/InterfaceInBlock.ets delete mode 100644 ets2panda/test/runtime/ets/lambdaWithLocalClassAccess.ets delete mode 100644 ets2panda/test/runtime/ets/lambda_with_default.ets delete mode 100644 ets2panda/test/runtime/ets/local-class-capture-boxing.ets delete mode 100644 ets2panda/test/runtime/ets/local-class-capture-not-boxing.ets delete mode 100644 ets2panda/test/runtime/ets/local-class-capture-parameter.ets delete mode 100644 ets2panda/test/runtime/ets/local-class-in-local-class.ets delete mode 100644 ets2panda/test/runtime/ets/local-class-mixed-capture.ets delete mode 100644 ets2panda/test/runtime/ets/local-class-modify-captured-parameter.ets delete mode 100644 ets2panda/test/runtime/ets/local-class-standard-example1.ets delete mode 100644 ets2panda/test/runtime/ets/local-class-standard-example2.ets delete mode 100644 ets2panda/test/runtime/ets/local_class_in_classfunction.ets delete mode 100644 ets2panda/test/runtime/ets/local_class_in_function.ets delete mode 100644 ets2panda/test/runtime/ets/statement_after_local_class.ets diff --git a/ets2panda/BUILD.gn b/ets2panda/BUILD.gn index dec0dc9a48..0466b97afd 100644 --- a/ets2panda/BUILD.gn +++ b/ets2panda/BUILD.gn @@ -228,7 +228,6 @@ libes2panda_sources = [ "compiler/lowering/ets/interfacePropertyDeclarations.cpp", "compiler/lowering/ets/lateInitialization.cpp", "compiler/lowering/ets/lambdaLowering.cpp", - "compiler/lowering/ets/localClassLowering.cpp", "compiler/lowering/ets/objectIndexAccess.cpp", "compiler/lowering/ets/objectIterator.cpp", "compiler/lowering/ets/objectLiteralLowering.cpp", diff --git a/ets2panda/CMakeLists.txt b/ets2panda/CMakeLists.txt index 10cf792e94..6ba1f67993 100644 --- a/ets2panda/CMakeLists.txt +++ b/ets2panda/CMakeLists.txt @@ -292,7 +292,6 @@ set(ES2PANDA_LIB_SRC 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 compiler/lowering/ets/objectIterator.cpp compiler/lowering/ets/insertOptionalParametersAnnotation.cpp diff --git a/ets2panda/REVIEWERS b/ets2panda/REVIEWERS index 8d77d32339..2a076034cb 100644 --- a/ets2panda/REVIEWERS +++ b/ets2panda/REVIEWERS @@ -68,7 +68,6 @@ /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 diff --git a/ets2panda/compiler/lowering/ets/localClassLowering.h b/ets2panda/compiler/lowering/ets/localClassLowering.h deleted file mode 100644 index 08ee325919..0000000000 --- a/ets2panda/compiler/lowering/ets/localClassLowering.h +++ /dev/null @@ -1,52 +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. - */ - -#ifndef ES2PANDA_COMPILER_LOWERING_LOCAL_CLASS_LOWERING_H -#define ES2PANDA_COMPILER_LOWERING_LOCAL_CLASS_LOWERING_H - -#include "compiler/lowering/phase.h" - -namespace ark::es2panda::compiler { - -class LocalClassConstructionPhase : public PhaseForBodies { -public: - std::string_view Name() const override; - bool PerformForModule(public_lib::Context *ctx, parser::Program *program) override; - -protected: - void CreateClassPropertiesForCapturedVariables(public_lib::Context *ctx, ir::ClassDefinition *classDef, - ArenaSet const &capturedVars, - ArenaMap &variableMap, - ArenaMap &propertyMap); - - void ModifyConstructorParameters(public_lib::Context *ctx, ir::ClassDefinition *classDef, - ArenaSet const &capturedVars, - ArenaMap &variableMap, - ArenaMap ¶meterMap); - - void RemapReferencesFromCapturedVariablesToClassProperties( - ir::ClassDefinition *classDef, ArenaMap &variableMap); - - void HandleLocalClass(public_lib::Context *ctx, - ArenaUnorderedMap> &capturedVarsMap, - ir::ClassDefinition *classDef); - - ir::ETSParameterExpression *CreateParam(public_lib::Context *ctx, varbinder::FunctionParamScope *scope, - util::StringView name, checker::Type *type); -}; - -} // namespace ark::es2panda::compiler - -#endif diff --git a/ets2panda/compiler/lowering/phase.cpp b/ets2panda/compiler/lowering/phase.cpp index 6cd559f27d..7a223877b4 100644 --- a/ets2panda/compiler/lowering/phase.cpp +++ b/ets2panda/compiler/lowering/phase.cpp @@ -42,7 +42,6 @@ #include "compiler/lowering/ets/interfaceObjectLiteralLowering.h" #include "compiler/lowering/ets/interfacePropertyDeclarations.h" #include "compiler/lowering/ets/lambdaLowering.h" -#include "compiler/lowering/ets/localClassLowering.h" #include "compiler/lowering/ets/objectIndexAccess.h" #include "compiler/lowering/ets/objectIterator.h" #include "compiler/lowering/ets/objectLiteralLowering.h" @@ -109,7 +108,6 @@ static DefaultParametersLowering g_defaultParametersLowering; static DefaultParametersInConstructorLowering g_defaultParametersInConstructorLowering; static OptionalArgumentsLowering g_optionalArgumentsLowering; static TopLevelStatements g_topLevelStatements; -static LocalClassConstructionPhase g_localClassLowering; static StringComparisonLowering g_stringComparisonLowering; static StringConstantsLowering g_stringConstantsLowering; static PartialExportClassGen g_partialExportClassGen; @@ -187,7 +185,6 @@ std::vector GetETSPhaseList() &g_lambdaConversionPhase, &g_unionLowering, &g_expandBracketsPhase, - &g_localClassLowering, &g_partialExportClassGen, &g_interfaceObjectLiteralLowering, // this lowering should be put after all classs generated. &g_objectLiteralLowering, diff --git a/ets2panda/parser/ETSparserStatements.cpp b/ets2panda/parser/ETSparserStatements.cpp index 3a3bcf9294..d65ff8c423 100644 --- a/ets2panda/parser/ETSparserStatements.cpp +++ b/ets2panda/parser/ETSparserStatements.cpp @@ -350,9 +350,13 @@ ir::Statement *ETSParser::ParseClassStatement([[maybe_unused]] StatementParsingF ir::ClassDefinitionModifiers modifiers, ir::ModifierFlags modFlags) { modFlags |= ParseClassModifiers(); - return ParseClassDeclaration(modifiers | ir::ClassDefinitionModifiers::ID_REQUIRED | - ir::ClassDefinitionModifiers::CLASS_DECL | ir::ClassDefinitionModifiers::LOCAL, - modFlags); + const auto &rangeClass = Lexer()->GetToken().Loc(); + LogError(diagnostic::ILLEGAL_START_STRUCT_CLASS, {"CLASS"}, rangeClass.start); + // Try to parse class and drop the result. + ParseClassDeclaration(modifiers | ir::ClassDefinitionModifiers::ID_REQUIRED | + ir::ClassDefinitionModifiers::CLASS_DECL | ir::ClassDefinitionModifiers::LOCAL, + modFlags); + return AllocBrokenStatement(rangeClass); } // NOLINTNEXTLINE(google-default-arguments) @@ -360,10 +364,11 @@ ir::Statement *ETSParser::ParseStructStatement([[maybe_unused]] StatementParsing ir::ClassDefinitionModifiers modifiers, ir::ModifierFlags modFlags) { const auto &rangeStruct = Lexer()->GetToken().Loc(); - LogError(diagnostic::ILLEGAL_START_STRUCT, {}, rangeStruct.start); + LogError(diagnostic::ILLEGAL_START_STRUCT_CLASS, {"STRUCT"}, rangeStruct.start); + // Try to parse struct and drop the result. ParseClassDeclaration(modifiers | ir::ClassDefinitionModifiers::ID_REQUIRED | ir::ClassDefinitionModifiers::CLASS_DECL | ir::ClassDefinitionModifiers::LOCAL, - modFlags); // Try to parse struct and drop the result. + modFlags); return AllocBrokenStatement(rangeStruct); } diff --git a/ets2panda/parser/statementParser.cpp b/ets2panda/parser/statementParser.cpp index 9039a1b441..5a67627f71 100644 --- a/ets2panda/parser/statementParser.cpp +++ b/ets2panda/parser/statementParser.cpp @@ -297,7 +297,7 @@ ir::Statement *ParserImpl::ParsePotentialExpressionStatement(StatementParsingFla ir::Statement *ParserImpl::ParseStructStatement([[maybe_unused]] StatementParsingFlags flags, ir::ClassDefinitionModifiers modifiers, ir::ModifierFlags modFlags) { - LogError(diagnostic::ILLEGAL_START_EXPRESSION); + LogError(diagnostic::ILLEGAL_START_STRUCT_CLASS, {"STRUCT"}); return ParseStructDeclaration(modifiers, modFlags); } diff --git a/ets2panda/test/ast/parser/ets/InvalidClasses.ets b/ets2panda/test/ast/parser/ets/InvalidClasses.ets index 85d1c1fbf9..b73dc9af4c 100644 --- a/ets2panda/test/ast/parser/ets/InvalidClasses.ets +++ b/ets2panda/test/ast/parser/ets/InvalidClasses.ets @@ -112,6 +112,7 @@ interface I1 { /* @@? 58:25 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ /* @@? 58:25 Error SyntaxError: Unexpected token, expected ',' or ')'. */ /* @@? 58:25 Error SyntaxError: Unexpected token '}'. */ +/* @@? 61:5 Error SyntaxError: Illegal start of CLASS expression. */ /* @@? 62:9 Error SyntaxError: Local class or interface declaration members can not have access modifies. */ /* @@? 66:9 Error SyntaxError: Local class or interface declaration members can not have access modifies. */ /* @@? 66:18 Error SyntaxError: Private interface methods must have body. */ diff --git a/ets2panda/test/ast/parser/ets/InvalidStatements1.ets b/ets2panda/test/ast/parser/ets/InvalidStatements1.ets index 0e78be95d1..a0a247f919 100644 --- a/ets2panda/test/ast/parser/ets/InvalidStatements1.ets +++ b/ets2panda/test/ast/parser/ets/InvalidStatements1.ets @@ -65,6 +65,7 @@ throw /* @@? 42:1 Error SyntaxError: A try statement should contain either finally clause or at least one catch clause. */ /* @@? 43:5 Error SyntaxError: Expected '{', got 'let'. */ /* @@? 45:9 Error SyntaxError: Unexpected token '{'. */ +/* @@? 47:1 Error SyntaxError: Illegal start of CLASS expression. */ /* @@? 48:5 Error SyntaxError: Unexpected token 'let'. */ /* @@? 52:1 Error SyntaxError: Illegal newline after throw. */ -/* @@? 71:1 Error SyntaxError: Expected '}', got 'end of stream'. */ +/* @@? 72:1 Error SyntaxError: Expected '}', got 'end of stream'. */ diff --git a/ets2panda/test/ast/parser/ets/class_variable_empty.ets b/ets2panda/test/ast/parser/ets/class_variable_empty.ets index aa702d4d0e..3ad4914548 100644 --- a/ets2panda/test/ast/parser/ets/class_variable_empty.ets +++ b/ets2panda/test/ast/parser/ets/class_variable_empty.ets @@ -19,6 +19,9 @@ function main(): void { let a: A = new A; assertTrue(a != null) } - assertTrue(/* @@ label */a != null) + assertTrue(a != null) } -/* @@@ label Error TypeError: Unresolved reference a */ \ No newline at end of file +/* @@? 18:5 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 19:12 Error TypeError: Cannot find type 'A'. */ +/* @@? 19:20 Error TypeError: Cannot find type 'A'. */ +/* @@? 22:14 Error TypeError: Unresolved reference a */ diff --git a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-private1.ets b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-private1.ets index 43fd173a70..2e523713b2 100644 --- a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-private1.ets +++ b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-private1.ets @@ -17,7 +17,8 @@ function foo() { class LocalClass { - /* @@ label */private property : int; + private property : int; } } -/* @@@ label Error SyntaxError: Local class or interface declaration members can not have access modifies. */ +/* @@? 18:5 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 20:9 Error SyntaxError: Local class or interface declaration members can not have access modifies. */ diff --git a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-private2.ets b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-private2.ets index 00c1422a83..85dd9b2df4 100644 --- a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-private2.ets +++ b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-private2.ets @@ -17,8 +17,8 @@ function foo() { class LocalClass { - /* @@ label */private method() : void; + private method() : void; } } -/* @@@ label Error SyntaxError: Local class or interface declaration members can not have access modifies. */ -/* @@? 20:37 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 18:5 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 20:9 Error SyntaxError: Local class or interface declaration members can not have access modifies. */ diff --git a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-protected1.ets b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-protected1.ets index 4091ddc869..2e7a15b760 100644 --- a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-protected1.ets +++ b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-protected1.ets @@ -17,7 +17,9 @@ function foo() { class LocalClass { - /* @@ label */protected property : int; + protected property : int; } } -/* @@@ label Error SyntaxError: Local class or interface declaration members can not have access modifies. */ + +/* @@? 18:5 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 20:9 Error SyntaxError: Local class or interface declaration members can not have access modifies. */ diff --git a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-protected2.ets b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-protected2.ets index 3d9cee80d4..a320b25eb8 100644 --- a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-protected2.ets +++ b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-protected2.ets @@ -17,8 +17,9 @@ function foo() { class LocalClass { - /* @@ label */protected method() : void; + protected method() : void; } } -/* @@@ label Error SyntaxError: Local class or interface declaration members can not have access modifies. */ -/* @@? 20:39 Error TypeError: Only abstract or native methods can't have body. */ + +/* @@? 18:5 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 20:9 Error SyntaxError: Local class or interface declaration members can not have access modifies. */ diff --git a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-public1.ets b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-public1.ets index 815ca264d0..3b55135eb7 100644 --- a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-public1.ets +++ b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-public1.ets @@ -17,7 +17,8 @@ function foo() { class LocalClass { - /* @@ label */public property : int; + public property : int; } } -/* @@@ label Error SyntaxError: Local class or interface declaration members can not have access modifies. */ +/* @@? 18:5 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 20:9 Error SyntaxError: Local class or interface declaration members can not have access modifies. */ diff --git a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-public2.ets b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-public2.ets index d04ccf89ed..5bf531cf9f 100644 --- a/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-public2.ets +++ b/ets2panda/test/ast/parser/ets/local-class-member-access-modifier-public2.ets @@ -17,8 +17,9 @@ function foo() { class LocalClass { - /* @@ label */public method() : void; + public method() : void; } } -/* @@@ label Error SyntaxError: Local class or interface declaration members can not have access modifies. */ -/* @@? 20:36 Error TypeError: Only abstract or native methods can't have body. */ + +/* @@? 18:5 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 20:9 Error SyntaxError: Local class or interface declaration members can not have access modifies. */ diff --git a/ets2panda/test/ast/parser/ets/local_class_already_class.ets b/ets2panda/test/ast/parser/ets/local_class_already_class.ets index 966c2505b1..3bfff8e7d3 100644 --- a/ets2panda/test/ast/parser/ets/local_class_already_class.ets +++ b/ets2panda/test/ast/parser/ets/local_class_already_class.ets @@ -22,5 +22,5 @@ function bar(): void { } } -/* @@? 20:9 Error TypeError: Variable 'BC' has already been declared. */ -/* @@? 20:9 Error TypeError: Merging declarations is not supported, please keep all definitions of classes, interfaces and enums compact in the codebase! */ +/* @@? 17:3 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 20:3 Error SyntaxError: Illegal start of CLASS expression. */ diff --git a/ets2panda/test/ast/parser/ets/local_class_already_interface.ets b/ets2panda/test/ast/parser/ets/local_class_already_interface.ets index 9b4408d291..e9fea16e52 100644 --- a/ets2panda/test/ast/parser/ets/local_class_already_interface.ets +++ b/ets2panda/test/ast/parser/ets/local_class_already_interface.ets @@ -22,5 +22,4 @@ function bar(): void { } } -/* @@? 20:9 Error TypeError: Variable 'BC' has already been declared. */ -/* @@? 20:9 Error TypeError: Merging declarations is not supported, please keep all definitions of classes, interfaces and enums compact in the codebase! */ +/* @@? 20:3 Error SyntaxError: Illegal start of CLASS expression. */ diff --git a/ets2panda/test/ast/parser/ets/local_class_already_variable.ets b/ets2panda/test/ast/parser/ets/local_class_already_variable.ets index b9523088d0..c784418b2c 100644 --- a/ets2panda/test/ast/parser/ets/local_class_already_variable.ets +++ b/ets2panda/test/ast/parser/ets/local_class_already_variable.ets @@ -20,5 +20,4 @@ function bar(): void { } } -/* @@? 18:9 Error TypeError: Variable 'BC' has already been declared. */ -/* @@? 18:9 Error TypeError: Merging declarations is not supported, please keep all definitions of classes, interfaces and enums compact in the codebase! */ +/* @@? 18:3 Error SyntaxError: Illegal start of CLASS expression. */ diff --git a/ets2panda/test/ast/parser/ets/local_class_in_classfunction.ets b/ets2panda/test/ast/parser/ets/local_class_in_classfunction.ets index c81cd8a8b2..7ae5c158df 100644 --- a/ets2panda/test/ast/parser/ets/local_class_in_classfunction.ets +++ b/ets2panda/test/ast/parser/ets/local_class_in_classfunction.ets @@ -49,13 +49,13 @@ class A_class{ } } -/* @@? 21:24 Error TypeError: Property 'localfield' of enclosing class 'A_class' is not allowed to be captured from the local class 'LocalClass' */ -/* @@? 21:24 Error TypeError: Property 'localfield' must be accessed through 'this' */ -/* @@? 26:29 Error TypeError: Property 'localfield' does not exist on type 'FinalLocalClass' */ -/* @@? 30:41 Error TypeError: Cannot inherit with 'final' modifier. */ -/* @@? 31:53 Error TypeError: Cannot use both 'final' and 'abstract' modifiers. */ -/* @@? 36:37 Error TypeError: AbstractLocalClass2 is abstract therefore cannot be instantiated. */ -/* @@? 39:13 Error TypeError: Invalid method modifier(s): an abstract method can't have private, override, static, final or native modifier. */ -/* @@? 40:31 Error TypeError: Native, Abstract and Declare methods cannot have body. */ -/* @@? 43:65 Error TypeError: FinalLocalClass2 is not abstract and does not override abstract method method3(): void in FinalLocalClass2 */ -/* @@? 45:13 Error TypeError: Non abstract class has abstract method. */ \ No newline at end of file +/* @@? 18:18 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 19:9 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 24:15 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 30:9 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 31:24 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 33:18 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 36:15 Error TypeError: Cannot find type 'AbstractLocalClass2'. */ +/* @@? 36:41 Error TypeError: Cannot find type 'AbstractLocalClass2'. */ +/* @@? 38:18 Error SyntaxError: Illegal start of CLASS expression. */ +/* @@? 43:15 Error SyntaxError: Illegal start of CLASS expression. */ diff --git a/ets2panda/test/ast/parser/ets/local_interface_already_class.ets b/ets2panda/test/ast/parser/ets/local_interface_already_class.ets index 92b9a2983a..a1458dd771 100644 --- a/ets2panda/test/ast/parser/ets/local_interface_already_class.ets +++ b/ets2panda/test/ast/parser/ets/local_interface_already_class.ets @@ -22,5 +22,4 @@ function bar(): void { } } -/* @@? 20:3 Error TypeError: Variable 'BC' has already been declared. */ -/* @@? 20:3 Error TypeError: Merging declarations is not supported, please keep all definitions of classes, interfaces and enums compact in the codebase! */ +/* @@? 17:3 Error SyntaxError: Illegal start of CLASS expression. */ diff --git a/ets2panda/test/parser/ets/local-class-expected.txt b/ets2panda/test/parser/ets/local-class-expected.txt deleted file mode 100644 index 8b51c20764..0000000000 --- a/ets2panda/test/parser/ets/local-class-expected.txt +++ /dev/null @@ -1,481 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "local-class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "local-class.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": "local-class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "local-class.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "main", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "local-class.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "local-class.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": "local-class.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "local-class.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "returnType": { - "type": "ETSPrimitiveType", - "loc": { - "start": { - "line": 16, - "column": 19, - "program": "local-class.ets" - }, - "end": { - "line": 16, - "column": 22, - "program": "local-class.ets" - } - } - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "LocalClass", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 11, - "program": "local-class.ets" - }, - "end": { - "line": 18, - "column": 21, - "program": "local-class.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "local-class.ets" - }, - "end": { - "line": 18, - "column": 23, - "program": "local-class.ets" - } - } - }, - "kind": "constructor", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "local-class.ets" - }, - "end": { - "line": 18, - "column": 23, - "program": "local-class.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "local-class.ets" - }, - "end": { - "line": 18, - "column": 23, - "program": "local-class.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "local-class.ets" - }, - "end": { - "line": 18, - "column": 23, - "program": "local-class.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 23, - "program": "local-class.ets" - }, - "end": { - "line": 18, - "column": 23, - "program": "local-class.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 18, - "column": 22, - "program": "local-class.ets" - }, - "end": { - "line": 19, - "column": 11, - "program": "local-class.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 5, - "program": "local-class.ets" - }, - "end": { - "line": 19, - "column": 11, - "program": "local-class.ets" - } - } - }, - { - "type": "ReturnStatement", - "argument": { - "type": "NumberLiteral", - "value": 0, - "loc": { - "start": { - "line": 19, - "column": 12, - "program": "local-class.ets" - }, - "end": { - "line": 19, - "column": 13, - "program": "local-class.ets" - } - } - }, - "loc": { - "start": { - "line": 19, - "column": 5, - "program": "local-class.ets" - }, - "end": { - "line": 19, - "column": 14, - "program": "local-class.ets" - } - } - } - ], - "loc": { - "start": { - "line": 17, - "column": 1, - "program": "local-class.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "local-class.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "local-class.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "local-class.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 10, - "program": "local-class.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "local-class.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "local-class.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "local-class.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "local-class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "local-class.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "local-class.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "local-class.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "local-class.ets" - }, - "end": { - "line": 20, - "column": 2, - "program": "local-class.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/local-class.ets b/ets2panda/test/parser/ets/local-class.ets deleted file mode 100644 index 94e03361a4..0000000000 --- a/ets2panda/test/parser/ets/local-class.ets +++ /dev/null @@ -1,20 +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() : int -{ - class LocalClass { } - return 0; -} \ No newline at end of file diff --git a/ets2panda/test/parser/ets/localClassIsPermitted-expected.txt b/ets2panda/test/parser/ets/localClassIsPermitted-expected.txt deleted file mode 100644 index 0995504c47..0000000000 --- a/ets2panda/test/parser/ets/localClassIsPermitted-expected.txt +++ /dev/null @@ -1,672 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "Klass", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 7, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 16, - "column": 12, - "program": "localClassIsPermitted.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "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": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "Local", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 15, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 18, - "column": 20, - "program": "localClassIsPermitted.ets" - } - } - }, - "superClass": null, - "implements": [], - "body": [ - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - } - } - }, - "kind": "constructor", - "static": false, - "optional": false, - "computed": false, - "value": { - "type": "FunctionExpression", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 18, - "column": 22, - "program": "localClassIsPermitted.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 18, - "column": 21, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 21, - "column": 6, - "program": "localClassIsPermitted.ets" - } - } - }, - "loc": { - "start": { - "line": 18, - "column": 9, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 21, - "column": 6, - "program": "localClassIsPermitted.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 - } - } - }, - "loc": { - "start": { - "line": 21, - "column": 5, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 21, - "column": 6, - "program": "localClassIsPermitted.ets" - } - } - }, - { - "type": "MethodDefinition", - "key": { - "type": "Identifier", - "name": "constructor", - "decorators": [], - "loc": { - "start": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.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": 14, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.ets" - } - } - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [], - "loc": { - "start": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 16, - "column": 14, - "program": "localClassIsPermitted.ets" - } - } - }, - "overloads": [], - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": null - }, - "end": { - "line": 1, - "column": 1, - "program": null - } - } - } - ], - "loc": { - "start": { - "line": 16, - "column": 13, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 23, - "column": 1, - "program": "localClassIsPermitted.ets" - } - } - }, - "loc": { - "start": { - "line": 16, - "column": 1, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 23, - "column": 1, - "program": "localClassIsPermitted.ets" - } - } - }, - { - "type": "ClassDeclaration", - "definition": { - "id": { - "type": "Identifier", - "name": "ETSGLOBAL", - "decorators": [], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.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": "localClassIsPermitted.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.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": "localClassIsPermitted.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - } - } - }, - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - } - } - } - ], - "loc": { - "start": { - "line": 1, - "column": 1, - "program": "localClassIsPermitted.ets" - }, - "end": { - "line": 23, - "column": 1, - "program": "localClassIsPermitted.ets" - } - } -} diff --git a/ets2panda/test/parser/ets/localClassIsPermitted.ets b/ets2panda/test/parser/ets/localClassIsPermitted.ets deleted file mode 100644 index 85aa2cd787..0000000000 --- a/ets2panda/test/parser/ets/localClassIsPermitted.ets +++ /dev/null @@ -1,22 +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. - */ - -class Klass { - static { - class Local { - - } - } -} diff --git a/ets2panda/test/runtime/ets/InterfaceInBlock.ets b/ets2panda/test/runtime/ets/InterfaceInBlock.ets deleted file mode 100644 index 0674863ac1..0000000000 --- a/ets2panda/test/runtime/ets/InterfaceInBlock.ets +++ /dev/null @@ -1,31 +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 I - { - foo(): int; - } - - class C implements I - { - foo(): int - { - return 1; - } - } - - assertEQ(new C().foo(), 1); -} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/lambdaWithLocalClassAccess.ets b/ets2panda/test/runtime/ets/lambdaWithLocalClassAccess.ets deleted file mode 100644 index 6f004b0948..0000000000 --- a/ets2panda/test/runtime/ets/lambdaWithLocalClassAccess.ets +++ /dev/null @@ -1,26 +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 f() { - class C { - x: boolean = true - } - let lam = (c: C): boolean => { return c.x } - assertTrue(lam(new C())) -} - -function main() { - f() -} diff --git a/ets2panda/test/runtime/ets/lambda_with_default.ets b/ets2panda/test/runtime/ets/lambda_with_default.ets deleted file mode 100644 index 85e5cf14dd..0000000000 --- a/ets2panda/test/runtime/ets/lambda_with_default.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() { - ()=> { - class A { - foo(x :String ="aa"){ - return x; - } - } - } - assertTrue(true) -} diff --git a/ets2panda/test/runtime/ets/local-class-capture-boxing.ets b/ets2panda/test/runtime/ets/local-class-capture-boxing.ets deleted file mode 100644 index a3ebeedea6..0000000000 --- a/ets2panda/test/runtime/ets/local-class-capture-boxing.ets +++ /dev/null @@ -1,218 +0,0 @@ -/* - * 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. - */ - -class UserClassType -{ - v : int = 0; - constructor (p : int) - { - this.v = p; - } - - override toString() : string { - return Int.valueOf(this.v).toString(); - } -} - -enum UserEnumType -{ - Red, - Green, - Blue -}; - -let g_array : int [] = [1,2,3]; -let g_array2 : int [] = [11,12,13]; -let g_Array : Array = new Array(new Int(4), new Int(5), new Int(6)); -let g_Array2 : Array = new Array(new Int(14), new Int(15), new Int(16)); -let g_Object : Object = new Object(); -let g_Object2 : Object = new Object(); -let g_Class : UserClassType = new UserClassType(25); -let g_Class2 : UserClassType = new UserClassType(250); - - - -class GlobalClass -{ - static s_field : int = 13; - field : int = 14; - - static s_method_boxing_local_class() { - // predefined value types - let l_number : number = 1; - let l_byte : byte = 2; - let l_short : short = 3; - let l_int : int = 4; - let l_long : long = 5; - let l_float : float = 6.0f; - let l_double : double = 7.0; - let l_boolean : boolean = false; - let l_char : char = c'x'; - - // user defined value types - let l_enum : UserEnumType = UserEnumType.Red; - - // predefined reference types - let l_Number : Number = new Number(11); - let l_Byte : Byte = new Byte(12 as byte); - let l_Short : Short = new Short(13 as short); - let l_Int : Int = new Int(14 as int); - let l_Long : Long = new Long(15 as long); - let l_Float : Float = new Float(16.0); - let l_Double : Double = new Double(17.0); - let l_Boolean: Boolean = new Boolean(false); - let l_Char : Char = new Char(c'X'); - - let l_string : string = "something"; - let l_String : String = new String("Something"); - let l_array : int [] = g_array; - let l_Array : Array = g_Array; - //let l_bigint : bigint = 20n; - //let l_BigInt : BigInt = new BigInt(21n); - let l_Object : Object = g_Object; - - // user defined reference types - let l_Class : UserClassType = g_Class; - - class LocalClassBoxing - { - local_field : int = 1000; - static local_s_field : int = 2000; - - static local_s_method(lp : int) : void - { - assertEQ(lp, 300) - assertEQ(LocalClassBoxing.local_s_field, 2000) - - LocalClassBoxing.local_s_field = 5000; - assertEQ(LocalClassBoxing.local_s_field, 5000) - } - - local_method(lp : int) : void - { - // Parameter - assertEQ(lp, 400) - // Local class object field - assertEQ(this.local_field, 1000) - // Local class static field - assertEQ(LocalClassBoxing.local_s_field, 5000) - // Outer class static field - assertEQ(GlobalClass.s_field, 13) - // Predefined value types - assertEQ(l_number, 1) - assertEQ(l_byte, 2) - assertEQ(l_short, 3) - assertEQ(l_int, 4) - assertEQ(l_long, 5) - assertEQ(l_float, 6) - assertEQ(l_double, 7) - assertEQ(l_boolean, false) - assertEQ(l_char, c'x') - // User defined value type - assertEQ(l_enum, UserEnumType.Red) - // Predefined reference types - assertEQ(l_Number, Number.valueOf(11)) - assertEQ(l_Byte, Byte.valueOf(12 as byte)) - assertEQ(l_Short, Short.valueOf(13 as short)) - assertEQ(l_Int, Int.valueOf(14 as int)) - assertEQ(l_Long, Long.valueOf(15 as long)) - assertEQ(l_Float, Float.valueOf(16 as float)) - assertEQ(l_Double, Double.valueOf(17 as double)) - assertEQ(l_Boolean, Boolean.valueOf(false)) - assertEQ(l_Char, Char.valueOf(c'X')) - assertEQ(l_string, "something") - assertEQ(l_String, "Something") - // assertEQ(l_array, g_array) - // assertEQ(l_Array, g_Array) - assertEQ(l_Object, g_Object) - assertEQ(l_Class, g_Class) - - this.local_field = 1100; - LocalClassBoxing.local_s_field = 5100; - - l_number = 101; - l_byte = 102; - l_short = 103; - l_int = 104; - l_long = 105; - l_float = Double.toFloat(106.0); - l_double = 107.0; - l_boolean = true; - l_char = c'y'; - //l_enum = UserEnumType.Green; - - l_Number = new Number(111); - l_Byte = new Byte(112 as byte); - l_Short = new Short(113 as short); - l_Int = new Int(114 as int); - l_Long = new Long(115 as long); - l_Float = new Float(116.0); - l_Double = new Double(117.0); - l_Boolean = new Boolean(true); - l_Char = new Char(c'Y'); - - l_string = "something new"; - l_String = new String("Something new"); - l_array = g_array2; - l_Array = g_Array2; - l_Object = g_Object2; - l_Class = g_Class2; - } - }; - LocalClassBoxing.local_s_field = 2000; // due to the jit loop - LocalClassBoxing.local_s_method(300); - - let lcb = new LocalClassBoxing(); - lcb.local_method(400); - - assertEQ(lcb.local_field, 1100) - assertEQ(LocalClassBoxing.local_s_field, 5100) - assertEQ(l_number, 101) - assertEQ(l_byte, 102) - assertEQ(l_short, 103) - assertEQ(l_int, 104) - assertEQ(l_long, 105) - assertEQ(l_float, 106) - assertEQ(l_double, 107) - assertEQ(l_boolean, true) - assertEQ(l_char, c'y') - - //assertEQ(l_enum, UserEnumType.Green) - - // Predefined reference types - assertEQ(l_Number, Number.valueOf(111)) - assertEQ(l_Byte, Byte.valueOf(112 as byte)) - assertEQ(l_Short, Short.valueOf(113 as short)) - assertEQ(l_Int, Int.valueOf(114 as int)) - assertEQ(l_Long, Long.valueOf(115 as long)) - assertEQ(l_Float, Float.valueOf(116 as float)) - assertEQ(l_Double, Double.valueOf(117 as double)) - assertEQ(l_Boolean, Boolean.valueOf(true)) - assertEQ(l_Char, Char.valueOf(c'Y')) - assertEQ(l_string, "something new") - assertEQ(l_String, "Something new") - //assertEQ(l_array, g_array2) - //assertEQ(l_Array, g_Array2) - assertEQ(l_Object, g_Object2) - assertEQ(l_Class, g_Class2) - } -} - - -function main() : int -{ - GlobalClass.s_method_boxing_local_class(); - return 0; -} diff --git a/ets2panda/test/runtime/ets/local-class-capture-not-boxing.ets b/ets2panda/test/runtime/ets/local-class-capture-not-boxing.ets deleted file mode 100644 index d06cbc640e..0000000000 --- a/ets2panda/test/runtime/ets/local-class-capture-not-boxing.ets +++ /dev/null @@ -1,151 +0,0 @@ -/* - * 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. - */ - -class UserClassType -{ - v : int = 0; - constructor (p : int) - { - this.v = p; - } - - override toString() : string { - return Int.valueOf(this.v).toString(); - } -} - -enum UserEnumType -{ - Red, - Green, - Blue -}; - -let g_array : int [] = [1,2,3]; -let g_array2 : int [] = [11,12,13]; -let g_Array : Array = new Array(new Int(4), new Int(5), new Int(6)); -let g_Array2 : Array = new Array(new Int(14), new Int(15), new Int(16)); -let g_Object : Object = new Object(); -let g_Object2 : Object = new Object(); -let g_Class : UserClassType = new UserClassType(25); -let g_Class2 : UserClassType = new UserClassType(250); - - - -class GlobalClass -{ - static s_field : int = 13; - field : int = 14; - - static s_method_not_boxing_local_class() { - // predefined value types - let l_number : number = 1; - let l_byte : byte = 2; - let l_short : short = 3; - let l_int : int = 4; - let l_long : long = 5; - let l_float : float = 6.0f; - let l_double : double = 7.0; - let l_boolean : boolean = false; - let l_char : char = c'x'; - - // user defined value types - let l_enum : UserEnumType = UserEnumType.Red; - - // predefined reference types - let l_Number : Number = new Number(11); - let l_Byte : Byte = new Byte(12 as byte); - let l_Short : Short = new Short(13 as short); - let l_Int : Int = new Int(14 as int); - let l_Long : Long = new Long(15 as long); - let l_Float : Float = new Float(16.0); - let l_Double : Double = new Double(17.0); - let l_Boolean: Boolean = new Boolean(false); - let l_Char : Char = new Char(c'X'); - - let l_string : string = "something"; - let l_String : String = new String("Something"); - let l_array : int [] = g_array; - let l_Array : Array = g_Array; - //let l_bigint : bigint = 20n; - //let l_BigInt : BigInt = new BigInt(21n); - let l_Object : Object = g_Object; - - // user defined reference types - let l_Class : UserClassType = g_Class; - - class LocalClassNotBoxing - { - local_field : int = 100; - static local_s_field : int = 200; - - static local_s_method(lp : int) : void - { - assertEQ(lp, 30) - assertEQ(LocalClassNotBoxing.local_s_field, 200) - } - - local_method(lp : int) : void - { - // Parameter - assertEQ(lp, 40) - // Local class object field - assertEQ(this.local_field, 100) - // Local class static field - assertEQ(LocalClassNotBoxing.local_s_field, 200) - // Predefined value types - assertEQ(l_number, 1) - assertEQ(l_byte, 2) - assertEQ(l_short, 3) - assertEQ(l_int, 4) - assertEQ(l_long, 5) - assertEQ(l_float, 6) - assertEQ(l_double, 7) - assertEQ(l_boolean, false) - assertEQ(l_char, c'x') - // User defined value type - assertEQ(l_enum, UserEnumType.Red) - // Predefined reference types - assertEQ(l_Number, Number.valueOf(11)) - assertEQ(l_Byte, Byte.valueOf(12 as byte)) - assertEQ(l_Short, Short.valueOf(13 as short)) - assertEQ(l_Int, Int.valueOf(14 as int)) - assertEQ(l_Long, Long.valueOf(15 as long)) - assertEQ(l_Float, Float.valueOf(16 as float)) - assertEQ(l_Double, Double.valueOf(17 as double)) - assertEQ(l_Boolean, Boolean.valueOf(false)) - assertEQ(l_Char, Char.valueOf(c'X')) - assertEQ(l_string, "something") - assertEQ(l_String, "Something") - assertEQ(l_array, g_array) - assertEQ(l_Array, g_Array) - assertEQ(l_Object, g_Object) - assertEQ(l_Class, g_Class) - } - }; - - LocalClassNotBoxing.local_s_method(30); - - let lc = new LocalClassNotBoxing(); - lc.local_method(40); - } -} - - -function main() : int -{ - GlobalClass.s_method_not_boxing_local_class(); - return 0; -} diff --git a/ets2panda/test/runtime/ets/local-class-capture-parameter.ets b/ets2panda/test/runtime/ets/local-class-capture-parameter.ets deleted file mode 100644 index c931bf4fda..0000000000 --- a/ets2panda/test/runtime/ets/local-class-capture-parameter.ets +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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. - */ - - -class GlobalClass -{ - static capture_param_method(param : int) - { - class LocalClass - { - method() - { - assertEQ(param, 1) - } - } - - let lc = new LocalClass(); - lc.method() - } -} - -function main() : int -{ - GlobalClass.capture_param_method(1); - - return 0; -} diff --git a/ets2panda/test/runtime/ets/local-class-in-local-class.ets b/ets2panda/test/runtime/ets/local-class-in-local-class.ets deleted file mode 100644 index 680ea18e4b..0000000000 --- a/ets2panda/test/runtime/ets/local-class-in-local-class.ets +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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. - */ - - -function main() : int -{ - let l_int = 0; - - class LocalClassLevel1 - { - m_int1 = 11; - - method1() - { - let l_int2 = 12; - assertEQ(this.m_int1, 11) - assertEQ(l_int, 0) - l_int = 1; - - class LocalClassLevel2 - { - m_int2 : int = 22; - - method2() { - assertEQ(this.m_int2, 22) - assertEQ(l_int2, 12) - l_int2 = 13; - } - } - - let lcl2 = new LocalClassLevel2(); - lcl2.method2(); - assertEQ(l_int2, 13) - } - } - - let lcl1 = new LocalClassLevel1(); - lcl1.method1(); - assertEQ(l_int, 1) - - return 0; -} diff --git a/ets2panda/test/runtime/ets/local-class-mixed-capture.ets b/ets2panda/test/runtime/ets/local-class-mixed-capture.ets deleted file mode 100644 index 916b84c4d2..0000000000 --- a/ets2panda/test/runtime/ets/local-class-mixed-capture.ets +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - */ - -function main() : int -{ - // Since the BoxingLocalClass modifies the 'i' it has to be boxed and use it as a boxed - // variable in the NotBoxingLocalClass too - let i : int = 1; - - class NotBoxingLocalClass - { - local_method() - { - assertEQ(i, 1) - } - } - - class BoxingLocalClass - { - local_method() - { - assertEQ(i, 1) - i = 2; - } - } - - let nblc = new NotBoxingLocalClass(); - nblc.local_method(); - - let blc = new BoxingLocalClass(); - blc.local_method(); - assertEQ(i, 2) - return 0; -} diff --git a/ets2panda/test/runtime/ets/local-class-modify-captured-parameter.ets b/ets2panda/test/runtime/ets/local-class-modify-captured-parameter.ets deleted file mode 100644 index c217536ffd..0000000000 --- a/ets2panda/test/runtime/ets/local-class-modify-captured-parameter.ets +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - */ - - -class GlobalClass -{ - static capture_param_method(param : int) - { - class LocalClass - { - method() - { - assertEQ(param, 1) - param = 3; - } - } - - let lc = new LocalClass(); - lc.method() - assertEQ(param, 3) - } -} - -function main() : int -{ - GlobalClass.capture_param_method(1); - - return 0; -} diff --git a/ets2panda/test/runtime/ets/local-class-standard-example1.ets b/ets2panda/test/runtime/ets/local-class-standard-example1.ets deleted file mode 100644 index 99429c2fcc..0000000000 --- a/ets2panda/test/runtime/ets/local-class-standard-example1.ets +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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. - */ - -function foo (parameter: number) { - let local: string = "function local"; - interface LocalInterface { // Local interface in a top-level function - method (): void; // It has a method - field: string; // and a property - } - class LocalClass implements LocalInterface { // Class implements interface - // Local class in a top-level function - override method () { - console.log ("Instance field = " + this.field + " par = " + parameter + " loc = " + local ) - assertEQ(this.field, "`instance field value`") - assertEQ(parameter, 42) - assertEQ(local, "function local") - } - field: string = "`instance field value`" - static s_method () { - console.log ("Static field = " + LocalClass.s_field) - assertEQ(LocalClass.s_field, "`class/static field value`") - - } - static s_field: string = "`class/static field value`" - } - - let lc: LocalInterface = new LocalClass(); - // Both local types can be freely used in the top-level function scope - lc.method() - LocalClass.s_method() -} - -function main() : int -{ - foo(42); - return 0; -} diff --git a/ets2panda/test/runtime/ets/local-class-standard-example2.ets b/ets2panda/test/runtime/ets/local-class-standard-example2.ets deleted file mode 100644 index 313b2e96ed..0000000000 --- a/ets2panda/test/runtime/ets/local-class-standard-example2.ets +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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. - */ - -class A_class { - field: number = 1234 // Not visible for the local class - method (parameter: number) { - let local: string = "instance local" - - interface LocalInterface { - method (): void - field: string - } - - class LocalClass implements LocalInterface { - override method () { - console.log ("Instance field = " + this.field + " par = " + parameter + " loc = " + local ) - assertEQ(this.field, "`instance method instance field value`") - assertEQ(parameter, 42) - assertEQ(local, "instance local") - - } - field: string = "`instance method instance field value`" - static s_method () { - console.log ("Static field = " + LocalClass.s_field) - assertEQ(LocalClass.s_field, "`instance method class/static field value`") - } - static s_field: string = "`instance method class/static field value`" - } - - let lc: LocalInterface = new LocalClass - lc.method() - LocalClass.s_method() - } - - static s_method (parameter: number) { - let local: string = "class/static local" - interface LocalInterface { - method (): void - field: string - } - - class LocalClass implements LocalInterface { - override method () { - console.log ("Instance field = " + this.field + " par = " + parameter + " loc = " + local) - assertEQ(this.field, "`static method instance field value`") - assertEQ(parameter, 72) - assertEQ(local, "class/static local") - } - field: string = "`static method instance field value`" - static s_method () { - console.log ("Static field = " + LocalClass.s_field) - assertEQ(LocalClass.s_field, "`static method class/static field value`") - } - static s_field: string = "`static method class/static field value`" - } - let lc: LocalInterface = new LocalClass - lc.method() - LocalClass.s_method() - } -} - -function main() : int -{ - A_class.s_method(72); - - let a = new A_class(); - a.method(42) - - return 0; -} diff --git a/ets2panda/test/runtime/ets/local_class_in_classfunction.ets b/ets2panda/test/runtime/ets/local_class_in_classfunction.ets deleted file mode 100644 index 08bd662e7b..0000000000 --- a/ets2panda/test/runtime/ets/local_class_in_classfunction.ets +++ /dev/null @@ -1,64 +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. - */ -class A_class{ - foo(){ - let localfield:string = "localstring"; - abstract class AbstractLocalClass{ - field1:int = 100; - } - class LocalClass extends AbstractLocalClass{ - field2:int = 200; - static staticfield = 300; - method1(){ - assertEQ(this.field1, 100) - assertEQ(this.field2, 200) - assertEQ(localfield, "localstring") - } - static method2(){ - assertEQ(LocalClass.staticfield, 300) - } - } - final class FinalLocalClass{ - field1:int = 100; - static staticfield = 300; - method1(){ - assertEQ(this.field1, 100) - assertEQ(localfield, "localstring") - } - static method2(){ - assertEQ(LocalClass.staticfield, 300) - } - } - - let x:AbstractLocalClass = new LocalClass(); - assertEQ(x.field1, 100) - assertEQ(x.field2, 200) - assertEQ(LocalClass.staticfield, 300) - x.method1(); - LocalClass.method2(); - - let x2:FinalLocalClass = new FinalLocalClass(); - assertEQ(x2.field1, 100) - assertEQ(FinalLocalClass.staticfield, 300) - x2.method1() - FinalLocalClass.method2(); - } -} - -function main():void -{ - let x3:A_class = new A_class; - x3.foo(); -} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/local_class_in_function.ets b/ets2panda/test/runtime/ets/local_class_in_function.ets deleted file mode 100644 index 7457a257ef..0000000000 --- a/ets2panda/test/runtime/ets/local_class_in_function.ets +++ /dev/null @@ -1,60 +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():void -{ - let localint:int = 200; - - abstract class AbstractLocalClass{ - field1:int = 10; - } - - class LocalClass extends AbstractLocalClass{ - field2:int = 20; - static staticfield = 30; - method1(){ - assertEQ(this.field1, 10) - assertEQ(this.field2, 20) - assertEQ(localint, 200) - } - static method2(){ - assertEQ(LocalClass.staticfield, 30) - } - } - - final class FinalLocalClass{ - field1:int = 10; - static staticfield = 30; - method1(){ - assertEQ(this.field1, 10) - assertEQ(localint, 200) - } - static method2(){ - assertEQ(FinalLocalClass.staticfield, 30) - } - } - - let x:AbstractLocalClass = new LocalClass(); - assertEQ(x.field1, 10) - assertEQ(x.field2, 20) - assertEQ(LocalClass.staticfield, 30) - x.method1(); - LocalClass.method2(); - - let x2:FinalLocalClass = new FinalLocalClass(); - assertEQ(x2.field1, 10) - assertEQ(FinalLocalClass.staticfield, 30) - x2.method1() - FinalLocalClass.method2(); -} \ No newline at end of file diff --git a/ets2panda/test/runtime/ets/statement_after_local_class.ets b/ets2panda/test/runtime/ets/statement_after_local_class.ets deleted file mode 100644 index 6b000813b0..0000000000 --- a/ets2panda/test/runtime/ets/statement_after_local_class.ets +++ /dev/null @@ -1,29 +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(): void { - class MyClass { - constructor() { - } - - foo(): number { - return 1.0 - } - } - - let m = new MyClass() - - assertEQ(m.foo(), 1.0) -} diff --git a/ets2panda/util/diagnostic/syntax.yaml b/ets2panda/util/diagnostic/syntax.yaml index a412c35ab5..4fcca86710 100644 --- a/ets2panda/util/diagnostic/syntax.yaml +++ b/ets2panda/util/diagnostic/syntax.yaml @@ -168,9 +168,9 @@ syntax: id: 39 message: "A try statement should contain either finally clause or at least one catch clause." -- name: ILLEGAL_START_STRUCT +- name: ILLEGAL_START_STRUCT_CLASS id: 40 - message: "Illegal start of STRUCT expression." + message: "Illegal start of {} expression." - name: ONLY_EXPORT_CLASS_OR_INTERFACE id: 41 -- Gitee From f0cf58241d2e6854d6de4e178a1439986157ee50 Mon Sep 17 00:00:00 2001 From: fcc Date: Fri, 20 Jun 2025 17:20:44 +0800 Subject: [PATCH 073/145] fix instantiate void parameter type After instantiation, parameter type might be 'void'. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICGPYZ Signed-off-by: fcc --- ets2panda/checker/types/signature.cpp | 4 ++++ ets2panda/test/runtime/ets/voidTypeArg.ets | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/ets2panda/checker/types/signature.cpp b/ets2panda/checker/types/signature.cpp index 5ced79c411..4533d51d30 100644 --- a/ets2panda/checker/types/signature.cpp +++ b/ets2panda/checker/types/signature.cpp @@ -51,6 +51,10 @@ Signature *Signature::Substitute(TypeRelation *relation, const Substitution *sub if (newParamType != param->TsType()) { anyChange = true; newParam = param->Copy(allocator, param->Declaration()); + if (newParamType->IsETSVoidType()) { + // since `void` is not allowed to be used as param type + newParamType = checker->GlobalETSUndefinedType(); + } newParam->SetTsType(newParamType); } newSigInfo->params.push_back(newParam); diff --git a/ets2panda/test/runtime/ets/voidTypeArg.ets b/ets2panda/test/runtime/ets/voidTypeArg.ets index c9cc22d0b4..41f798e7db 100644 --- a/ets2panda/test/runtime/ets/voidTypeArg.ets +++ b/ets2panda/test/runtime/ets/voidTypeArg.ets @@ -17,9 +17,17 @@ function foo(a0: T): T { return a0; } +type Fn = (e: T) => void; + +function test(arg: Fn) {} + function main() : void { foo(undefined); let bfoo = foo(undefined); assertEQ(bfoo, undefined) + + test((e) => { + assertEQ(e, undefined) + }) } -- Gitee From 7b5baad5e0edc6a1f1c507c2343ac6ea96a40dcf Mon Sep 17 00:00:00 2001 From: tsatsulya Date: Mon, 30 Jun 2025 18:18:30 +0300 Subject: [PATCH 074/145] fix codecheck Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIYQX Signed-off-by: tsatsulya --- ets2panda/ast_verifier/ASTVerifier.h | 2 +- ets2panda/compiler/base/lreference.cpp | 5 ++++- ets2panda/compiler/core/CFG.cpp | 4 ++++ ets2panda/compiler/core/ETSCompiler.cpp | 7 ++++++- ets2panda/compiler/core/ETSemitter.cpp | 14 ++++++++++++++ ets2panda/compiler/core/JSCompiler.cpp | 2 ++ ets2panda/compiler/core/dynamicContext.cpp | 2 ++ ets2panda/compiler/core/emitter.cpp | 4 ++-- ets2panda/compiler/core/moduleContext.cpp | 2 +- ets2panda/compiler/core/pandagen.cpp | 1 + ets2panda/compiler/core/regAllocator.cpp | 2 ++ .../compiler/lowering/ets/ambientLowering.cpp | 1 + .../compiler/lowering/ets/arrayLiteralLowering.cpp | 2 ++ .../compiler/lowering/ets/asyncMethodLowering.cpp | 7 ++++++- .../compiler/lowering/ets/boxingForLocals.cpp | 2 ++ .../debugInfoDeserializer.cpp | 4 +++- .../debugInfoDeserialization/methodBuilder.cpp | 3 +++ ets2panda/evaluate/helpers.cpp | 2 +- ets2panda/evaluate/scopedDebugInfoPlugin.cpp | 2 ++ ets2panda/ir/base/catchClause.cpp | 11 +++++++++-- ets2panda/ir/base/decorator.cpp | 2 +- ets2panda/ir/base/metaProperty.cpp | 1 + ets2panda/ir/base/methodDefinition.cpp | 4 +++- ets2panda/ir/base/methodDefinition.h | 2 +- ets2panda/ir/base/property.cpp | 2 +- ets2panda/ir/base/scriptFunction.cpp | 2 ++ ets2panda/ir/base/spreadElement.cpp | 1 + ets2panda/ir/base/templateElement.cpp | 1 + ets2panda/ir/base/tsIndexSignature.cpp | 1 + ets2panda/ir/base/tsPropertySignature.cpp | 1 + ets2panda/ir/expressions/callExpression.cpp | 1 + ets2panda/ir/expressions/chainExpression.cpp | 1 + ets2panda/ir/expressions/classExpression.cpp | 1 + ets2panda/ir/expressions/functionExpression.cpp | 1 + ets2panda/ir/expressions/identifier.cpp | 2 ++ ets2panda/ir/expressions/importExpression.cpp | 1 + .../ir/expressions/literals/bigIntLiteral.cpp | 1 + .../ir/expressions/literals/booleanLiteral.cpp | 1 + ets2panda/ir/expressions/literals/charLiteral.cpp | 1 + .../ir/expressions/literals/numberLiteral.cpp | 7 +++++-- .../ir/expressions/literals/regExpLiteral.cpp | 1 + .../ir/expressions/literals/stringLiteral.cpp | 1 + .../ir/expressions/literals/undefinedLiteral.cpp | 1 + ets2panda/ir/expressions/memberExpression.cpp | 3 +++ ets2panda/ir/expressions/newExpression.cpp | 1 + ets2panda/ir/expressions/objectExpression.cpp | 2 ++ ets2panda/ir/expressions/omittedExpression.cpp | 1 + ets2panda/ir/expressions/sequenceExpression.cpp | 1 + ets2panda/ir/expressions/superExpression.cpp | 1 + .../ir/expressions/taggedTemplateExpression.cpp | 1 + ets2panda/ir/expressions/templateLiteral.cpp | 1 + ets2panda/ir/expressions/thisExpression.cpp | 1 + ets2panda/ir/expressions/unaryExpression.cpp | 1 + ets2panda/ir/expressions/updateExpression.cpp | 1 + ets2panda/ir/expressions/yieldExpression.cpp | 2 +- ets2panda/ir/ts/tsArrayType.cpp | 1 + ets2panda/ir/ts/tsAsExpression.cpp | 1 + ets2panda/ir/ts/tsQualifiedName.cpp | 1 + ets2panda/ir/ts/tsThisType.cpp | 1 + ets2panda/ir/ts/tsTupleType.cpp | 13 +++++++++---- ets2panda/ir/ts/tsTypeLiteral.cpp | 1 + ets2panda/ir/ts/tsTypeParameterDeclaration.h | 1 + ets2panda/ir/typeNode.cpp | 1 + 63 files changed, 130 insertions(+), 22 deletions(-) diff --git a/ets2panda/ast_verifier/ASTVerifier.h b/ets2panda/ast_verifier/ASTVerifier.h index 9aaa1aecc3..f0d6315741 100644 --- a/ets2panda/ast_verifier/ASTVerifier.h +++ b/ets2panda/ast_verifier/ASTVerifier.h @@ -96,7 +96,7 @@ public: } } - ~ASTVerifier() + ~ASTVerifier() noexcept { if (!suppressed_) { if (Options().IsAstVerifierAfterPhases()) { diff --git a/ets2panda/compiler/base/lreference.cpp b/ets2panda/compiler/base/lreference.cpp index f9651af734..e466a11fa8 100644 --- a/ets2panda/compiler/base/lreference.cpp +++ b/ets2panda/compiler/base/lreference.cpp @@ -301,6 +301,7 @@ void ETSLReference::SetValueComputed(const ir::MemberExpression *memberExpr) con ES2PANDA_ASSERT(objectType->IsETSArrayType() || objectType->IsETSResizableArrayType()); auto vRegtype = etsg_->GetVRegType(baseReg_); + ES2PANDA_ASSERT(vRegtype != nullptr); auto *elementType = vRegtype->IsETSArrayType() ? vRegtype->AsETSArrayType()->ElementType() : vRegtype->AsETSResizableArrayType()->ElementType(); etsg_->StoreArrayElement(Node(), baseReg_, propReg_, elementType); @@ -308,6 +309,7 @@ void ETSLReference::SetValueComputed(const ir::MemberExpression *memberExpr) con void ETSLReference::SetValueGetterSetter(const ir::MemberExpression *memberExpr) const { + ES2PANDA_ASSERT(memberExpr->PropVar() != nullptr); const auto *sig = memberExpr->PropVar()->TsType()->AsETSFunctionType()->FindSetter(); auto argReg = etsg_->AllocReg(); @@ -341,7 +343,8 @@ void ETSLReference::SetValue() const return; } - if (memberExpr->PropVar()->TsType()->HasTypeFlag(checker::TypeFlag::GETTER_SETTER)) { + if (memberExpr->PropVar() != nullptr && + memberExpr->PropVar()->TsType()->HasTypeFlag(checker::TypeFlag::GETTER_SETTER)) { SetValueGetterSetter(memberExpr); return; } diff --git a/ets2panda/compiler/core/CFG.cpp b/ets2panda/compiler/core/CFG.cpp index cfafe5d792..80177b220e 100644 --- a/ets2panda/compiler/core/CFG.cpp +++ b/ets2panda/compiler/core/CFG.cpp @@ -33,6 +33,7 @@ size_t CFG::BasicBlock::AddNode(ir::AstNode *node) std::pair CFG::BasicBlock::AddSuccessor(BasicBlock *successor) { succs_.push_back(successor); + ES2PANDA_ASSERT(successor != nullptr); successor->preds_.push_back(this); return std::make_pair(succs_.size() - 1, successor->preds_.size() - 1); } @@ -208,6 +209,7 @@ CFG::BasicBlock *CFG::Build(ir::ScriptFunction *scriptFunctionNode) } ES2PANDA_ASSERT(scriptFunctionNode->Body()->IsBlockStatement()); auto exitBB = Build(scriptFunctionNode->Body()->AsBlockStatement(), entryBB); + ES2PANDA_ASSERT(exitBB != nullptr); exitBB->SetFlag(BasicBlockFlags::EXIT); return entryBB; } @@ -231,6 +233,7 @@ CFG::BasicBlock *CFG::CreateNewBB(const std::vector &&preds, const std::vector &&labels) { auto bb = allocator_->New(allocator_, basicBlockIdx_++); + ES2PANDA_ASSERT(bb != nullptr); if (inLoop_ > 0) { bb->SetFlag(BasicBlockFlags::LOOP); } @@ -840,6 +843,7 @@ size_t CFG::AddNodeToBB(ir::AstNode *node, BasicBlock *bb) if (bb == nullptr) { bb = CreateNewBB({}); } + ES2PANDA_ASSERT(bb != nullptr); size_t index = bb->AddNode(node); nodeBBMap_[node] = std::make_pair(bb, index); return index; diff --git a/ets2panda/compiler/core/ETSCompiler.cpp b/ets2panda/compiler/core/ETSCompiler.cpp index 76dc7e8bdf..43bc91d1fe 100644 --- a/ets2panda/compiler/core/ETSCompiler.cpp +++ b/ets2panda/compiler/core/ETSCompiler.cpp @@ -210,6 +210,7 @@ static void ConvertRestArguments(checker::ETSChecker *const checker, const ir::E elements.emplace_back(expr->GetArguments()[i]); } auto *arrayExpression = checker->AllocNode(std::move(elements), checker->Allocator()); + ES2PANDA_ASSERT(arrayExpression != nullptr); arrayExpression->SetParent(const_cast(expr)); auto restType = expr->GetSignature()->RestVar()->TsType()->AsETSArrayType(); arrayExpression->SetTsType(restType); @@ -749,6 +750,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() && + (etsg->Checker()->GetApparentType(me->Object()->TsType()) != nullptr) && (etsg->Checker()->GetApparentType(me->Object()->TsType())->IsETSUnionType())) { etsg->CallByName(expr, signature, calleeReg, expr->Arguments()); } else { @@ -958,6 +960,7 @@ void ETSCompiler::Compile(const ir::MemberExpression *expr) const bool ETSCompiler::HandleArrayTypeLengthProperty(const ir::MemberExpression *expr, ETSGen *etsg) const { auto *const objectType = etsg->Checker()->GetApparentType(expr->Object()->TsType()); + ES2PANDA_ASSERT(objectType != nullptr); auto &propName = expr->Property()->AsIdentifier()->Name(); if (objectType->IsETSArrayType() && propName.Is("length")) { auto ottctx = compiler::TargetTypeContext(etsg, objectType); @@ -981,6 +984,7 @@ bool ETSCompiler::HandleStaticProperties(const ir::MemberExpression *expr, ETSGe if (auto const *const varType = variable->TsType(); varType->HasTypeFlag(checker::TypeFlag::GETTER_SETTER)) { checker::Signature *sig = varType->AsETSFunctionType()->FindGetter(); + ES2PANDA_ASSERT(sig != nullptr); etsg->CallExact(expr, sig->InternalName()); etsg->SetAccumulatorType(expr->TsType()); } else { @@ -1009,6 +1013,7 @@ void ETSCompiler::Compile(const ir::ObjectExpression *expr) const auto *signatureInfo = etsg->Allocator()->New(etsg->Allocator()); auto *createObjSig = etsg->Allocator()->New(signatureInfo, nullptr, nullptr); + ES2PANDA_ASSERT(createObjSig != nullptr); createObjSig->SetInternalName(compiler::Signatures::BUILTIN_JSRUNTIME_CREATE_OBJECT); compiler::VReg dummyReg = compiler::VReg::RegStart(); etsg->CallDynamic(ETSGen::CallDynamicData {expr, dummyReg, dummyReg}, createObjSig, @@ -1575,7 +1580,7 @@ void ETSCompiler::CompileCastUnboxable(const ir::TSAsExpression *expr) const { ETSGen *etsg = GetETSGen(); auto *targetType = etsg->Checker()->GetApparentType(expr->TsType()); - ES2PANDA_ASSERT(targetType->IsETSObjectType()); + ES2PANDA_ASSERT(targetType != nullptr && targetType->IsETSObjectType()); switch (targetType->AsETSObjectType()->UnboxableKind()) { case checker::ETSObjectFlags::BUILTIN_BOOLEAN: diff --git a/ets2panda/compiler/core/ETSemitter.cpp b/ets2panda/compiler/core/ETSemitter.cpp index 66a81912f4..d4569622d1 100644 --- a/ets2panda/compiler/core/ETSemitter.cpp +++ b/ets2panda/compiler/core/ETSemitter.cpp @@ -116,6 +116,7 @@ static pandasm::Type PandasmTypeWithRank(checker::Type const *type, uint32_t ran static pandasm::Function GenScriptFunction(const ir::ScriptFunction *scriptFunc, ETSEmitter *emitter) { + ES2PANDA_ASSERT(scriptFunc != nullptr); auto *funcScope = scriptFunc->Scope(); auto *paramScope = funcScope->ParamScope(); @@ -247,6 +248,7 @@ static std::vector> StoreExportNodes( result.emplace_back(declString, node->AsClassProperty()->Id()->Name().Mutf8()); } else if (node->IsMethodDefinition()) { StoreEntity(literals, parser::EntityType::METHOD_DEFINITION); + ES2PANDA_ASSERT(node->AsMethodDefinition()->Function() != nullptr); result.emplace_back(declString, node->AsMethodDefinition()->Function()->Scope()->InternalName()); } else if (node->IsClassDefinition()) { StoreEntity(literals, parser::EntityType::CLASS_DEFINITION); @@ -433,6 +435,7 @@ void ETSEmitter::GenInterfaceMethodDefinition(const ir::MethodDefinition *method void ETSEmitter::GenClassField(const ir::ClassProperty *prop, pandasm::Record &classRecord, bool external) { auto field = pandasm::Field(Program()->lang); + ES2PANDA_ASSERT(prop->Id() != nullptr); field.name = prop->Id()->Name().Mutf8(); field.type = PandasmTypeWithRank(prop->TsType()); field.metadata->SetAccessFlags(TranslateModifierFlags(prop->Modifiers())); @@ -647,6 +650,8 @@ void ETSEmitter::CreateEnumProp(const ir::ClassProperty *prop, pandasm::Field &f return; } field.metadata->SetFieldType(field.type); + ES2PANDA_ASSERT(prop != nullptr && prop->Value() != nullptr && + prop->Value()->AsMemberExpression()->PropVar() != nullptr); auto declNode = prop->Value()->AsMemberExpression()->PropVar()->Declaration()->Node(); auto *init = declNode->AsClassProperty()->OriginEnumMember()->Init(); if (init->IsNumberLiteral()) { @@ -680,6 +685,7 @@ static void ProcessEnumExpression(std::vector &l { auto *memberExpr = elem->IsCallExpression() ? elem->AsCallExpression()->Arguments()[0]->AsMemberExpression() : elem->AsMemberExpression(); + ES2PANDA_ASSERT(memberExpr->PropVar() != nullptr); auto *init = memberExpr->PropVar()->Declaration()->Node()->AsClassProperty()->OriginEnumMember()->Init(); if (init->IsNumberLiteral()) { auto enumValue = static_cast(init->AsNumberLiteral()->Number().GetInt()); @@ -791,6 +797,7 @@ void ETSEmitter::GenCustomAnnotationProp(const ir::ClassProperty *prop, std::str { auto field = pandasm::Field(Program()->lang); auto *type = prop->TsType(); + ES2PANDA_ASSERT(prop->Id() != nullptr); field.name = prop->Id()->Name().Mutf8(); field.type = PandasmTypeWithRank(type); field.metadata->SetAccessFlags(TranslateModifierFlags(prop->Modifiers())); @@ -834,6 +841,7 @@ void ETSEmitter::GenCustomAnnotationRecord(const ir::AnnotationDeclaration *anno pandasm::AnnotationElement ETSEmitter::ProcessArrayType(const ir::ClassProperty *prop, std::string &baseName, const ir::Expression *init) { + ES2PANDA_ASSERT(prop->Id() != nullptr); auto propName = prop->Id()->Name().Mutf8(); std::string newBaseName = GenerateMangledName(baseName, propName); auto litArrays = CreateLiteralArray(newBaseName, init); @@ -850,6 +858,8 @@ pandasm::AnnotationElement ETSEmitter::ProcessArrayType(const ir::ClassProperty pandasm::AnnotationElement ETSEmitter::ProcessETSEnumType(std::string &baseName, const ir::Expression *init, const checker::Type *type) { + ES2PANDA_ASSERT(init != nullptr && init->AsMemberExpression() != nullptr && + init->AsMemberExpression()->PropVar() != nullptr); auto declNode = init->AsMemberExpression()->PropVar()->Declaration()->Node(); auto *initValue = declNode->AsClassProperty()->OriginEnumMember()->Init(); if (type->IsETSIntEnumType()) { @@ -868,6 +878,7 @@ pandasm::AnnotationElement ETSEmitter::GenCustomAnnotationElement(const ir::Clas const auto *init = prop->Value(); const auto *type = init->TsType(); auto typeKind = checker::ETSChecker::TypeKind(type); + ES2PANDA_ASSERT(prop->Id() != nullptr); auto propName = prop->Id()->Name().Mutf8(); if (type->IsETSArrayType() || type->IsETSResizableArrayType()) { return ProcessArrayType(prop, baseName, init); @@ -1005,6 +1016,7 @@ pandasm::AnnotationData ETSEmitter::GenAnnotationFunctionalReference(const ir::C GenAnnotationRecord(Signatures::ETS_ANNOTATION_FUNCTIONAL_REFERENCE); pandasm::AnnotationData functionalReference(Signatures::ETS_ANNOTATION_FUNCTIONAL_REFERENCE); bool isStatic = classDef->FunctionalReferenceReferencedMethod()->IsStatic(); + ES2PANDA_ASSERT(const_cast(classDef) != nullptr); pandasm::AnnotationElement value( Signatures::ANNOTATION_KEY_VALUE, std::make_unique( @@ -1079,6 +1091,7 @@ ir::MethodDefinition *ETSEmitter::FindAsyncImpl(ir::ScriptFunction *asyncFunc) auto *checker = static_cast(Context()->checker); checker::TypeRelation *typeRel = checker->Relation(); checker::SavedTypeRelationFlagsContext savedFlagsCtx(typeRel, checker::TypeRelationFlag::NO_RETURN_TYPE_CHECK); + ES2PANDA_ASSERT(method->Function() != nullptr); method->Function()->Signature()->IsSubtypeOf(typeRel, asyncFunc->Signature()); auto overloadIt = method->Overloads().begin(); while (overloadIt != method->Overloads().end() && !typeRel->IsTrue()) { @@ -1094,6 +1107,7 @@ pandasm::AnnotationData ETSEmitter::GenAnnotationAsync(ir::ScriptFunction *scrip GenAnnotationRecord(Signatures::ETS_COROUTINE_ASYNC); const ir::MethodDefinition *impl = FindAsyncImpl(scriptFunc); ES2PANDA_ASSERT(impl != nullptr); + ES2PANDA_ASSERT(impl->Function() != nullptr); pandasm::AnnotationData ann(Signatures::ETS_COROUTINE_ASYNC); pandasm::AnnotationElement value( Signatures::ANNOTATION_KEY_VALUE, diff --git a/ets2panda/compiler/core/JSCompiler.cpp b/ets2panda/compiler/core/JSCompiler.cpp index b7cb2f00d3..38332f2747 100644 --- a/ets2panda/compiler/core/JSCompiler.cpp +++ b/ets2panda/compiler/core/JSCompiler.cpp @@ -261,6 +261,7 @@ static void CompileStaticFieldInitializers(compiler::PandaGen *pg, compiler::VRe } if (prop->IsPrivateElement()) { + ES2PANDA_ASSERT(prop->Id() != nullptr); pg->ClassPrivateFieldAdd(prop, classReg, classReg, prop->Id()->Name()); continue; } @@ -395,6 +396,7 @@ void JSCompiler::Compile(const ir::ClassDefinition *node) const compiler::LocalRegScope lrs(pg, node->Scope()); compiler::VReg baseReg = CompileHeritageClause(pg, node); + ES2PANDA_ASSERT(node->Ctor() != nullptr); util::StringView ctorId = node->Ctor()->Function()->Scope()->InternalName(); util::BitSet compiled(node->Body().size()); diff --git a/ets2panda/compiler/core/dynamicContext.cpp b/ets2panda/compiler/core/dynamicContext.cpp index 2cb7dab7ba..c982ae44de 100644 --- a/ets2panda/compiler/core/dynamicContext.cpp +++ b/ets2panda/compiler/core/dynamicContext.cpp @@ -69,6 +69,7 @@ LexEnvContext::LexEnvContext(LoopEnvScope *envScope, PandaGen *pg, LabelTarget t } catchTable_ = Cg()->CreateCatchTable(); + ES2PANDA_ASSERT(catchTable_ != nullptr); const auto &labelSet = catchTable_->LabelSet(); const auto *node = envScope_->Scope()->Node(); @@ -222,6 +223,7 @@ void ETSTryContext::EmitFinalizer( // First compile of the finaly clause, executed if the statement executed normally tryStmt_->FinallyBlock()->Compile(etsg); + ES2PANDA_ASSERT(finalizerTable != nullptr); etsg->Branch(tryStmt_, finalizerTable->LabelSet().CatchEnd()); for (std::pair insertion : finalizerInsertions) { diff --git a/ets2panda/compiler/core/emitter.cpp b/ets2panda/compiler/core/emitter.cpp index 95b7d45aee..917ca1dc69 100644 --- a/ets2panda/compiler/core/emitter.cpp +++ b/ets2panda/compiler/core/emitter.cpp @@ -354,8 +354,8 @@ void FunctionEmitter::GenScopeVariableInfo(pandasm::Function *func, const varbin if (iter == lastIter || *iter == scope->ScopeEnd()) { return; } - uint32_t count = iter - instructions.begin(); - uint32_t start = count; + size_t count = iter - instructions.begin(); + size_t start = count; auto checkNodeIsValid = [](const ir::AstNode *node) { return node != nullptr && node != FIRST_NODE_OF_FUNCTION; }; // NOTE(dslynko, #19090): need to track start location for each local variable diff --git a/ets2panda/compiler/core/moduleContext.cpp b/ets2panda/compiler/core/moduleContext.cpp index 659d61305c..f9cc6f9ddc 100644 --- a/ets2panda/compiler/core/moduleContext.cpp +++ b/ets2panda/compiler/core/moduleContext.cpp @@ -35,7 +35,7 @@ void CompileImports(PandaGen *pg, varbinder::ModuleScope *scope) for (const auto *decl : decls) { varbinder::Variable *v = scope->FindLocal(decl->LocalName(), varbinder::ResolveBindingOptions::BINDINGS); - + ES2PANDA_ASSERT(v != nullptr); if (!v->IsModuleVariable()) { ES2PANDA_ASSERT(decl->ImportName() == "*"); diff --git a/ets2panda/compiler/core/pandagen.cpp b/ets2panda/compiler/core/pandagen.cpp index 85ab16b545..391de10e2d 100644 --- a/ets2panda/compiler/core/pandagen.cpp +++ b/ets2panda/compiler/core/pandagen.cpp @@ -1786,6 +1786,7 @@ void PandaGen::DirectEval(const ir::AstNode *node, uint32_t parserStatus) const auto *iter = Scope()->EnclosingVariableScope(); while (true) { + ES2PANDA_ASSERT(iter != nullptr); uint32_t scopeBindingsBuf = iter->EvalBindings(); if (scopeBindingsBuf != INVALID_LITERAL_BUFFER_ID) { Sa().Emit(node, util::Helpers::ToStringView(Allocator(), scopeBindingsBuf)); diff --git a/ets2panda/compiler/core/regAllocator.cpp b/ets2panda/compiler/core/regAllocator.cpp index 408daed8c6..f951ecdf6a 100644 --- a/ets2panda/compiler/core/regAllocator.cpp +++ b/ets2panda/compiler/core/regAllocator.cpp @@ -146,6 +146,7 @@ void RegAllocator::Run(IRNode *const ins, const int32_t spillMax) { ES2PANDA_ASSERT(Spiller().Restored()); std::array regs {}; + ES2PANDA_ASSERT(ins != nullptr); const auto regCnt = ins->Registers(®s); const auto registers = Span(regs.data(), regs.data() + (spillMax == std::numeric_limits::max() ? regCnt : spillMax)); @@ -215,6 +216,7 @@ void RangeRegAllocator::Run(IRNode *const ins, VReg rangeStart, const std::size_ const auto rangeEnd = rangeStart + argCount; std::array regs {}; + ES2PANDA_ASSERT(ins != nullptr); const auto regCnt = ins->Registers(®s); const auto registers = Span(regs.data(), regs.data() + regCnt); if (RegIndicesValid(ins, registers).first) { diff --git a/ets2panda/compiler/lowering/ets/ambientLowering.cpp b/ets2panda/compiler/lowering/ets/ambientLowering.cpp index b07f25dc9b..7f7f319086 100644 --- a/ets2panda/compiler/lowering/ets/ambientLowering.cpp +++ b/ets2panda/compiler/lowering/ets/ambientLowering.cpp @@ -82,6 +82,7 @@ ir::MethodDefinition *CreateMethodFunctionDefinition(ir::DummyNode *node, public methodDefinition->SetParent(node->Parent()); methodDefinition->AddModifier(ir::ModifierFlags::DECLARE); + ES2PANDA_ASSERT(methodDefinition->AsMethodDefinition()->Function() != nullptr); methodDefinition->AsMethodDefinition()->Function()->AddModifier(ir::ModifierFlags::DECLARE); return methodDefinition->AsMethodDefinition(); } diff --git a/ets2panda/compiler/lowering/ets/arrayLiteralLowering.cpp b/ets2panda/compiler/lowering/ets/arrayLiteralLowering.cpp index a9aa187de8..574de47b0b 100644 --- a/ets2panda/compiler/lowering/ets/arrayLiteralLowering.cpp +++ b/ets2panda/compiler/lowering/ets/arrayLiteralLowering.cpp @@ -56,6 +56,7 @@ ArenaVector ArrayLiteralLowering::GenerateDefaultCallToConstruc ss << "@@I8[@@I9] = new @@T10() }"; newStmts.emplace_back(arraySymbol->Clone(Allocator(), nullptr)); newStmts.emplace_back(indexSymbol->Clone(Allocator(), nullptr)); + ES2PANDA_ASSERT(typeNode != nullptr); newStmts.emplace_back(typeNode->Clone(Allocator(), nullptr)); } else { ArenaVector emptyStatement(Allocator()->Adapter()); @@ -100,6 +101,7 @@ ir::AstNode *ArrayLiteralLowering::TryTransformLiteralArrayToRefArray(ir::ArrayE auto *parent = literalArray->Parent(); auto *loweringResult = parser_->CreateFormattedExpression(ss.str(), newStmts); + ES2PANDA_ASSERT(loweringResult != nullptr); loweringResult->SetRange(literalArray->Range()); loweringResult->SetParent(parent); diff --git a/ets2panda/compiler/lowering/ets/asyncMethodLowering.cpp b/ets2panda/compiler/lowering/ets/asyncMethodLowering.cpp index d801b5526c..ad6c0daeeb 100644 --- a/ets2panda/compiler/lowering/ets/asyncMethodLowering.cpp +++ b/ets2panda/compiler/lowering/ets/asyncMethodLowering.cpp @@ -32,6 +32,7 @@ static void CreateFuncDecl(checker::ETSChecker *checker, ir::MethodDefinition *f auto *varBinder = checker->VarBinder(); // Add the function declarations to the lambda class scope auto ctx = varbinder::LexicalScope::Enter(varBinder, scope); + ES2PANDA_ASSERT(func->Id() != nullptr); varbinder::Variable *var = scope->FindLocal(func->Id()->Name(), varbinder::ResolveBindingOptions::ALL_DECLARATION); if (var == nullptr) { var = std::get<1>( @@ -53,6 +54,7 @@ ir::ETSTypeReference *CreateAsyncImplMethodReturnTypeAnnotation(checker::ETSChec auto *returnTypeAnn = checker->AllocNode( checker->AllocNode(objectId, nullptr, nullptr, checker->Allocator()), checker->Allocator()); + ES2PANDA_ASSERT(returnTypeAnn != nullptr); objectId->SetParent(returnTypeAnn->Part()); returnTypeAnn->Part()->SetParent(returnTypeAnn); @@ -76,6 +78,7 @@ ir::MethodDefinition *CreateAsyncImplMethod(checker::ETSChecker *checker, ir::Me // clear ASYNC flag for implementation modifiers &= ~ir::ModifierFlags::ASYNC; ir::ScriptFunction *asyncFunc = asyncMethod->Function(); + ES2PANDA_ASSERT(asyncFunc != nullptr); ir::ScriptFunctionFlags flags = ir::ScriptFunctionFlags::METHOD; if (asyncFunc->IsProxy()) { @@ -124,6 +127,7 @@ ir::MethodDefinition *CreateAsyncImplMethod(checker::ETSChecker *checker, ir::Me ir::MethodDefinition *CreateAsyncProxy(checker::ETSChecker *checker, ir::MethodDefinition *asyncMethod, ir::ClassDefinition *classDef) { + ES2PANDA_ASSERT(asyncMethod != nullptr); ir::ScriptFunction *asyncFunc = asyncMethod->Function(); if (!asyncFunc->IsExternal()) { checker->VarBinder()->AsETSBinder()->GetRecordTable()->Signatures().push_back(asyncFunc->Scope()); @@ -159,6 +163,7 @@ ir::MethodDefinition *CreateAsyncProxy(checker::ETSChecker *checker, ir::MethodD void ComposeAsyncImplMethod(checker::ETSChecker *checker, ir::MethodDefinition *node) { + ES2PANDA_ASSERT(checker->FindAncestorGivenByType(node, ir::AstNodeType::CLASS_DEFINITION) != nullptr); auto *classDef = checker->FindAncestorGivenByType(node, ir::AstNodeType::CLASS_DEFINITION)->AsClassDefinition(); ir::MethodDefinition *implMethod = CreateAsyncProxy(checker, node, classDef); @@ -176,7 +181,7 @@ void ComposeAsyncImplMethod(checker::ETSChecker *checker, ir::MethodDefinition * void HandleMethod(checker::ETSChecker *checker, ir::MethodDefinition *node) { - ES2PANDA_ASSERT(!node->TsType()->IsTypeError()); + ES2PANDA_ASSERT(!node->TsType()->IsTypeError() && node->Function() != nullptr); if (util::Helpers::IsAsyncMethod(node) && !node->Function()->IsExternal()) { ComposeAsyncImplMethod(checker, node); } diff --git a/ets2panda/compiler/lowering/ets/boxingForLocals.cpp b/ets2panda/compiler/lowering/ets/boxingForLocals.cpp index 2f63e74222..dd2e41e0fc 100644 --- a/ets2panda/compiler/lowering/ets/boxingForLocals.cpp +++ b/ets2panda/compiler/lowering/ets/boxingForLocals.cpp @@ -132,6 +132,7 @@ static void HandleFunctionParam(public_lib::Context *ctx, ir::ETSParameterExpres auto *scope = body->Scope(); auto *initId = allocator->New(id->Name(), allocator); + ES2PANDA_ASSERT(initId != nullptr); initId->SetVariable(id->Variable()); initId->SetTsType(oldType); @@ -203,6 +204,7 @@ static ir::AstNode *HandleVariableDeclarator(public_lib::Context *ctx, ir::Varia auto *newDecl = allocator->New(oldVar->Name(), newDeclarator); auto *newVar = allocator->New(newDecl, oldVar->Flags()); + ES2PANDA_ASSERT(newVar != nullptr); newDeclarator->Id()->AsIdentifier()->SetVariable(newVar); newVar->AddFlag(varbinder::VariableFlags::INITIALIZED); newVar->SetScope(scope); diff --git a/ets2panda/evaluate/debugInfoDeserialization/debugInfoDeserializer.cpp b/ets2panda/evaluate/debugInfoDeserialization/debugInfoDeserializer.cpp index 56a8350b50..16ee81d217 100644 --- a/ets2panda/evaluate/debugInfoDeserialization/debugInfoDeserializer.cpp +++ b/ets2panda/evaluate/debugInfoDeserialization/debugInfoDeserializer.cpp @@ -75,7 +75,7 @@ varbinder::Variable *DebugInfoDeserializer::CreateIrClass(panda_file::File::Enti ES2PANDA_ASSERT(program); const auto *pf = debugInfoPlugin_.GetDebugInfoStorage()->GetPandaFile(pathToSource.Utf8()); - ES2PANDA_ASSERT(pf); + ES2PANDA_ASSERT(pf != nullptr); // NOTE: may cache the created `ClassDataAccessor`. auto cda = panda_file::ClassDataAccessor(*pf, classId); @@ -145,6 +145,7 @@ varbinder::Variable *DebugInfoDeserializer::CreateIrGlobalVariable(parser::Progr varbinder::Variable *var = nullptr; auto *cda = debugInfoStorage->GetGlobalClassAccessor(pathToSource.Utf8()); + ES2PANDA_ASSERT(cda != nullptr); cda->EnumerateFields([program, varDeclName, pf, &var, checkHelper](panda_file::FieldDataAccessor &fda) { // All ETSGLOBAL fields must be static. ES2PANDA_ASSERT(fda.IsStatic()); @@ -183,6 +184,7 @@ varbinder::Variable *DebugInfoDeserializer::CreateIrGlobalMethods(ArenaVectorGetGlobalClassAccessor(pathToSource.Utf8()); + ES2PANDA_ASSERT(cda != nullptr); cda->EnumerateMethods([this, &var, &createdMethods, program, methodDeclName, &cda](panda_file::MethodDataAccessor &mda) { if (!methodDeclName.Is(mda.GetFullName())) { diff --git a/ets2panda/evaluate/debugInfoDeserialization/methodBuilder.cpp b/ets2panda/evaluate/debugInfoDeserialization/methodBuilder.cpp index 2f79f32dbf..f4a9db5c1e 100644 --- a/ets2panda/evaluate/debugInfoDeserialization/methodBuilder.cpp +++ b/ets2panda/evaluate/debugInfoDeserialization/methodBuilder.cpp @@ -171,6 +171,7 @@ ir::AstNode *MethodBuilder::CreateIrConstructor(ir::Identifier *id, ir::BlockSta if constexpr (IS_STATIC) { // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *staticBlock = checker_->AllocNode(funcExpr, allocator); + ES2PANDA_ASSERT(staticBlock != nullptr); staticBlock->AddModifier(ir::ModifierFlags::STATIC); return staticBlock; } @@ -184,6 +185,7 @@ ir::MethodDefinition *MethodBuilder::CreateIrMethod(ir::Identifier *id, ir::Bloc { auto *allocator = checker_->Allocator(); auto *funcExpr = CreateFunctionExpression(id, body, ir::ScriptFunctionFlags::METHOD); + ES2PANDA_ASSERT(funcExpr != nullptr); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *method = checker_->AllocNode(ir::MethodDefinitionKind::METHOD, funcExpr->Function()->Id()->Clone(allocator, nullptr), @@ -200,6 +202,7 @@ ir::FunctionExpression *MethodBuilder::CreateFunctionExpression(ir::Identifier * auto *func = checker_->AllocNode( checker_->Allocator(), ir::ScriptFunction::ScriptFunctionData {body, std::move(funcSignature), scriptFuncFlags, modifierFlags_}); + ES2PANDA_ASSERT(func != nullptr); func->SetIdent(id); func->SetReturnTypeAnnotation(returnType_); diff --git a/ets2panda/evaluate/helpers.cpp b/ets2panda/evaluate/helpers.cpp index 210e57abe7..e41daa9022 100644 --- a/ets2panda/evaluate/helpers.cpp +++ b/ets2panda/evaluate/helpers.cpp @@ -243,7 +243,7 @@ std::optional ToTypeName(std::string_view typeSignature, checker::G pandasm::Type type = pandasm::Type::FromDescriptor(typeSignature); auto *checkerType = PrimitiveToCheckerType(type.GetId(), globalTypes); - ES2PANDA_ASSERT(checkerType); + ES2PANDA_ASSERT(checkerType != nullptr); return checkerType->ToString(); } diff --git a/ets2panda/evaluate/scopedDebugInfoPlugin.cpp b/ets2panda/evaluate/scopedDebugInfoPlugin.cpp index fc8666dc9e..2b34d66784 100644 --- a/ets2panda/evaluate/scopedDebugInfoPlugin.cpp +++ b/ets2panda/evaluate/scopedDebugInfoPlugin.cpp @@ -33,6 +33,7 @@ ir::VariableDeclaration *CreateVariableDeclaration(checker::ETSChecker *checker, ir::Expression *init) { auto *declarator = checker->AllocNode(ir::VariableDeclaratorFlag::CONST, ident, init); + ES2PANDA_ASSERT(declarator != nullptr); ArenaVector declarators(1, declarator, checker->Allocator()->Adapter()); auto *declaration = checker->AllocNode( @@ -404,6 +405,7 @@ parser::Program *ScopedDebugInfoPlugin::CreateEmptyProgram(std::string_view sour // Checker doesn't yet have `VarBinder`, must retrieve it from `globalProgram_`. parser::Program *program = allocator->New(allocator, GetETSBinder()); + ES2PANDA_ASSERT(program != nullptr); program->SetSource({sourceFilePath, "", globalProgram_->SourceFileFolder().Utf8(), true, false}); program->SetPackageInfo(moduleName, util::ModuleKind::MODULE); auto *emptyIdent = allocator->New("", allocator); diff --git a/ets2panda/ir/base/catchClause.cpp b/ets2panda/ir/base/catchClause.cpp index 53b37af715..c4c120f155 100644 --- a/ets2panda/ir/base/catchClause.cpp +++ b/ets2panda/ir/base/catchClause.cpp @@ -96,13 +96,20 @@ checker::VerifiedType CatchClause::Check(checker::ETSChecker *checker) CatchClause::CatchClause(CatchClause const &other, ArenaAllocator *allocator) : TypedStatement(other) { - param_ = other.param_ == nullptr ? nullptr : other.param_->Clone(allocator, this)->AsExpression(); - body_ = other.body_ == nullptr ? nullptr : other.body_->Clone(allocator, this)->AsBlockStatement(); + param_ = nullptr; + body_ = nullptr; + if (other.param_ != nullptr && other.param_->Clone(allocator, this) != nullptr) { + param_ = other.param_->Clone(allocator, this)->AsExpression(); + } + if (other.body_ != nullptr && other.body_->Clone(allocator, this) != nullptr) { + body_ = other.body_->Clone(allocator, this)->AsBlockStatement(); + } } CatchClause *CatchClause::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(*this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/base/decorator.cpp b/ets2panda/ir/base/decorator.cpp index 08bb4ffc5c..6198ae7b4f 100644 --- a/ets2panda/ir/base/decorator.cpp +++ b/ets2panda/ir/base/decorator.cpp @@ -68,7 +68,7 @@ Decorator *Decorator::Clone(ArenaAllocator *const allocator, AstNode *const pare { auto *const expr = expr_ != nullptr ? expr_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(expr); - + ES2PANDA_ASSERT(clone != nullptr); if (expr != nullptr) { expr->SetParent(clone); } diff --git a/ets2panda/ir/base/metaProperty.cpp b/ets2panda/ir/base/metaProperty.cpp index fcb85de132..38bed829d8 100644 --- a/ets2panda/ir/base/metaProperty.cpp +++ b/ets2panda/ir/base/metaProperty.cpp @@ -76,6 +76,7 @@ checker::VerifiedType MetaProperty::Check(checker::ETSChecker *checker) MetaProperty *MetaProperty::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(kind_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/base/methodDefinition.cpp b/ets2panda/ir/base/methodDefinition.cpp index cf497838fb..16b2aad0e6 100644 --- a/ets2panda/ir/base/methodDefinition.cpp +++ b/ets2panda/ir/base/methodDefinition.cpp @@ -274,6 +274,7 @@ bool MethodDefinition::FilterForDeclGen(ir::SrcDumper *dumper) const return true; } + ES2PANDA_ASSERT(Id() != nullptr); auto name = Id()->Name().Mutf8(); if (name.find("$asyncimpl") != std::string::npos || name == compiler::Signatures::INITIALIZER_BLOCK_INIT || name == compiler::Signatures::INIT_METHOD) { @@ -301,7 +302,8 @@ void MethodDefinition::Dump(ir::SrcDumper *dumper) const return; } - if (compiler::HasGlobalClassParent(this) && Id()->Name().Is(compiler::Signatures::INIT_METHOD)) { + if (compiler::HasGlobalClassParent(this) && Id() != nullptr && Id()->Name().Is(compiler::Signatures::INIT_METHOD) && + Function() != nullptr) { Function()->Body()->Dump(dumper); return; } diff --git a/ets2panda/ir/base/methodDefinition.h b/ets2panda/ir/base/methodDefinition.h index 22b5321129..0a45fc032f 100644 --- a/ets2panda/ir/base/methodDefinition.h +++ b/ets2panda/ir/base/methodDefinition.h @@ -154,7 +154,7 @@ public: void AddOverload(MethodDefinition *const overload) { - ES2PANDA_ASSERT(overload != nullptr); + ES2PANDA_ASSERT(overload != nullptr && overload->Function() != nullptr); overloads_.emplace_back(overload); overload->Function()->AddFlag((ir::ScriptFunctionFlags::OVERLOAD)); overload->SetBaseOverloadMethod(this); diff --git a/ets2panda/ir/base/property.cpp b/ets2panda/ir/base/property.cpp index 24deab39d0..8df2099a5a 100644 --- a/ets2panda/ir/base/property.cpp +++ b/ets2panda/ir/base/property.cpp @@ -33,7 +33,7 @@ Property *Property::Clone(ArenaAllocator *const allocator, AstNode *const parent auto *const key = key_ != nullptr ? key_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const value = value_ != nullptr ? value_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(Tag {}, *this, key, value); - + ES2PANDA_ASSERT(clone != nullptr); if (key != nullptr) { key->SetParent(clone); } diff --git a/ets2panda/ir/base/scriptFunction.cpp b/ets2panda/ir/base/scriptFunction.cpp index 0eb77cd6c8..f622829dd7 100644 --- a/ets2panda/ir/base/scriptFunction.cpp +++ b/ets2panda/ir/base/scriptFunction.cpp @@ -64,6 +64,7 @@ std::size_t ScriptFunction::FormalParamsLength() const noexcept void ScriptFunction::SetIdent(Identifier *id) noexcept { id_ = id; + ES2PANDA_ASSERT(id_ != nullptr); id_->SetParent(this); } @@ -89,6 +90,7 @@ ScriptFunction *ScriptFunction::Clone(ArenaAllocator *allocator, AstNode *parent : nullptr, HasReceiver()}, funcFlags_, flags_, lang_}); + ES2PANDA_ASSERT(res != nullptr); res->SetParent(parent); res->SetAnnotations(std::move(annotationUsages)); return res; diff --git a/ets2panda/ir/base/spreadElement.cpp b/ets2panda/ir/base/spreadElement.cpp index 1f69ae5286..e8188e8aa9 100644 --- a/ets2panda/ir/base/spreadElement.cpp +++ b/ets2panda/ir/base/spreadElement.cpp @@ -36,6 +36,7 @@ SpreadElement::SpreadElement([[maybe_unused]] Tag const tag, SpreadElement const SpreadElement *SpreadElement::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/base/templateElement.cpp b/ets2panda/ir/base/templateElement.cpp index 6ab35fff9e..4ba3be396a 100644 --- a/ets2panda/ir/base/templateElement.cpp +++ b/ets2panda/ir/base/templateElement.cpp @@ -63,6 +63,7 @@ checker::VerifiedType TemplateElement::Check(checker::ETSChecker *checker) TemplateElement *TemplateElement::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(raw_, cooked_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/base/tsIndexSignature.cpp b/ets2panda/ir/base/tsIndexSignature.cpp index ae7cd74478..22d8a78b56 100644 --- a/ets2panda/ir/base/tsIndexSignature.cpp +++ b/ets2panda/ir/base/tsIndexSignature.cpp @@ -83,6 +83,7 @@ TSIndexSignature *TSIndexSignature::Clone(ArenaAllocator *const allocator, AstNo auto *const param = param_ != nullptr ? param_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const typeAnnotation = typeAnnotation_->Clone(allocator, nullptr); auto *const clone = allocator->New(param, typeAnnotation, readonly_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); diff --git a/ets2panda/ir/base/tsPropertySignature.cpp b/ets2panda/ir/base/tsPropertySignature.cpp index 7c993c2ad7..d1a2bb2ee1 100644 --- a/ets2panda/ir/base/tsPropertySignature.cpp +++ b/ets2panda/ir/base/tsPropertySignature.cpp @@ -85,6 +85,7 @@ TSPropertySignature *TSPropertySignature::Clone(ArenaAllocator *const allocator, auto *const typeAnnotation = TypeAnnotation()->Clone(allocator, nullptr); auto *const clone = allocator->New(key, typeAnnotation, computed_, optional_, readonly_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); diff --git a/ets2panda/ir/expressions/callExpression.cpp b/ets2panda/ir/expressions/callExpression.cpp index a7bfa507bb..0a512fc229 100644 --- a/ets2panda/ir/expressions/callExpression.cpp +++ b/ets2panda/ir/expressions/callExpression.cpp @@ -147,6 +147,7 @@ CallExpression::CallExpression(CallExpression const &other, ArenaAllocator *cons CallExpression *CallExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(*this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/chainExpression.cpp b/ets2panda/ir/expressions/chainExpression.cpp index d805249fd3..b594540b44 100644 --- a/ets2panda/ir/expressions/chainExpression.cpp +++ b/ets2panda/ir/expressions/chainExpression.cpp @@ -87,6 +87,7 @@ ChainExpression *ChainExpression::Clone(ArenaAllocator *const allocator, AstNode expression->SetParent(clone); } + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/classExpression.cpp b/ets2panda/ir/expressions/classExpression.cpp index d5d8d83cfb..36a0f7fa2e 100644 --- a/ets2panda/ir/expressions/classExpression.cpp +++ b/ets2panda/ir/expressions/classExpression.cpp @@ -67,6 +67,7 @@ ClassExpression *ClassExpression::Clone(ArenaAllocator *const allocator, AstNode { auto *const def = def_ != nullptr ? def_->Clone(allocator, nullptr)->AsClassDefinition() : nullptr; auto *const clone = allocator->New(def); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); diff --git a/ets2panda/ir/expressions/functionExpression.cpp b/ets2panda/ir/expressions/functionExpression.cpp index 8e39aaff4b..054e3eae82 100644 --- a/ets2panda/ir/expressions/functionExpression.cpp +++ b/ets2panda/ir/expressions/functionExpression.cpp @@ -67,6 +67,7 @@ FunctionExpression *FunctionExpression::Clone(ArenaAllocator *const allocator, A { auto *const func = func_->Clone(allocator, nullptr)->AsScriptFunction(); auto *const clone = allocator->New(func); + ES2PANDA_ASSERT(clone != nullptr); func->SetParent(clone); if (parent != nullptr) { clone->SetParent(parent); diff --git a/ets2panda/ir/expressions/identifier.cpp b/ets2panda/ir/expressions/identifier.cpp index ad06be7bfb..ad7eca0627 100644 --- a/ets2panda/ir/expressions/identifier.cpp +++ b/ets2panda/ir/expressions/identifier.cpp @@ -62,6 +62,7 @@ void Identifier::SetName(const util::StringView &newName) noexcept Identifier *Identifier::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); clone->SetTsType(TsType()); if (parent != nullptr) { @@ -75,6 +76,7 @@ Identifier *Identifier::Clone(ArenaAllocator *const allocator, AstNode *const pa Identifier *Identifier::CloneReference(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = Clone(allocator, parent); + ES2PANDA_ASSERT(clone != nullptr); if (clone->IsReference(ScriptExtension::ETS)) { clone->SetTsTypeAnnotation(nullptr); } diff --git a/ets2panda/ir/expressions/importExpression.cpp b/ets2panda/ir/expressions/importExpression.cpp index 9a0c7d40fe..13afd2511d 100644 --- a/ets2panda/ir/expressions/importExpression.cpp +++ b/ets2panda/ir/expressions/importExpression.cpp @@ -71,6 +71,7 @@ ImportExpression *ImportExpression::Clone(ArenaAllocator *const allocator, AstNo source->SetParent(clone); } + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/literals/bigIntLiteral.cpp b/ets2panda/ir/expressions/literals/bigIntLiteral.cpp index 877c53e20d..4988527d1c 100644 --- a/ets2panda/ir/expressions/literals/bigIntLiteral.cpp +++ b/ets2panda/ir/expressions/literals/bigIntLiteral.cpp @@ -61,6 +61,7 @@ checker::VerifiedType BigIntLiteral::Check([[maybe_unused]] checker::ETSChecker BigIntLiteral *BigIntLiteral::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(src_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/literals/booleanLiteral.cpp b/ets2panda/ir/expressions/literals/booleanLiteral.cpp index 2b24ef60ff..513b42d9a2 100644 --- a/ets2panda/ir/expressions/literals/booleanLiteral.cpp +++ b/ets2panda/ir/expressions/literals/booleanLiteral.cpp @@ -61,6 +61,7 @@ checker::VerifiedType BooleanLiteral::Check([[maybe_unused]] checker::ETSChecker BooleanLiteral *BooleanLiteral::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(boolean_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/literals/charLiteral.cpp b/ets2panda/ir/expressions/literals/charLiteral.cpp index c97c0216f0..564c760adb 100644 --- a/ets2panda/ir/expressions/literals/charLiteral.cpp +++ b/ets2panda/ir/expressions/literals/charLiteral.cpp @@ -67,6 +67,7 @@ checker::VerifiedType CharLiteral::Check([[maybe_unused]] checker::ETSChecker *c CharLiteral *CharLiteral::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(char_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/literals/numberLiteral.cpp b/ets2panda/ir/expressions/literals/numberLiteral.cpp index 7a2c2267dc..a9390d446e 100644 --- a/ets2panda/ir/expressions/literals/numberLiteral.cpp +++ b/ets2panda/ir/expressions/literals/numberLiteral.cpp @@ -20,6 +20,8 @@ #include "compiler/core/pandagen.h" #include "util/dtoa_helper.h" +#include + namespace ark::es2panda::ir { inline constexpr size_t BUF_SIZE = 128; @@ -89,6 +91,7 @@ checker::VerifiedType NumberLiteral::Check(checker::ETSChecker *checker) NumberLiteral *NumberLiteral::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(number_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } @@ -253,7 +256,7 @@ static Span FpToStringDecimalRadixMainCase(FpType number, bool negative, S // 8. If −6 < n ≤ 0, return the String consisting of the code unit 0x0030 (DIGIT ZERO), followed by the code // unit 0x002E (FULL STOP), followed by −n occurrences of the code unit 0x0030 (DIGIT ZERO), followed by the // code units of the k digits of the decimal representation of s. - auto length = -n + 2U; + int length = -n + 2U; auto fracStart = bufferStart + length; if (memmove_s(fracStart, buffer.end() - fracStart, bufferStart, k) != EOK) { ES2PANDA_UNREACHABLE(); @@ -312,7 +315,7 @@ static char *SmallFpToString(FpType number, bool negative, char *buffer) power *= TEN; } for (int k = digits - 1; k >= 0; k--) { - auto digit = s % TEN; + auto digit = std::abs(s) % TEN; s /= TEN; *(buffer + k) = '0' + digit; } diff --git a/ets2panda/ir/expressions/literals/regExpLiteral.cpp b/ets2panda/ir/expressions/literals/regExpLiteral.cpp index f0f29978d4..e7e6bbbc13 100644 --- a/ets2panda/ir/expressions/literals/regExpLiteral.cpp +++ b/ets2panda/ir/expressions/literals/regExpLiteral.cpp @@ -61,6 +61,7 @@ checker::VerifiedType RegExpLiteral::Check(checker::ETSChecker *checker) RegExpLiteral *RegExpLiteral::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(pattern_, flags_, flagsStr_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/literals/stringLiteral.cpp b/ets2panda/ir/expressions/literals/stringLiteral.cpp index f47fe3ea32..2874e23442 100644 --- a/ets2panda/ir/expressions/literals/stringLiteral.cpp +++ b/ets2panda/ir/expressions/literals/stringLiteral.cpp @@ -60,6 +60,7 @@ checker::VerifiedType StringLiteral::Check(checker::ETSChecker *checker) StringLiteral *StringLiteral::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(str_); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/literals/undefinedLiteral.cpp b/ets2panda/ir/expressions/literals/undefinedLiteral.cpp index c044fbcd04..c15e0437df 100644 --- a/ets2panda/ir/expressions/literals/undefinedLiteral.cpp +++ b/ets2panda/ir/expressions/literals/undefinedLiteral.cpp @@ -64,6 +64,7 @@ checker::VerifiedType UndefinedLiteral::Check(checker::ETSChecker *checker) UndefinedLiteral *UndefinedLiteral::Clone(ArenaAllocator *allocator, AstNode *parent) { auto *const clone = allocator->New(); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/memberExpression.cpp b/ets2panda/ir/expressions/memberExpression.cpp index 9b8569317c..a0b9b4bc75 100644 --- a/ets2panda/ir/expressions/memberExpression.cpp +++ b/ets2panda/ir/expressions/memberExpression.cpp @@ -224,6 +224,7 @@ checker::Type *MemberExpression::TraverseUnionMember(checker::ETSChecker *checke for (auto *const type : unionType->ConstituentTypes()) { auto *const apparent = checker->GetApparentType(type); + ES2PANDA_ASSERT(apparent != nullptr); if (apparent->IsETSObjectType()) { SetObjectType(apparent->AsETSObjectType()); addPropType(ResolveObjectMember(checker).first); @@ -279,6 +280,7 @@ static checker::Type *AdjustRecordReturnType(checker::Type *type, checker::Type checker::Type *MemberExpression::AdjustType(checker::ETSChecker *checker, checker::Type *type) { auto *const objType = checker->GetApparentType(Object()->TsType()); + ES2PANDA_ASSERT(objType != nullptr); if (type != nullptr && objType->IsETSObjectType() && objType->ToAssemblerName().str() == compiler::Signatures::BUILTIN_RECORD) { type = AdjustRecordReturnType(type, objType); @@ -543,6 +545,7 @@ checker::VerifiedType MemberExpression::Check(checker::ETSChecker *checker) MemberExpression *MemberExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/newExpression.cpp b/ets2panda/ir/expressions/newExpression.cpp index 0138a4216c..121a9871a1 100644 --- a/ets2panda/ir/expressions/newExpression.cpp +++ b/ets2panda/ir/expressions/newExpression.cpp @@ -36,6 +36,7 @@ NewExpression::NewExpression([[maybe_unused]] Tag const tag, NewExpression const NewExpression *NewExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/objectExpression.cpp b/ets2panda/ir/expressions/objectExpression.cpp index 11e04243c2..1d238cf5fd 100644 --- a/ets2panda/ir/expressions/objectExpression.cpp +++ b/ets2panda/ir/expressions/objectExpression.cpp @@ -43,6 +43,7 @@ ObjectExpression::ObjectExpression([[maybe_unused]] Tag const tag, ObjectExpress ObjectExpression *ObjectExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } @@ -336,6 +337,7 @@ checker::Type *ObjectExpression::CheckPattern(checker::TSChecker *checker) varbinder::LocalVariable *patternVar = varbinder::Scope::CreateVar( checker->Allocator(), prop->Key()->AsIdentifier()->Name(), varbinder::VariableFlags::PROPERTY, *it); + ES2PANDA_ASSERT(patternVar != nullptr); patternVar->SetTsType(patternParamType); if (isOptional) { diff --git a/ets2panda/ir/expressions/omittedExpression.cpp b/ets2panda/ir/expressions/omittedExpression.cpp index 17e99c3377..a804144ab3 100644 --- a/ets2panda/ir/expressions/omittedExpression.cpp +++ b/ets2panda/ir/expressions/omittedExpression.cpp @@ -60,6 +60,7 @@ checker::VerifiedType OmittedExpression::Check(checker::ETSChecker *checker) OmittedExpression *OmittedExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/sequenceExpression.cpp b/ets2panda/ir/expressions/sequenceExpression.cpp index cbe9d5dbbb..f84e542b58 100644 --- a/ets2panda/ir/expressions/sequenceExpression.cpp +++ b/ets2panda/ir/expressions/sequenceExpression.cpp @@ -33,6 +33,7 @@ SequenceExpression::SequenceExpression([[maybe_unused]] Tag const tag, SequenceE SequenceExpression *SequenceExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/superExpression.cpp b/ets2panda/ir/expressions/superExpression.cpp index 2bfb758bfa..027182de8a 100644 --- a/ets2panda/ir/expressions/superExpression.cpp +++ b/ets2panda/ir/expressions/superExpression.cpp @@ -61,6 +61,7 @@ checker::VerifiedType SuperExpression::Check([[maybe_unused]] checker::ETSChecke SuperExpression *SuperExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/taggedTemplateExpression.cpp b/ets2panda/ir/expressions/taggedTemplateExpression.cpp index 54eb9a71c8..29d2ccda65 100644 --- a/ets2panda/ir/expressions/taggedTemplateExpression.cpp +++ b/ets2panda/ir/expressions/taggedTemplateExpression.cpp @@ -102,6 +102,7 @@ TaggedTemplateExpression *TaggedTemplateExpression::Clone(ArenaAllocator *const typeParams->SetParent(clone); } + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/templateLiteral.cpp b/ets2panda/ir/expressions/templateLiteral.cpp index e7c10eda77..4275fe126a 100644 --- a/ets2panda/ir/expressions/templateLiteral.cpp +++ b/ets2panda/ir/expressions/templateLiteral.cpp @@ -41,6 +41,7 @@ TemplateLiteral::TemplateLiteral([[maybe_unused]] Tag const tag, TemplateLiteral TemplateLiteral *TemplateLiteral::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/thisExpression.cpp b/ets2panda/ir/expressions/thisExpression.cpp index 3323964b98..269fb8a222 100644 --- a/ets2panda/ir/expressions/thisExpression.cpp +++ b/ets2panda/ir/expressions/thisExpression.cpp @@ -61,6 +61,7 @@ checker::VerifiedType ThisExpression::Check(checker::ETSChecker *checker) ThisExpression *ThisExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/unaryExpression.cpp b/ets2panda/ir/expressions/unaryExpression.cpp index 8cdaa4bdf7..805c807125 100644 --- a/ets2panda/ir/expressions/unaryExpression.cpp +++ b/ets2panda/ir/expressions/unaryExpression.cpp @@ -80,6 +80,7 @@ UnaryExpression *UnaryExpression::Clone(ArenaAllocator *const allocator, AstNode argument->SetParent(clone); } + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/updateExpression.cpp b/ets2panda/ir/expressions/updateExpression.cpp index f594e7fc09..cc8896f4a8 100644 --- a/ets2panda/ir/expressions/updateExpression.cpp +++ b/ets2panda/ir/expressions/updateExpression.cpp @@ -82,6 +82,7 @@ UpdateExpression *UpdateExpression::Clone(ArenaAllocator *const allocator, AstNo argument->SetParent(clone); } + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/expressions/yieldExpression.cpp b/ets2panda/ir/expressions/yieldExpression.cpp index a64f33df86..e4cc631224 100644 --- a/ets2panda/ir/expressions/yieldExpression.cpp +++ b/ets2panda/ir/expressions/yieldExpression.cpp @@ -76,7 +76,7 @@ YieldExpression *YieldExpression::Clone(ArenaAllocator *const allocator, AstNode if (argument != nullptr) { argument->SetParent(clone); } - + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/ts/tsArrayType.cpp b/ets2panda/ir/ts/tsArrayType.cpp index 8a1e1abd2c..df02231c45 100644 --- a/ets2panda/ir/ts/tsArrayType.cpp +++ b/ets2panda/ir/ts/tsArrayType.cpp @@ -105,6 +105,7 @@ TSArrayType *TSArrayType::Clone(ArenaAllocator *const allocator, AstNode *const { auto *const elementTypeClone = elementType_ != nullptr ? elementType_->Clone(allocator, nullptr) : nullptr; auto *const clone = allocator->New(elementTypeClone, allocator); + ES2PANDA_ASSERT(clone != nullptr); clone->AddModifier(flags_); diff --git a/ets2panda/ir/ts/tsAsExpression.cpp b/ets2panda/ir/ts/tsAsExpression.cpp index 8452359ba2..90f1c4efca 100644 --- a/ets2panda/ir/ts/tsAsExpression.cpp +++ b/ets2panda/ir/ts/tsAsExpression.cpp @@ -99,6 +99,7 @@ TSAsExpression *TSAsExpression::Clone(ArenaAllocator *const allocator, AstNode * } auto *const clone = allocator->New(expression, typeAnnotation, isConst_); + ES2PANDA_ASSERT(clone != nullptr); if (expression != nullptr) { expression->SetParent(clone); diff --git a/ets2panda/ir/ts/tsQualifiedName.cpp b/ets2panda/ir/ts/tsQualifiedName.cpp index d71f7db781..f47595f293 100644 --- a/ets2panda/ir/ts/tsQualifiedName.cpp +++ b/ets2panda/ir/ts/tsQualifiedName.cpp @@ -134,6 +134,7 @@ const ir::TSQualifiedName *TSQualifiedName::ResolveLeftMostQualifiedName() const TSQualifiedName *TSQualifiedName::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/ts/tsThisType.cpp b/ets2panda/ir/ts/tsThisType.cpp index da5e36ad8c..fcc43a3102 100644 --- a/ets2panda/ir/ts/tsThisType.cpp +++ b/ets2panda/ir/ts/tsThisType.cpp @@ -89,6 +89,7 @@ TSThisType *TSThisType::Clone(ArenaAllocator *const allocator, AstNode *const pa if (!Annotations().empty()) { ArenaVector annotationUsages {allocator->Adapter()}; for (auto *annotationUsage : Annotations()) { + ES2PANDA_ASSERT(annotationUsage->Clone(allocator, clone) != nullptr); annotationUsages.push_back(annotationUsage->Clone(allocator, clone)->AsAnnotationUsage()); } clone->SetAnnotations(std::move(annotationUsages)); diff --git a/ets2panda/ir/ts/tsTupleType.cpp b/ets2panda/ir/ts/tsTupleType.cpp index cb69e8542c..c6f8052957 100644 --- a/ets2panda/ir/ts/tsTupleType.cpp +++ b/ets2panda/ir/ts/tsTupleType.cpp @@ -91,6 +91,12 @@ checker::Type *GetNumberIndexType(ArenaVector numberIndexTypes, return numberIndexType; } +static void SetMemberVarType(checker::Type *memberType, varbinder::LocalVariable *memberVar) +{ + memberType->SetVariable(memberVar); + memberVar->SetTsType(memberType); +} + checker::Type *TSTupleType::GetType(checker::TSChecker *checker) { if (TsType() != nullptr) { @@ -98,6 +104,7 @@ checker::Type *TSTupleType::GetType(checker::TSChecker *checker) } checker::ObjectDescriptor *desc = checker->Allocator()->New(checker->Allocator()); + ES2PANDA_ASSERT(desc != nullptr); checker::NamedTupleMemberPool namedMembers(checker->Allocator()->Adapter()); ArenaVector elementFlags(checker->Allocator()->Adapter()); checker::ElementFlags combinedFlags = checker::ElementFlags::NO_OPTS; @@ -123,14 +130,12 @@ checker::Type *TSTupleType::GetType(checker::TSChecker *checker) minLength++; } - memberType->SetVariable(memberVar); - memberVar->SetTsType(memberType); + SetMemberVarType(memberType, memberVar); numberIndexTypes.push_back(memberType); namedMembers.insert({memberVar, namedMember->Label()->AsIdentifier()->Name()}); } else { checker::Type *memberType = it->GetType(checker); - memberType->SetVariable(memberVar); - memberVar->SetTsType(memberType); + SetMemberVarType(memberType, memberVar); memberFlag = checker::ElementFlags::REQUIRED; numberIndexTypes.push_back(memberType); minLength++; diff --git a/ets2panda/ir/ts/tsTypeLiteral.cpp b/ets2panda/ir/ts/tsTypeLiteral.cpp index 418d5aa34d..b22b22a4d1 100644 --- a/ets2panda/ir/ts/tsTypeLiteral.cpp +++ b/ets2panda/ir/ts/tsTypeLiteral.cpp @@ -89,6 +89,7 @@ checker::Type *TSTypeLiteral::GetType(checker::TSChecker *checker) checker::ObjectDescriptor *desc = checker->Allocator()->New(checker->Allocator()); checker::Type *type = checker->Allocator()->New(desc); + ES2PANDA_ASSERT(type != nullptr); type->SetVariable(Variable()); SetTsType(type); diff --git a/ets2panda/ir/ts/tsTypeParameterDeclaration.h b/ets2panda/ir/ts/tsTypeParameterDeclaration.h index 9fef5c44ff..da5f9c8861 100644 --- a/ets2panda/ir/ts/tsTypeParameterDeclaration.h +++ b/ets2panda/ir/ts/tsTypeParameterDeclaration.h @@ -58,6 +58,7 @@ public: void AddParam(TSTypeParameter *param) { + ES2PANDA_ASSERT(param != nullptr); if (requiredParams_ == params_.size() && param->DefaultType() == nullptr) { requiredParams_++; } diff --git a/ets2panda/ir/typeNode.cpp b/ets2panda/ir/typeNode.cpp index 233b4ff768..f45f76c13c 100644 --- a/ets2panda/ir/typeNode.cpp +++ b/ets2panda/ir/typeNode.cpp @@ -22,6 +22,7 @@ TypeNode *TypeNode::Clone(ArenaAllocator *const allocator, AstNode *const parent { if (auto *const type = TsType(); type != nullptr) { auto *const clone = allocator->New(type, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } -- Gitee From 2831dff60d002a88c1cdaea872a670a0c7c74271 Mon Sep 17 00:00:00 2001 From: Ilya Trubachev Date: Fri, 4 Jul 2025 14:15:38 +0300 Subject: [PATCH 075/145] Fix codecheck Signed-off-by: Ilya Trubachev Issue: https://gitee.com/openharmony/arkcompiler_runtime_core/issues/ICK479 --- ets2panda/util/arktsconfig.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ets2panda/util/arktsconfig.cpp b/ets2panda/util/arktsconfig.cpp index d58d6220f2..557c238a34 100644 --- a/ets2panda/util/arktsconfig.cpp +++ b/ets2panda/util/arktsconfig.cpp @@ -341,6 +341,7 @@ std::optional ArkTsConfig::ReadConfig(const std::string &path) static std::string ValueOrEmptyString(const JsonObject::JsonObjPointer *json, const std::string &key) { + ES2PANDA_ASSERT(json != nullptr); auto res = json->get()->GetValue(key); return (res != nullptr) ? *res : ""; } @@ -384,7 +385,9 @@ bool ArkTsConfig::ParseCompilerOptions(std::string &arktsConfigDir, std::unorder // Parse "useUrl" if (compilerOptions->get()->HasKey(USE_EMPTY_PACKAGE)) { - useUrl_ = *(compilerOptions->get()->GetValue(USE_EMPTY_PACKAGE)); + auto *useUrl = compilerOptions->get()->GetValue(USE_EMPTY_PACKAGE); + ES2PANDA_ASSERT(useUrl != nullptr); + useUrl_ = *useUrl; } // Parse "dependencies" -- Gitee From 1357767a7bc4641bb161518437d06829000507fd Mon Sep 17 00:00:00 2001 From: zmw Date: Tue, 1 Jul 2025 15:33:29 +0800 Subject: [PATCH 076/145] Fix arrow function in record Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJ5LZ Description: Fix arrow function call in record property as key assert fail Signed-off-by: zmw --- ets2panda/checker/ets/helpers.cpp | 4 ++ .../compiler/lowering/ets/recordLowering.cpp | 6 +-- ...w_function_call_as_record_property_key.ets | 52 +++++++++++++++++++ 3 files changed, 57 insertions(+), 5 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/arrow_function_call_as_record_property_key.ets diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index b3ac490f1a..b7795fd503 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -1765,6 +1765,10 @@ Type *ETSChecker::GetReferencedTypeBase(ir::Expression *name) } ES2PANDA_ASSERT(name->IsIdentifier()); + if (name->AsIdentifier()->Variable() == nullptr) { + // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) + VarBinder()->AsETSBinder()->LookupTypeReference(name->AsIdentifier(), false); + } auto *const var = name->AsIdentifier()->Variable(); ES2PANDA_ASSERT(var != nullptr); diff --git a/ets2panda/compiler/lowering/ets/recordLowering.cpp b/ets2panda/compiler/lowering/ets/recordLowering.cpp index 5522c4a3f6..67d23e6f90 100644 --- a/ets2panda/compiler/lowering/ets/recordLowering.cpp +++ b/ets2panda/compiler/lowering/ets/recordLowering.cpp @@ -103,12 +103,8 @@ void RecordLowering::CheckDuplicateKey(KeySetType &keySet, ir::ObjectExpression ctx->checker->AsETSChecker()->LogError(diagnostic::OBJ_LIT_PROP_NAME_COLLISION, {}, expr->Start()); break; } - case ir::AstNodeType::IDENTIFIER: { - ctx->checker->AsETSChecker()->LogError(diagnostic::OBJ_LIT_UNKNOWN_PROP, {}, expr->Start()); - break; - } default: { - ES2PANDA_UNREACHABLE(); + ctx->checker->AsETSChecker()->LogError(diagnostic::OBJ_LIT_UNKNOWN_PROP, {}, expr->Start()); break; } } diff --git a/ets2panda/test/ast/compiler/ets/arrow_function_call_as_record_property_key.ets b/ets2panda/test/ast/compiler/ets/arrow_function_call_as_record_property_key.ets new file mode 100644 index 0000000000..041edd9bf5 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/arrow_function_call_as_record_property_key.ets @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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: Record = { + [((): number => 2)()]: '1' +} + +const b: Record number> = { + [(():number => +("foo"))()]: function (y: string): number { + return y.length; + }, + [(():number => +("bar"))()]: (y: string):number => y.length +}; + +/* @@? 21:21 Error TypeError: Bad operand type, the type of the operand must be numeric type. */ +/* @@? 21:34 Error SyntaxError: Unexpected token 'function'. */ +/* @@? 21:45 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 21:45 Error SyntaxError: Unexpected token. */ +/* @@? 21:47 Error TypeError: Type 'String' is not compatible with type 'Double' at index 1 */ +/* @@? 21:47 Error TypeError: Type name 'string' used in the wrong context */ +/* @@? 21:53 Error SyntaxError: Unexpected token, expected ':'. */ +/* @@? 21:54 Error SyntaxError: Unexpected token ':'. */ +/* @@? 21:56 Error SyntaxError: Unexpected token. */ +/* @@? 22:9 Error SyntaxError: return keyword should be used in function body. */ +/* @@? 22:16 Error TypeError: All return statements in the function should be empty or have a value. */ +/* @@? 22:16 Error TypeError: Unresolved reference y */ +/* @@? 23:5 Error SyntaxError: Unexpected token '}'. */ +/* @@? 23:6 Error SyntaxError: Unexpected token ','. */ +/* @@? 23:6 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 24:32 Error SyntaxError: Unexpected token ':'. */ +/* @@? 24:36 Error SyntaxError: Unexpected token ':'. */ +/* @@? 24:36 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 24:36 Error SyntaxError: Unexpected token ':'. */ +/* @@? 24:38 Error SyntaxError: Unexpected token 'string'. */ +/* @@? 24:38 Error TypeError: Type name 'string' used in the wrong context */ +/* @@? 24:44 Error SyntaxError: Unexpected token ')'. */ +/* @@? 24:45 Error SyntaxError: Unexpected token ':'. */ +/* @@? 24:46 Error SyntaxError: Unexpected token 'number'. */ +/* @@? 24:46 Error TypeError: The type of parameter 'number' cannot be inferred */ +/* @@? 25:1 Error SyntaxError: Unexpected token '}'. */ -- Gitee From e86dd53b6119fcfc468e930d85c72916d89d1125 Mon Sep 17 00:00:00 2001 From: nikozer Date: Mon, 30 Jun 2025 22:13:31 +0300 Subject: [PATCH 077/145] codecheck fixes Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIYVI Test: ninja tests Signed-off-by: nikozer --- .../lowering/ets/localClassLowering.cpp | 3 +++ .../lowering/ets/objectIndexAccess.cpp | 1 + .../compiler/lowering/ets/objectIterator.cpp | 2 ++ .../lowering/ets/objectLiteralLowering.cpp | 25 ++++++++++++------- .../compiler/lowering/ets/opAssignment.cpp | 2 +- .../ets/optionalArgumentsLowering.cpp | 1 + .../lowering/ets/optionalLowering.cpp | 1 + .../compiler/lowering/ets/recordLowering.cpp | 1 + .../lowering/ets/resizableArrayLowering.cpp | 1 + .../lowering/ets/restArgsLowering.cpp | 5 +++- .../lowering/ets/restTupleLowering.cpp | 4 +++ .../compiler/lowering/ets/spreadLowering.cpp | 7 +++++- .../lowering/ets/stringComparison.cpp | 1 + .../lowering/ets/stringConstantsLowering.cpp | 1 + .../ets/stringConstructorLowering.cpp | 1 + .../ets/topLevelStmts/globalClassHandler.cpp | 13 +++++++--- .../topLevelStmts/globalDeclTransformer.cpp | 3 +++ .../ets/topLevelStmts/importExportDecls.cpp | 1 + .../ets/topLevelStmts/importExportDecls.h | 2 +- .../compiler/lowering/ets/unionLowering.cpp | 8 ++++-- ets2panda/ir/statements/annotationUsage.cpp | 2 ++ ets2panda/ir/statements/blockStatement.cpp | 1 + ets2panda/ir/statements/breakStatement.cpp | 1 + ets2panda/ir/statements/continueStatement.cpp | 1 + ets2panda/ir/statements/forOfStatement.cpp | 1 + ets2panda/ir/statements/tryStatement.cpp | 17 +++++++++++-- .../ir/statements/variableDeclaration.cpp | 5 +++- .../ir/statements/variableDeclarator.cpp | 1 + ets2panda/parser/TSparser.cpp | 3 +++ ets2panda/parser/TypedParser.cpp | 19 +++++++++++--- ets2panda/parser/expressionParser.cpp | 1 + ets2panda/varbinder/scope.h | 4 ++- ets2panda/varbinder/varbinder.cpp | 9 ++++--- ets2panda/varbinder/variable.cpp | 5 ++-- 34 files changed, 123 insertions(+), 30 deletions(-) diff --git a/ets2panda/compiler/lowering/ets/localClassLowering.cpp b/ets2panda/compiler/lowering/ets/localClassLowering.cpp index 4de051d1ea..c5bc5fd80b 100644 --- a/ets2panda/compiler/lowering/ets/localClassLowering.cpp +++ b/ets2panda/compiler/lowering/ets/localClassLowering.cpp @@ -52,6 +52,7 @@ static ir::ClassProperty *CreateCapturedField(public_lib::Context *ctx, const va var->SetTsType(capturedVar->TsType()); fieldIdent->SetVariable(var); + ES2PANDA_ASSERT(field != nullptr); field->SetTsType(capturedVar->TsType()); decl->BindNode(field); return field; @@ -91,6 +92,7 @@ void LocalClassConstructionPhase::CreateClassPropertiesForCapturedVariables( LOG(DEBUG, ES2PANDA) << " - Creating property (" << property->Id()->Name() << ") for captured variable: " << var->Name(); properties.push_back(property); + ES2PANDA_ASSERT(property->Id() != nullptr); variableMap[var] = property->Id()->Variable(); propertyMap[var] = property; idx++; @@ -199,6 +201,7 @@ void LocalClassConstructionPhase::RemapReferencesFromCapturedVariablesToClassPro if (it->IsMethodDefinition() && !it->AsMethodDefinition()->IsConstructor()) { LOG(DEBUG, ES2PANDA) << " - Rebinding variable rerferences in: " << it->AsMethodDefinition()->Id()->Name().Mutf8().c_str(); + ES2PANDA_ASSERT(it->AsMethodDefinition()->Function() != nullptr); if (it->AsMethodDefinition()->Function()->Body() == nullptr && it->AsMethodDefinition()->AsyncPairMethod() != nullptr) { it->AsMethodDefinition()->AsyncPairMethod()->Function()->Body()->IterateRecursively( diff --git a/ets2panda/compiler/lowering/ets/objectIndexAccess.cpp b/ets2panda/compiler/lowering/ets/objectIndexAccess.cpp index deefde6145..73717301b7 100644 --- a/ets2panda/compiler/lowering/ets/objectIndexAccess.cpp +++ b/ets2panda/compiler/lowering/ets/objectIndexAccess.cpp @@ -71,6 +71,7 @@ ir::Expression *ObjectIndexLowering::ProcessIndexSetAccess(parser::ETSParser *pa memberExpression->Property(), assignmentExpression->Right()); setter = loweringResult; } + ES2PANDA_ASSERT(loweringResult != nullptr); loweringResult->SetParent(assignmentExpression->Parent()); loweringResult->SetRange(assignmentExpression->Range()); loweringResult->SetBoxingUnboxingFlags(assignmentExpression->GetBoxingUnboxingFlags()); diff --git a/ets2panda/compiler/lowering/ets/objectIterator.cpp b/ets2panda/compiler/lowering/ets/objectIterator.cpp index cf43ac31d1..1901de4988 100644 --- a/ets2panda/compiler/lowering/ets/objectIterator.cpp +++ b/ets2panda/compiler/lowering/ets/objectIterator.cpp @@ -108,6 +108,7 @@ static ir::OpaqueTypeNode *FindIterValueType(checker::ETSObjectType *type, Arena checker::PropertySearchFlags::SEARCH_INSTANCE_METHOD | checker::PropertySearchFlags::SEARCH_IN_INTERFACES | checker::PropertySearchFlags::SEARCH_IN_BASE); + ES2PANDA_ASSERT(itor != nullptr); auto const &sigs = itor->TsType()->AsETSFunctionType()->CallSignatures(); checker::ETSObjectType *itorReturnType = nullptr; for (auto &sig : sigs) { @@ -170,6 +171,7 @@ ir::Statement *ObjectIteratorLowering::ProcessObjectIterator(public_lib::Context auto *const loweringResult = parser->CreateFormattedStatement( whileStatement, iterIdent, forOfStatement->Right(), nextIdent, iterIdent->Clone(allocator, nullptr), nextIdent->Clone(allocator, nullptr), loopVariableIdent, nextIdent->Clone(allocator, nullptr), typeNode); + ES2PANDA_ASSERT(loweringResult != nullptr); loweringResult->SetParent(forOfStatement->Parent()); loweringResult->SetRange(forOfStatement->Range()); diff --git a/ets2panda/compiler/lowering/ets/objectLiteralLowering.cpp b/ets2panda/compiler/lowering/ets/objectLiteralLowering.cpp index bcc71b964c..96f8c83ca9 100644 --- a/ets2panda/compiler/lowering/ets/objectLiteralLowering.cpp +++ b/ets2panda/compiler/lowering/ets/objectLiteralLowering.cpp @@ -100,6 +100,7 @@ static void AllowRequiredTypeInstantiation(const ir::Expression *const loweringR static bool CheckReadonlyAndUpdateCtorArgs(const ir::Identifier *key, ir::Expression *value, std::map &ctorArgumentsMap) { + ES2PANDA_ASSERT(key != nullptr); auto varType = (key->Variable() != nullptr) ? key->Variable()->TsType() : nullptr; if (varType == nullptr || varType->HasTypeFlag(checker::TypeFlag::SETTER)) { return false; @@ -162,6 +163,18 @@ static void SetInstanceArguments(ArenaVector &statements, Arena instance->SetArguments(std::move(ctorArguments)); } +static void GenerateArgsForAnonymousClassType(const checker::ETSObjectType *classType, const bool &isAnonymous, + std::map &ctorArgumentsMap) +{ + if (isAnonymous) { + checker::Signature *sig = classType->ConstructSignatures().front(); + for (auto param : sig->Params()) { + ES2PANDA_ASSERT(param->Declaration() != nullptr); + ctorArgumentsMap.emplace(param->Declaration()->Name(), nullptr); + } + } +} + static void GenerateNewStatements(public_lib::Context *ctx, ir::ObjectExpression *objExpr, std::stringstream &ss, std::vector &newStmts, std::deque &nestedBlckExprs, @@ -186,13 +199,7 @@ static void GenerateNewStatements(public_lib::Context *ctx, ir::ObjectExpression bool isAnonymous = IsAnonymousClassType(classType); std::map ctorArgumentsMap; - if (isAnonymous) { - checker::Signature *sig = classType->ConstructSignatures().front(); - for (auto param : sig->Params()) { - ES2PANDA_ASSERT(param->Declaration() != nullptr); - ctorArgumentsMap.emplace(param->Declaration()->Name(), nullptr); - } - } + GenerateArgsForAnonymousClassType(classType, isAnonymous, ctorArgumentsMap); for (auto *propExpr : objExpr->Properties()) { // Skip possibly invalid properties: @@ -218,7 +225,7 @@ static void GenerateNewStatements(public_lib::Context *ctx, ir::ObjectExpression if (isAnonymous && CheckReadonlyAndUpdateCtorArgs(keyIdent, value, ctorArgumentsMap)) { continue; } - + ES2PANDA_ASSERT(genSymIdent != nullptr); ss << "@@I" << addNode(genSymIdent->Clone(allocator, nullptr)) << ".@@I" << addNode(keyIdent); if (value->IsBlockExpression()) { @@ -269,7 +276,7 @@ static ir::AstNode *HandleObjectLiteralLowering(public_lib::Context *ctx, ir::Ob GenerateNewStatements(ctx, objExpr, ss, newStmts, nestedBlckExprs, ctorArguments); auto *loweringResult = parser->CreateFormattedExpression(ss.str(), newStmts); - + ES2PANDA_ASSERT(loweringResult != nullptr); SetInstanceArguments(loweringResult->AsBlockExpression()->Statements(), ctorArguments); loweringResult->SetParent(objExpr->Parent()); diff --git a/ets2panda/compiler/lowering/ets/opAssignment.cpp b/ets2panda/compiler/lowering/ets/opAssignment.cpp index 62e38b69c3..bdffff251f 100644 --- a/ets2panda/compiler/lowering/ets/opAssignment.cpp +++ b/ets2panda/compiler/lowering/ets/opAssignment.cpp @@ -94,7 +94,7 @@ void AdjustBoxingUnboxingFlags(ir::Expression *loweringResult, const ir::Express ir::BoxingUnboxingFlags::BOXING_FLAG}; const ir::BoxingUnboxingFlags oldUnboxingFlag {oldExpr->GetBoxingUnboxingFlags() & ir::BoxingUnboxingFlags::UNBOXING_FLAG}; - + ES2PANDA_ASSERT(exprToProcess != nullptr); if (exprToProcess->TsType()->IsETSPrimitiveType()) { loweringResult->SetBoxingUnboxingFlags(oldBoxingFlag); } else if (exprToProcess->TsType()->IsETSObjectType()) { diff --git a/ets2panda/compiler/lowering/ets/optionalArgumentsLowering.cpp b/ets2panda/compiler/lowering/ets/optionalArgumentsLowering.cpp index 969fabd2d2..469c1ca520 100644 --- a/ets2panda/compiler/lowering/ets/optionalArgumentsLowering.cpp +++ b/ets2panda/compiler/lowering/ets/optionalArgumentsLowering.cpp @@ -58,6 +58,7 @@ static void TransformArguments(public_lib::Context *ctx, ir::Expression *callLik size_t missing = signature->ArgCount() - arguments.size(); for (size_t i = 0; i < missing; ++i) { auto undefArg = allocator->New(); + ES2PANDA_ASSERT(undefArg != nullptr); undefArg->SetTsType(checker->GlobalETSUndefinedType()); arguments.push_back(undefArg); undefArg->SetParent(callLike); diff --git a/ets2panda/compiler/lowering/ets/optionalLowering.cpp b/ets2panda/compiler/lowering/ets/optionalLowering.cpp index 36f6aefe14..73c5b83e85 100644 --- a/ets2panda/compiler/lowering/ets/optionalLowering.cpp +++ b/ets2panda/compiler/lowering/ets/optionalLowering.cpp @@ -39,6 +39,7 @@ static ir::AstNode *LowerOptionalExpr(GetSource const &getSource, SetSource cons auto expressionCtx = varbinder::LexicalScope::Enter(varbinder, NearestScope(expr)); auto *tmpIdent = Gensym(allocator); + ES2PANDA_ASSERT(tmpIdent != nullptr); auto *tmpIdentClone = tmpIdent->Clone(allocator, nullptr); // '0's act as placeholders diff --git a/ets2panda/compiler/lowering/ets/recordLowering.cpp b/ets2panda/compiler/lowering/ets/recordLowering.cpp index 5522c4a3f6..f5e907c1cc 100644 --- a/ets2panda/compiler/lowering/ets/recordLowering.cpp +++ b/ets2panda/compiler/lowering/ets/recordLowering.cpp @@ -189,6 +189,7 @@ ir::Expression *RecordLowering::UpdateObjectExpression(ir::ObjectExpression *exp // Create Block Expression auto block = CreateBlockExpression(expr, typeArguments[0], typeArguments[1], ctx); + ES2PANDA_ASSERT(block != nullptr); block->SetParent(expr->Parent()); // Run checks diff --git a/ets2panda/compiler/lowering/ets/resizableArrayLowering.cpp b/ets2panda/compiler/lowering/ets/resizableArrayLowering.cpp index 12d58293e3..77a38420fb 100644 --- a/ets2panda/compiler/lowering/ets/resizableArrayLowering.cpp +++ b/ets2panda/compiler/lowering/ets/resizableArrayLowering.cpp @@ -27,6 +27,7 @@ static ir::AstNode *ConvertToResizableArrayType(ir::TSArrayType *node, public_li auto *parser = ctx->parser->AsETSParser(); ir::TypeNode *typeAnnotation = parser->CreateFormattedTypeAnnotation("Array<" + node->ElementType()->DumpEtsSrc() + ">"); + ES2PANDA_ASSERT(typeAnnotation != nullptr); typeAnnotation->SetAnnotations(std::move(node->Annotations())); typeAnnotation->SetParent(node->Parent()); typeAnnotation->SetRange(node->Range()); diff --git a/ets2panda/compiler/lowering/ets/restArgsLowering.cpp b/ets2panda/compiler/lowering/ets/restArgsLowering.cpp index 224e980335..e8c8c4efbe 100644 --- a/ets2panda/compiler/lowering/ets/restArgsLowering.cpp +++ b/ets2panda/compiler/lowering/ets/restArgsLowering.cpp @@ -51,6 +51,7 @@ static ir::BlockExpression *CreateRestArgsBlockExpression(public_lib::Context *c args.emplace_back(argumentSymbol->Clone(allocator, nullptr)); ss << "@@I3[@@I4] = @@I5;"; args.emplace_back(arraySymbol->Clone(allocator, nullptr)); + ES2PANDA_ASSERT(iteratorIndex != nullptr); args.emplace_back(iteratorIndex->Clone(allocator, nullptr)); args.emplace_back(iteratorSymbol->Clone(allocator, nullptr)); ss << "@@I6 = @@I7 + 1;"; @@ -69,6 +70,7 @@ static ir::BlockExpression *ConvertSpreadToBlockExpression(public_lib::Context * ir::SpreadElement *spreadElement) { auto *blockExpression = CreateRestArgsBlockExpression(context, spreadElement); + ES2PANDA_ASSERT(blockExpression != nullptr); blockExpression->SetParent(spreadElement->Parent()); blockExpression->SetRange(spreadElement->Range()); @@ -111,6 +113,7 @@ static ir::Expression *CreateRestArgsArray(public_lib::Context *context, ArenaVe ss << "let @@I1 : FixedArray<@@T2> = @@E3;"; ss << "Array.from<@@T4>(@@I5);"; auto *arrayExpr = checker->AllocNode(std::move(copiedArguments), allocator); + ES2PANDA_ASSERT(type != nullptr); auto *loweringResult = parser->CreateFormattedExpression(ss.str(), genSymIdent, type, arrayExpr, type->Clone(allocator, nullptr), genSymIdent->Clone(allocator, nullptr)); @@ -133,7 +136,7 @@ static ir::CallExpression *RebuildCallExpression(public_lib::Context *context, i auto *newCall = util::NodeAllocator::ForceSetParent(allocator, originalCall->Callee(), std::move(newArgs), nullptr, false); - + ES2PANDA_ASSERT(newCall != nullptr); restArgsArray->SetParent(newCall); newCall->SetParent(originalCall->Parent()); newCall->AddModifier(originalCall->Modifiers()); diff --git a/ets2panda/compiler/lowering/ets/restTupleLowering.cpp b/ets2panda/compiler/lowering/ets/restTupleLowering.cpp index 7e9724a1bf..81d5a02c3f 100644 --- a/ets2panda/compiler/lowering/ets/restTupleLowering.cpp +++ b/ets2panda/compiler/lowering/ets/restTupleLowering.cpp @@ -209,6 +209,7 @@ ir::ArrayExpression *CreateArrayExpression(public_lib::Context *ctx, const Arena ArenaVector elements(ctx->Allocator()->Adapter()); auto *arrayExpr = ctx->AllocNode(std::move(elementsInit), ctx->Allocator()); + ES2PANDA_ASSERT(arrayExpr != nullptr); for (auto tupleElementAnno : newRestParams) { auto &tupleElementName = tupleElementAnno->AsETSParameterExpression()->Ident()->AsIdentifier()->Name(); ir::Expression *arg = ctx->AllocNode(tupleElementName, allocator); @@ -262,6 +263,7 @@ ir::ScriptFunction *CreateNewScriptFunction(public_lib::Context *ctx, ir::Script allocator, ir::ScriptFunction::ScriptFunctionData { body, ir::FunctionSignature(newParamDeclaration, std::move(newParams), newReturnTypeAnno), scriptFunc->Flags()}); + ES2PANDA_ASSERT(newScriptFunc != nullptr); newScriptFunc->AddModifier(scriptFunc->AsScriptFunction()->Modifiers()); ArenaVector annotationUsages {allocator->Adapter()}; @@ -284,6 +286,7 @@ ir::VariableDeclaration *CreateNewVariableDeclaration(public_lib::Context *ctx, util::StringView tupleIdentName = restParam->Ident()->Name(); auto *newId = ctx->AllocNode(tupleIdentName, allocator); + ES2PANDA_ASSERT(newId != nullptr); ir::TypeNode *typeAnnotation = restParam->TypeAnnotation()->Clone(allocator, newId); newId->SetTsTypeAnnotation(typeAnnotation); newTuple->SetParent(typeAnnotation); @@ -322,6 +325,7 @@ ir::MethodDefinition *CreateNewMethodDefinition(public_lib::Context *ctx, ir::Me auto *const methodDef = ctx->AllocNode(definition->AsMethodDefinition()->Kind(), methodKey, function, definition->AsMethodDefinition()->Modifiers(), allocator, false); + ES2PANDA_ASSERT(methodDef != nullptr); methodDef->SetParent(definition->Parent()); return methodDef; diff --git a/ets2panda/compiler/lowering/ets/spreadLowering.cpp b/ets2panda/compiler/lowering/ets/spreadLowering.cpp index 1c2f4241cf..6d3dbb95ef 100644 --- a/ets2panda/compiler/lowering/ets/spreadLowering.cpp +++ b/ets2panda/compiler/lowering/ets/spreadLowering.cpp @@ -58,6 +58,7 @@ ir::Identifier *CreateNewArrayLengthStatement(public_lib::Context *ctx, ir::Arra auto *const allocator = ctx->allocator; auto *const parser = ctx->parser->AsETSParser(); ir::Identifier *newArrayLengthId = Gensym(allocator); + ES2PANDA_ASSERT(newArrayLengthId != nullptr); std::vector nodesWaitingInsert {newArrayLengthId->Clone(allocator, nullptr)}; size_t argumentCount = 1; std::stringstream lengthString; @@ -107,6 +108,7 @@ static ir::Identifier *CreateNewArrayDeclareStatement(public_lib::Context *ctx, newArrayDeclareStr << "let @@I1: FixedArray<@@T2> = new (@@T3)[@@I4];" << std::endl; } + ES2PANDA_ASSERT(newArrayLengthId != nullptr); ir::Statement *newArrayDeclareSt = parser->CreateFormattedStatement( newArrayDeclareStr.str(), newArrayId->Clone(allocator, nullptr), arrayElementType, arrayElementType, newArrayLengthId->Clone(allocator, nullptr)); @@ -166,6 +168,7 @@ static ir::Identifier *CreateNewTupleDeclareStatement(public_lib::Context *ctx, auto *const allocator = ctx->allocator; auto *const parser = ctx->parser->AsETSParser(); ir::Identifier *newTupleId = Gensym(allocator); + ES2PANDA_ASSERT(newTupleId != nullptr); checker::ETSTupleType *tupleType = array->TsType()->AsETSTupleType(); std::stringstream newArrayDeclareStr; @@ -196,6 +199,7 @@ static ir::Statement *CreateElementsAssignStatementBySpreadArr(public_lib::Conte elementsAssignStr << "@@I7++;"; elementsAssignStr << "}"; + ES2PANDA_ASSERT(spreadArrIterator != nullptr); ir::Statement *elementsAssignStatement = parser->CreateFormattedStatement( elementsAssignStr.str(), spreadArrIterator->Clone(allocator, nullptr), spId->Clone(allocator, nullptr), newArrayId->Clone(allocator, nullptr), newArrayIndexId->Clone(allocator, nullptr), @@ -327,6 +331,7 @@ static ir::BlockExpression *CreateLoweredExpressionForArray(public_lib::Context ir::Identifier *newArrayLengthId = CreateNewArrayLengthStatement(ctx, array, spreadArrayIds, statements); ir::Identifier *newArrayId = CreateNewArrayDeclareStatement(ctx, array, statements, newArrayLengthId); + ES2PANDA_ASSERT(newArrayId != nullptr); ir::Identifier *newArrayIndexId = Gensym(allocator); statements.emplace_back( parser->CreateFormattedStatement("let @@I1 = 0", newArrayIndexId->Clone(allocator, nullptr))); @@ -349,7 +354,7 @@ static ir::BlockExpression *CreateLoweredExpressionForTuple(public_lib::Context ArenaVector statements(allocator->Adapter()); ir::Identifier *newTupleId = CreateNewTupleDeclareStatement(ctx, array, statements); - + ES2PANDA_ASSERT(newTupleId != nullptr); statements.emplace_back(parser->CreateFormattedStatement("@@I1;", newTupleId->Clone(allocator, nullptr))); return checker->AllocNode(std::move(statements)); } diff --git a/ets2panda/compiler/lowering/ets/stringComparison.cpp b/ets2panda/compiler/lowering/ets/stringComparison.cpp index e7f0cb4f16..79feda59eb 100644 --- a/ets2panda/compiler/lowering/ets/stringComparison.cpp +++ b/ets2panda/compiler/lowering/ets/stringComparison.cpp @@ -83,6 +83,7 @@ void StringComparisonLowering::ProcessBinaryExpression(ir::BinaryExpression *exp ir::Expression *accessor = nullptr; auto *zeroExpr = checker->AllocNode(util::StringView("0")); auto *const callee = checker->AllocNode("compareTo", checker->Allocator()); + ES2PANDA_ASSERT(callee != nullptr); auto *var = checker->GlobalBuiltinETSStringType()->GetProperty(callee->AsIdentifier()->Name(), checker::PropertySearchFlags::SEARCH_METHOD); callee->SetVariable(var); diff --git a/ets2panda/compiler/lowering/ets/stringConstantsLowering.cpp b/ets2panda/compiler/lowering/ets/stringConstantsLowering.cpp index e2bae0b0e6..dd07eacc1e 100644 --- a/ets2panda/compiler/lowering/ets/stringConstantsLowering.cpp +++ b/ets2panda/compiler/lowering/ets/stringConstantsLowering.cpp @@ -30,6 +30,7 @@ static ir::AstNode *FoldConcat(public_lib::Context *ctx, ir::BinaryExpression *c auto const resStr = util::UString(lhs->Str().Mutf8() + rhs->Str().Mutf8(), ctx->allocator).View(); auto resNode = util::NodeAllocator::Alloc(ctx->allocator, resStr); + ES2PANDA_ASSERT(resNode != nullptr); resNode->SetParent(concat->Parent()); resNode->SetRange({lhs->Range().start, rhs->Range().end}); return resNode; diff --git a/ets2panda/compiler/lowering/ets/stringConstructorLowering.cpp b/ets2panda/compiler/lowering/ets/stringConstructorLowering.cpp index 1e4060b5ea..cf9c082392 100644 --- a/ets2panda/compiler/lowering/ets/stringConstructorLowering.cpp +++ b/ets2panda/compiler/lowering/ets/stringConstructorLowering.cpp @@ -72,6 +72,7 @@ ir::Expression *ReplaceStringConstructor(public_lib::Context *const ctx, if (argType->IsETSNullType() || argType->IsETSUndefinedType()) { auto *literal = argType->IsETSNullType() ? ctx->AllocNode("null") : ctx->AllocNode("undefined"); + ES2PANDA_ASSERT(literal != nullptr); literal->SetParent(newClassInstExpr->Parent()); // Run checker diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp index 13dd763e3b..863d82798f 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp @@ -86,6 +86,7 @@ ir::ClassDeclaration *GlobalClassHandler::CreateTransformedClass(ir::ETSModule * auto *classDef = NodeAllocator::Alloc( allocator_, allocator_, ident, ir::ClassDefinitionModifiers::CLASS_DECL, ir::ModifierFlags::ABSTRACT, Language(Language::Id::ETS)); + ES2PANDA_ASSERT(classDef != nullptr); classDef->SetRange(ns->Range()); classDef->AddModifier(ns->Modifiers()); auto *classDecl = NodeAllocator::Alloc(allocator_, classDef, allocator_); @@ -103,6 +104,7 @@ ir::ClassDeclaration *GlobalClassHandler::CreateTransformedClass(ir::ETSModule * static void InsertInGlobal(ir::ClassDefinition *globalClass, ir::AstNode *node) { + ES2PANDA_ASSERT(node != nullptr); globalClass->Body().insert(globalClass->Body().begin(), node); node->SetParent(globalClass); } @@ -145,6 +147,7 @@ void GlobalClassHandler::SetupGlobalMethods(parser::Program *program, ArenaVecto ir::MethodDefinition *initMethod = CreateGlobalMethod(compiler::Signatures::INIT_METHOD, std::move(initStatements), program); InsertInGlobal(globalClass, initMethod); + ES2PANDA_ASSERT(initMethod->Function()); if (!initMethod->Function()->Body()->AsBlockStatement()->Statements().empty()) { AddInitCallToStaticBlock(globalClass, initMethod); } @@ -209,6 +212,7 @@ void GlobalClassHandler::TransformBrokenNamespace(ir::AstNode *node, parser::Pro ir::ClassDeclaration *GlobalClassHandler::TransformNamespace(ir::ETSModule *ns, parser::Program *program) { ir::ClassDeclaration *const globalDecl = CreateTransformedClass(ns); + ES2PANDA_ASSERT(globalDecl != nullptr); ir::ClassDefinition *const globalClass = globalDecl->Definition(); ArenaVector immediateInitializers(allocator_->Adapter()); @@ -294,6 +298,7 @@ void GlobalClassHandler::SetupGlobalClass(const ArenaVector & ArenaUnorderedSet packageInitializerBlockCount(allocator_->Adapter()); ir::ClassDeclaration *const globalDecl = CreateGlobalClass(globalProgram); + ES2PANDA_ASSERT(globalDecl != nullptr); ir::ClassDefinition *const globalClass = globalDecl->Definition(); // NOTE(vpukhov): a clash inside program list is possible @@ -357,7 +362,7 @@ ir::MethodDefinition *GlobalClassHandler::CreateGlobalMethod(std::string_view na allocator_, allocator_, ir::ScriptFunction::ScriptFunctionData { body, std::move(funcSignature), functionFlags, {}, Language(Language::Id::ETS)}); - + ES2PANDA_ASSERT(func != nullptr); func->SetIdent(ident); func->AddModifier(functionModifiers); @@ -380,7 +385,7 @@ void GlobalClassHandler::AddInitializerBlockToStaticBlock(ir::ClassDefinition *g auto *staticBlock = (*maybeStaticBlock)->AsClassStaticBlock(); auto *initializerStmts = NodeAllocator::ForceSetParent(allocator_, allocator_, std::move(initializerBlocks)); - + ES2PANDA_ASSERT(initializerStmts != nullptr); auto *blockBody = staticBlock->Function()->Body()->AsBlockStatement(); initializerStmts->SetParent(blockBody); blockBody->Statements().emplace_back(initializerStmts); @@ -396,6 +401,7 @@ void GlobalClassHandler::AddInitCallToStaticBlock(ir::ClassDefinition *globalCla ES2PANDA_ASSERT(maybeStaticBlock != globalBody.end()); auto *staticBlock = (*maybeStaticBlock)->AsClassStaticBlock(); + ES2PANDA_ASSERT(initMethod->Id() != nullptr); auto *callee = RefIdent(initMethod->Id()->Name()); auto *const callExpr = NodeAllocator::Alloc( @@ -483,7 +489,7 @@ ir::ClassStaticBlock *GlobalClassHandler::CreateStaticBlock(ir::ClassDefinition ir::ScriptFunction::ScriptFunctionData {body, ir::FunctionSignature(nullptr, std::move(params), nullptr), ir::ScriptFunctionFlags::STATIC_BLOCK | ir::ScriptFunctionFlags::HIDDEN, ir::ModifierFlags::STATIC, Language(Language::Id::ETS)}); - + ES2PANDA_ASSERT(func != nullptr); func->SetIdent(id); auto *funcExpr = NodeAllocator::Alloc(allocator_, func); @@ -542,6 +548,7 @@ ir::ClassDeclaration *GlobalClassHandler::CreateGlobalClass(const parser::Progra auto *classDef = NodeAllocator::Alloc(allocator_, allocator_, ident, ir::ClassDefinitionModifiers::GLOBAL, ir::ModifierFlags::ABSTRACT, Language(Language::Id::ETS)); + ES2PANDA_ASSERT(classDef != nullptr); classDef->SetRange(rangeToStartOfFile); auto *classDecl = NodeAllocator::Alloc(allocator_, classDef, allocator_); classDecl->SetRange(rangeToStartOfFile); diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalDeclTransformer.cpp b/ets2panda/compiler/lowering/ets/topLevelStmts/globalDeclTransformer.cpp index 8e3afe694c..81b4d87476 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalDeclTransformer.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalDeclTransformer.cpp @@ -39,6 +39,7 @@ GlobalDeclTransformer::ResultT GlobalDeclTransformer::TransformStatements(const void GlobalDeclTransformer::VisitFunctionDeclaration(ir::FunctionDeclaration *funcDecl) { auto *funcExpr = util::NodeAllocator::ForceSetParent(allocator_, funcDecl->Function()); + ES2PANDA_ASSERT(funcExpr != nullptr); funcDecl->Function()->SetStart(funcDecl->Function()->Id()->Start()); funcExpr->SetRange(funcDecl->Function()->Range()); ir::MethodDefinitionKind methodKind; @@ -85,6 +86,7 @@ void GlobalDeclTransformer::VisitVariableDeclaration(ir::VariableDeclaration *va if (!varDecl->Annotations().empty()) { ArenaVector propAnnotations(allocator_->Adapter()); for (auto *annotationUsage : varDecl->Annotations()) { + ES2PANDA_ASSERT(annotationUsage != nullptr); propAnnotations.push_back(annotationUsage->Clone(allocator_, field)->AsAnnotationUsage()); } field->SetAnnotations(std::move(propAnnotations)); @@ -164,6 +166,7 @@ ir::ExpressionStatement *GlobalDeclTransformer::InitTopLevelProperty(ir::ClassPr initializer->SetParent(nullptr); auto *assignmentExpression = util::NodeAllocator::Alloc( allocator_, ident, initializer, lexer::TokenType::PUNCTUATOR_SUBSTITUTION); + ES2PANDA_ASSERT(assignmentExpression != nullptr); assignmentExpression->SetRange({ident->Start(), initializer->End()}); assignmentExpression->SetTsType(initializer->TsType()); diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/importExportDecls.cpp b/ets2panda/compiler/lowering/ets/topLevelStmts/importExportDecls.cpp index aa76dbdc45..adbb17ad0f 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/importExportDecls.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/importExportDecls.cpp @@ -133,6 +133,7 @@ void ImportExportDecls::HandleSelectiveExportWithAlias(util::StringView original !declItem->second->HasExportAlias(); if (!alreadyExported && declItem->second->IsVariableDeclaration()) { auto declarator = declItem->second->AsVariableDeclaration()->GetDeclaratorByName(exportName); + ES2PANDA_ASSERT(declarator != nullptr); alreadyExported |= ((declarator->Modifiers() & ir::ModifierFlags::EXPORTED) != 0) && !declarator->HasExportAlias(); } diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/importExportDecls.h b/ets2panda/compiler/lowering/ets/topLevelStmts/importExportDecls.h index f5b04f3f5b..c1b50a29aa 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/importExportDecls.h +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/importExportDecls.h @@ -151,7 +151,7 @@ private: exportMap.insert({program_->SourceFilePath(), newMap}); } - void RestoreImportExportDecls() + void RestoreImportExportDecls() noexcept { imExDecl_->fieldMap_ = fieldMapPrev_; imExDecl_->exportNameMap_ = exportNameMapPrev_; diff --git a/ets2panda/compiler/lowering/ets/unionLowering.cpp b/ets2panda/compiler/lowering/ets/unionLowering.cpp index 2df65448a0..2a726f8f96 100644 --- a/ets2panda/compiler/lowering/ets/unionLowering.cpp +++ b/ets2panda/compiler/lowering/ets/unionLowering.cpp @@ -62,6 +62,7 @@ static ir::ClassDefinition *GetUnionAccessClass(public_lib::Context *ctx, varbin auto classCtx = varbinder::LexicalScope(varbinder); auto *classDef = ctx->AllocNode(ctx->Allocator(), ident, ir::ClassDefinitionModifiers::GLOBAL, ir::ModifierFlags::ABSTRACT, Language(Language::Id::ETS)); + ES2PANDA_ASSERT(classDef != nullptr); classDef->SetScope(classCtx.GetScope()); auto *classDecl = ctx->AllocNode(classDef, allocator); classDef->Scope()->BindNode(classDecl->Definition()); @@ -103,6 +104,7 @@ static std::tuple CreateNamedA nullptr, ir::FunctionSignature(nullptr, std::move(params), returnTypeAnno), // CC-OFFNXT(G.FMT.02-CPP) project code style ir::ScriptFunctionFlags::METHOD, ir::ModifierFlags::PUBLIC}); + ES2PANDA_ASSERT(func != nullptr); func->SetIdent(methodIdent->Clone(allocator, nullptr)); // Create the synthetic function node @@ -146,7 +148,7 @@ static varbinder::LocalVariable *CreateNamedAccessProperty(public_lib::Context * // Create the synthetic class property node auto *field = ctx->AllocNode(fieldIdent, nullptr, nullptr, ir::ModifierFlags::NONE, allocator, false); - + ES2PANDA_ASSERT(field != nullptr); // Add the declaration to the scope auto [decl, var] = varbinder->NewVarDecl(fieldIdent->Start(), fieldIdent->Name()); var->AddFlag(varbinder::VariableFlags::PROPERTY); @@ -167,7 +169,7 @@ static varbinder::LocalVariable *CreateNamedAccess(public_lib::Context *ctx, var auto type = expr->TsType(); auto name = expr->Property()->AsIdentifier()->Name(); auto *checker = ctx->checker->AsETSChecker(); - + ES2PANDA_ASSERT(checker->GetApparentType(checker->GetNonNullishType(expr->Object()->TsType())) != nullptr); auto unionType = checker->GetApparentType(checker->GetNonNullishType(expr->Object()->TsType()))->AsETSUnionType(); auto *const accessClass = GetUnionAccessClass(ctx, varbinder, GetAccessClassName(unionType)); auto *classScope = accessClass->Scope()->AsClassScope(); @@ -207,6 +209,7 @@ static ir::TSAsExpression *GenAsExpression(public_lib::Context *ctx, checker::Ty { auto *const typeNode = ctx->AllocNode(opaqueType, ctx->Allocator()); auto *const asExpression = ctx->AllocNode(node, typeNode, false); + ES2PANDA_ASSERT(asExpression != nullptr); asExpression->SetParent(parent); asExpression->Check(ctx->checker->AsETSChecker()); return asExpression; @@ -240,6 +243,7 @@ static ir::TSAsExpression *HandleUnionCastToPrimitive(public_lib::Context *ctx, // when sourceType get `object`, it could cast to any primitive type but can't be unboxed; if (maybeUnboxingType != nullptr && expr->TsType()->IsETSPrimitiveType()) { auto *const asExpr = GenAsExpression(ctx, sourceType, expr->Expr(), expr); + ES2PANDA_ASSERT(asExpr != nullptr); asExpr->SetBoxingUnboxingFlags(checker->GetUnboxingFlag(maybeUnboxingType)); expr->Expr()->SetBoxingUnboxingFlags(ir::BoxingUnboxingFlags::NONE); expr->SetExpr(asExpr); diff --git a/ets2panda/ir/statements/annotationUsage.cpp b/ets2panda/ir/statements/annotationUsage.cpp index f45e552769..aee9d75d53 100644 --- a/ets2panda/ir/statements/annotationUsage.cpp +++ b/ets2panda/ir/statements/annotationUsage.cpp @@ -58,6 +58,7 @@ void AnnotationUsage::Dump(ir::SrcDumper *dumper) const if (!properties_.empty()) { dumper->Add("{"); for (auto elem : properties_) { + ES2PANDA_ASSERT(elem->AsClassProperty()->Id() != nullptr); dumper->Add(elem->AsClassProperty()->Id()->Name().Mutf8()); dumper->Add(":"); elem->AsClassProperty()->Value()->Dump(dumper); @@ -74,6 +75,7 @@ AnnotationUsage *AnnotationUsage::Clone(ArenaAllocator *const allocator, AstNode { auto *const expr = expr_ != nullptr ? expr_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(expr, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (expr != nullptr) { expr->SetParent(clone); diff --git a/ets2panda/ir/statements/blockStatement.cpp b/ets2panda/ir/statements/blockStatement.cpp index 63cc1287f0..53ee69d7c5 100644 --- a/ets2panda/ir/statements/blockStatement.cpp +++ b/ets2panda/ir/statements/blockStatement.cpp @@ -46,6 +46,7 @@ AstNode *BlockStatement::Clone(ArenaAllocator *const allocator, AstNode *const p } auto retVal = util::NodeAllocator::ForceSetParent(allocator, allocator, std::move(statements)); + ES2PANDA_ASSERT(retVal != nullptr); retVal->SetParent(parent); return retVal; diff --git a/ets2panda/ir/statements/breakStatement.cpp b/ets2panda/ir/statements/breakStatement.cpp index 3a8b44bde4..afbca163d3 100644 --- a/ets2panda/ir/statements/breakStatement.cpp +++ b/ets2panda/ir/statements/breakStatement.cpp @@ -79,6 +79,7 @@ BreakStatement *BreakStatement::Clone(ArenaAllocator *const allocator, AstNode * { auto *const ident = ident_ != nullptr ? ident_->Clone(allocator, nullptr) : nullptr; auto *const clone = util::NodeAllocator::ForceSetParent(allocator, ident); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); diff --git a/ets2panda/ir/statements/continueStatement.cpp b/ets2panda/ir/statements/continueStatement.cpp index 89bacf1b71..8b73763a7d 100644 --- a/ets2panda/ir/statements/continueStatement.cpp +++ b/ets2panda/ir/statements/continueStatement.cpp @@ -73,6 +73,7 @@ ContinueStatement *ContinueStatement::Clone(ArenaAllocator *const allocator, Ast { auto *const ident = ident_ != nullptr ? ident_->Clone(allocator, nullptr) : nullptr; auto *const clone = util::NodeAllocator::ForceSetParent(allocator, ident); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); diff --git a/ets2panda/ir/statements/forOfStatement.cpp b/ets2panda/ir/statements/forOfStatement.cpp index d6eee195c8..9fff61c950 100644 --- a/ets2panda/ir/statements/forOfStatement.cpp +++ b/ets2panda/ir/statements/forOfStatement.cpp @@ -121,6 +121,7 @@ ForOfStatement *ForOfStatement::Clone(ArenaAllocator *const allocator, AstNode * auto *const right = right_ != nullptr ? right_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const body = body_ != nullptr ? body_->Clone(allocator, nullptr)->AsStatement() : nullptr; auto *const clone = allocator->New(left, right, body, isAwait_); + ES2PANDA_ASSERT(clone != nullptr); if (left != nullptr) { left->SetParent(clone); diff --git a/ets2panda/ir/statements/tryStatement.cpp b/ets2panda/ir/statements/tryStatement.cpp index 7281fa5e60..82d74865c4 100644 --- a/ets2panda/ir/statements/tryStatement.cpp +++ b/ets2panda/ir/statements/tryStatement.cpp @@ -127,9 +127,21 @@ TryStatement::TryStatement(TryStatement const &other, ArenaAllocator *allocator) { block_ = other.block_ == nullptr ? nullptr : other.block_->Clone(allocator, this)->AsBlockStatement(); for (auto &cc : other.catchClauses_) { - catchClauses_.push_back(cc == nullptr ? nullptr : cc->Clone(allocator, this)->AsCatchClause()); + if (cc == nullptr) { + catchClauses_.push_back(nullptr); + continue; + } + auto *ccClone = cc->Clone(allocator, this); + ES2PANDA_ASSERT(ccClone != nullptr); + catchClauses_.push_back(ccClone->AsCatchClause()); + } + if (other.finalizer_ == nullptr) { + finalizer_ = nullptr; + } else { + auto *otherFinalizerClone = other.finalizer_->Clone(allocator, this); + ES2PANDA_ASSERT(otherFinalizerClone != nullptr); + finalizer_ = otherFinalizerClone->AsBlockStatement(); } - finalizer_ = other.finalizer_ == nullptr ? nullptr : other.finalizer_->Clone(allocator, this)->AsBlockStatement(); for (auto &[label, st] : other.finalizerInsertions_) { finalizerInsertions_.emplace_back(label, st); } @@ -138,6 +150,7 @@ TryStatement::TryStatement(TryStatement const &other, ArenaAllocator *allocator) TryStatement *TryStatement::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(*this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/statements/variableDeclaration.cpp b/ets2panda/ir/statements/variableDeclaration.cpp index 56934876cf..b6057d4e9c 100644 --- a/ets2panda/ir/statements/variableDeclaration.cpp +++ b/ets2panda/ir/statements/variableDeclaration.cpp @@ -142,7 +142,9 @@ VariableDeclaration::VariableDeclaration([[maybe_unused]] Tag const tag, Variabl } for (auto const &d : other.declarators_) { - declarators_.emplace_back(d->Clone(allocator, nullptr)->AsVariableDeclarator()); + auto *dClone = d->Clone(allocator, nullptr); + ES2PANDA_ASSERT(dClone != nullptr); + declarators_.emplace_back(dClone->AsVariableDeclarator()); declarators_.back()->SetParent(this); } } @@ -150,6 +152,7 @@ VariableDeclaration::VariableDeclaration([[maybe_unused]] Tag const tag, Variabl VariableDeclaration *VariableDeclaration::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/statements/variableDeclarator.cpp b/ets2panda/ir/statements/variableDeclarator.cpp index 78ee2fd4f8..059bd4173c 100644 --- a/ets2panda/ir/statements/variableDeclarator.cpp +++ b/ets2panda/ir/statements/variableDeclarator.cpp @@ -76,6 +76,7 @@ VariableDeclarator *VariableDeclarator::Clone(ArenaAllocator *const allocator, A auto *const id = id_ != nullptr ? id_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const init = init_ != nullptr ? init_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(flag_, id, init); + ES2PANDA_ASSERT(clone != nullptr); if (id != nullptr) { id->SetParent(clone); diff --git a/ets2panda/parser/TSparser.cpp b/ets2panda/parser/TSparser.cpp index 164f34c170..98823e5ef4 100644 --- a/ets2panda/parser/TSparser.cpp +++ b/ets2panda/parser/TSparser.cpp @@ -734,6 +734,7 @@ ir::TSTypeParameter *TSParser::ParseMappedTypeParameter() lexer::SourcePosition startLoc = Lexer()->GetToken().Start(); auto *paramName = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(paramName != nullptr); paramName->SetRange({Lexer()->GetToken().Start(), Lexer()->GetToken().End()}); Lexer()->NextToken(); @@ -891,6 +892,7 @@ ir::TypeNode *TSParser::ParseTypeLiteralOrMappedType(ir::TypeNode *typeAnnotatio Lexer()->NextToken(); auto *literalType = AllocNode(std::move(members), Allocator()); + ES2PANDA_ASSERT(literalType != nullptr); auto *typeVar = varbinder::Scope::CreateVar(Allocator(), "__type", varbinder::VariableFlags::TYPE, literalType); literalType->SetVariable(typeVar); literalType->SetRange({bodyStart, bodyEnd}); @@ -1998,6 +2000,7 @@ std::tuple TSParser::ParseComputedClassFieldOrIndexSignature(i if (Lexer()->GetToken().Type() == lexer::TokenType::LITERAL_IDENT && Lexer()->Lookahead() == lexer::LEX_CHAR_COLON) { auto id = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(id != nullptr); id->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); // eat param diff --git a/ets2panda/parser/TypedParser.cpp b/ets2panda/parser/TypedParser.cpp index 85634a4e63..cfdf144927 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -193,6 +193,7 @@ ir::TSTypeAssertion *TypedParser::ParseTypeAssertion() Lexer()->NextToken(); // eat '>' ir::Expression *expression = ParseExpression(); auto *typeAssertion = AllocNode(typeAnnotation, expression); + ES2PANDA_ASSERT(typeAssertion != nullptr); typeAssertion->SetRange({start, Lexer()->GetToken().End()}); return typeAssertion; @@ -299,6 +300,7 @@ ir::TSModuleDeclaration *TypedParser::ParseAmbientExternalModuleDeclaration(cons auto *moduleDecl = AllocNode(Allocator(), name, body, ir::TSModuleDeclaration::ConstructorFlags {isGlobal, true}); + ES2PANDA_ASSERT(moduleDecl != nullptr); moduleDecl->SetRange({startLoc, Lexer()->GetToken().End()}); return moduleDecl; @@ -311,6 +313,7 @@ ir::TSModuleDeclaration *TypedParser::ParseModuleOrNamespaceDeclaration(const le } auto *identNode = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(identNode != nullptr); identNode->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -343,6 +346,7 @@ ir::TSModuleBlock *TypedParser::ParseTsModuleBlock() auto statements = ParseStatementList(); auto *blockNode = AllocNode(std::move(statements)); + ES2PANDA_ASSERT(blockNode != nullptr); blockNode->SetRange({startLoc, Lexer()->GetToken().End()}); ExpectToken(lexer::TokenType::PUNCTUATOR_RIGHT_BRACE); @@ -419,6 +423,7 @@ ir::TypeNode *TypedParser::ParseInterfaceExtendsElement() if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_LESS_THAN) { TypeAnnotationParsingOptions options = TypeAnnotationParsingOptions::REPORT_ERROR; typeParamInst = ParseTypeParameterInstantiation(&options); + ES2PANDA_ASSERT(typeParamInst != nullptr); heritageEnd = typeParamInst->End(); } @@ -435,7 +440,9 @@ ArenaVector TypedParser::ParseInterfaceExtendsClause( while (true) { auto *typeReference = ParseInterfaceExtendsElement(); + ES2PANDA_ASSERT(typeReference != nullptr); auto *heritage = AllocNode(typeReference); + ES2PANDA_ASSERT(heritage != nullptr); heritage->SetRange(typeReference->Range()); extends.push_back(heritage); @@ -495,6 +502,7 @@ ir::Statement *TypedParser::ParseInterfaceDeclaration(bool isStatic) Allocator(), std::move(extends), ir::TSInterfaceDeclaration::ConstructorData {id, typeParamDecl, body, isStatic, isExternal, GetContext().GetLanguage()}); + ES2PANDA_ASSERT(interfaceDecl != nullptr); interfaceDecl->SetRange({interfaceStart, Lexer()->GetToken().End()}); Lexer()->NextToken(); @@ -693,6 +701,7 @@ ir::TSEnumDeclaration *TypedParser::ParseEnumMembers(ir::Identifier *key, const auto *enumDeclaration = AllocNode(Allocator(), key, std::move(members), ir::TSEnumDeclaration::ConstructorFlags {isConst}); + ES2PANDA_ASSERT(enumDeclaration != nullptr); enumDeclaration->SetRange({enumStart, endLoc}); return enumDeclaration; @@ -729,7 +738,7 @@ ir::TSTypeParameter *TypedParser::ParseTypeParameter(TypeAnnotationParsingOption const auto &ident = Lexer()->GetToken().Ident(); auto *paramIdent = AllocNode(ident, Allocator()); - + ES2PANDA_ASSERT(paramIdent != nullptr); paramIdent->SetRange({Lexer()->GetToken().Start(), Lexer()->GetToken().End()}); Lexer()->NextToken(); @@ -888,6 +897,7 @@ ArenaVector TypedParser::ParseClassImplementClause() lexer::SourcePosition implStart = Lexer()->GetToken().Start(); auto [expr, implTypeParams] = ParseClassImplementsElement(); auto *impl = AllocNode(expr, implTypeParams); + ES2PANDA_ASSERT(impl != nullptr); impl->SetRange({implStart, Lexer()->GetToken().End()}); implements.push_back(impl); @@ -973,6 +983,7 @@ ir::ClassDefinition *TypedParser::ParseClassDefinition(ir::ClassDefinitionModifi auto *classDefinition = AllocNode(identNode, typeParamDecl, superTypeParams, std::move(implements), ctor, superClass, std::move(properties), modifiers, flags, GetContext().GetLanguage()); + ES2PANDA_ASSERT(classDefinition != nullptr); classDefinition->SetInternalName(privateBinding.View()); classDefinition->SetRange(bodyRange); @@ -1006,7 +1017,7 @@ ir::AstNode *TypedParser::ParseProperty(const ArenaVector &proper property = AllocNode(propName, typeAnnotation, desc.modifiers & ir::ModifierFlags::READONLY); - + ES2PANDA_ASSERT(property != nullptr); property->SetRange({property->AsTSIndexSignature()->Param()->Start(), property->AsTSIndexSignature()->TypeAnnotation()->End()}); } else { @@ -1017,7 +1028,7 @@ ir::AstNode *TypedParser::ParseProperty(const ArenaVector &proper if (desc.isPrivateIdent) { LogError(diagnostic::DECORATORS_INVALID); } - + ES2PANDA_ASSERT(property != nullptr); property->AddDecorators(std::move(desc.decorators)); } } @@ -1203,6 +1214,7 @@ ir::Expression *TypedParser::ParseQualifiedName(ExpressionParseFlags flags) break; case lexer::TokenType::LITERAL_IDENT: expr = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(expr != nullptr); expr->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); break; @@ -1260,6 +1272,7 @@ ir::Expression *TypedParser::ParseQualifiedReference(ir::Expression *typeName, E propName->SetRange(Lexer()->GetToken().Loc()); typeName = AllocNode(typeName, propName, Allocator()); + ES2PANDA_ASSERT(typeName != nullptr); typeName->SetRange({typeName->AsTSQualifiedName()->Left()->Start(), Lexer()->GetToken().End()}); if (Lexer()->GetToken().Type() == lexer::TokenType::LITERAL_IDENT) { diff --git a/ets2panda/parser/expressionParser.cpp b/ets2panda/parser/expressionParser.cpp index 37c03683eb..3dd632cf3d 100644 --- a/ets2panda/parser/expressionParser.cpp +++ b/ets2panda/parser/expressionParser.cpp @@ -767,6 +767,7 @@ ir::TemplateLiteral *ParserImpl::ParseTemplateLiteral() } auto *templateNode = AllocNode(std::move(quasis), std::move(expressions), multilineStr); + ES2PANDA_ASSERT(templateNode != nullptr); templateNode->SetRange({startLoc, lexer_->GetToken().End()}); lexer_->NextToken(); diff --git a/ets2panda/varbinder/scope.h b/ets2panda/varbinder/scope.h index d8701598bd..d2ee06562b 100644 --- a/ets2panda/varbinder/scope.h +++ b/ets2panda/varbinder/scope.h @@ -216,6 +216,7 @@ public: Variable *AddDecl(ArenaAllocator *allocator, Decl *decl, ScriptExtension extension) { + ES2PANDA_ASSERT(decl != nullptr); auto *var = AddBinding(allocator, FindLocal(decl->Name(), varbinder::ResolveBindingOptions::BINDINGS), decl, extension); if (var != nullptr) { @@ -873,6 +874,7 @@ public: { auto *paramScope = allocator->New(allocator, this); paramScope_ = paramScope; + ES2PANDA_ASSERT(paramScope_ != nullptr); paramScope_->BindFunctionScope(this); } @@ -979,7 +981,7 @@ std::pair Scope::AddDecl(ArenaAllocator *allocator, auto *decl = allocator->New(name); variable = allocator->New(decl, flags); - + ES2PANDA_ASSERT(variable != nullptr); decls_.emplace_back(decl); bindings_.insert({decl->Name(), variable}); variable->SetScope(this); diff --git a/ets2panda/varbinder/varbinder.cpp b/ets2panda/varbinder/varbinder.cpp index d08635be49..157a58e7ef 100644 --- a/ets2panda/varbinder/varbinder.cpp +++ b/ets2panda/varbinder/varbinder.cpp @@ -145,7 +145,7 @@ void VarBinder::InstantiateArguments() auto *iter = scope_; while (true) { Scope *scope = iter->IsFunctionParamScope() ? iter : iter->EnclosingVariableScope(); - + ES2PANDA_ASSERT(scope != nullptr); const auto *node = scope->Node(); if (scope->IsLoopScope()) { @@ -172,7 +172,7 @@ void VarBinder::PropagateDirectEval() const do { VariableScope *scope = iter->IsFunctionParamScope() ? iter->AsFunctionParamScope()->GetFunctionScope() : iter->EnclosingVariableScope(); - + ES2PANDA_ASSERT(scope != nullptr); scope->AddFlag(ScopeFlags::NO_REG_STORE); iter = iter->Parent(); } while (iter != nullptr); @@ -185,7 +185,7 @@ void VarBinder::InstantiatePrivateContext(const ir::Identifier *ident) const while (classDef != nullptr) { auto *scope = classDef->Scope(); Variable *variable = scope->FindLocal(classDef->InternalName(), varbinder::ResolveBindingOptions::BINDINGS); - + ES2PANDA_ASSERT(variable != nullptr); if (!variable->HasFlag(VariableFlags::INITIALIZED)) { break; } @@ -328,6 +328,7 @@ void VarBinder::BuildVarDeclarator(ir::VariableDeclarator *varDecl) void VarBinder::BuildClassProperty(const ir::ClassProperty *prop) { const ir::ScriptFunction *ctor = util::Helpers::GetContainingConstructor(prop); + ES2PANDA_ASSERT(ctor != nullptr); auto scopeCtx = LexicalScope::Enter(this, ctor->Scope()); ResolveReferences(prop); @@ -363,6 +364,7 @@ void VarBinder::BuildClassDefinition(ir::ClassDefinition *classDef) } Variable *variable = scope_->FindLocal(classDef->InternalName(), varbinder::ResolveBindingOptions::BINDINGS); + ES2PANDA_ASSERT(variable != nullptr); variable->AddFlag(VariableFlags::INITIALIZED); if (classDef->Ident() != nullptr) { @@ -536,6 +538,7 @@ void VarBinder::ResolveReference(ir::AstNode *childNode) LookupIdentReference(childNode->AsIdentifier()); return ResolveReferences(childNode); case ir::AstNodeType::SUPER_EXPRESSION: + ES2PANDA_ASSERT(scope_->EnclosingVariableScope() != nullptr); scope_->EnclosingVariableScope()->AddFlag(ScopeFlags::USE_SUPER); return ResolveReferences(childNode); case ir::AstNodeType::SCRIPT_FUNCTION: { diff --git a/ets2panda/varbinder/variable.cpp b/ets2panda/varbinder/variable.cpp index 6768c7b88a..bb3cdb7998 100644 --- a/ets2panda/varbinder/variable.cpp +++ b/ets2panda/varbinder/variable.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 @@ -39,6 +39,7 @@ const util::StringView &Variable::Name() const LocalVariable *LocalVariable::Copy(ArenaAllocator *allocator, Decl *decl) const { auto *var = allocator->New(decl, flags_); + ES2PANDA_ASSERT(var != nullptr); var->vreg_ = vreg_; return var; } @@ -50,7 +51,7 @@ void LocalVariable::SetLexical(Scope *scope) } VariableScope *varScope = scope->EnclosingVariableScope(); - + ES2PANDA_ASSERT(varScope != nullptr); BindLexEnvSlot(varScope->NextSlot()); } -- Gitee From 6743dfc7474ef014153dbd5735285c4c7f127369 Mon Sep 17 00:00:00 2001 From: xingshunxiang Date: Mon, 30 Jun 2025 18:54:08 +0800 Subject: [PATCH 078/145] Redef Builtin Class cause SegV Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICK7IX?from=project-issue Description: Redef Builtin Class cause SegV Reason: In VarBinder, Redef Builtin class will Break the GlobalTypesHolder, because the Redef Builtin class will be inserted to bindingMaps, but with no builtin flag. 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/ets/invalid_class_declare.ets | 20 +++++++++++++ ets2panda/varbinder/ETSBinder.cpp | 6 ++++ ets2panda/varbinder/scope.cpp | 30 +++++++++++++++++++ ets2panda/varbinder/scope.h | 2 ++ 4 files changed, 58 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/invalid_class_declare.ets diff --git a/ets2panda/test/ast/compiler/ets/invalid_class_declare.ets b/ets2panda/test/ast/compiler/ets/invalid_class_declare.ets new file mode 100644 index 0000000000..082a7347c6 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/invalid_class_declare.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 Integral {} +class Numeric {} + +/* @@? 1:3 Error TypeError: Class 'Integral' is already defined. */ +/* @@? 1:3 Error TypeError: Class 'Numeric' is already defined. */ diff --git a/ets2panda/varbinder/ETSBinder.cpp b/ets2panda/varbinder/ETSBinder.cpp index 38e6ab7b42..52c736f570 100644 --- a/ets2panda/varbinder/ETSBinder.cpp +++ b/ets2panda/varbinder/ETSBinder.cpp @@ -692,6 +692,12 @@ void ETSBinder::ImportAllForeignBindings(ir::AstNode *const specifier, InsertForeignBinding(specifier, import, bindingName, var); } + // redeclaration for builtin type, + // need to erase the redeclaration one and make sure the builtin types initialized successfully. + if (var->HasFlag(varbinder::VariableFlags::BUILTIN_TYPE)) { + TopScope()->CorrectForeignBinding(bindingName, var, variable); + } + ThrowRedeclarationError(import->Source()->Start(), var, variable, bindingName); } } diff --git a/ets2panda/varbinder/scope.cpp b/ets2panda/varbinder/scope.cpp index fb13142b90..e9e8d36342 100644 --- a/ets2panda/varbinder/scope.cpp +++ b/ets2panda/varbinder/scope.cpp @@ -75,6 +75,27 @@ Variable *Scope::FindLocal(const util::StringView &name, ResolveBindingOptions o return res->second; } +bool Scope::CorrectForeignBinding(const util::StringView &name, Variable *builtinVar, Variable *redefinedVar) +{ + ES2PANDA_ASSERT(builtinVar != redefinedVar); + auto bindingTobeErase = bindings_.find(name); + if (bindingTobeErase == bindings_.end()) { + return false; + } + + Variable *varTobeErase = bindingTobeErase->second; + if (varTobeErase != redefinedVar) { + return false; + } + + auto declTobeErase = redefinedVar->Declaration(); + bindings_.erase(name); + auto it = std::find_if(decls_.begin(), decls_.end(), [&](auto *decl) { return decl == declTobeErase; }); + ES2PANDA_ASSERT(it != decls_.end()); + decls_.erase(it); + return Scope::InsertBinding(name, builtinVar).second; +} + Scope::InsertResult Scope::InsertBinding(const util::StringView &name, Variable *const var) { ES2PANDA_ASSERT(var != nullptr); @@ -630,6 +651,15 @@ Scope::InsertResult GlobalScope::InsertOrAssignForeignBinding(const util::String return GlobalScope::InsertImpl(name, var, InsertBindingFlags::FOREIGN | InsertBindingFlags::ASSIGN); } +bool GlobalScope::CorrectForeignBinding(const util::StringView &name, Variable *builtinVar, Variable *redefinedVar) +{ + const bool deleteRes = Scope::CorrectForeignBinding(name, builtinVar, redefinedVar); + if (deleteRes) { + foreignBindings_[name] = true; + } + return deleteRes; +} + Scope::InsertResult GlobalScope::InsertImpl(const util::StringView &name, Variable *const var, const InsertBindingFlags flags) { diff --git a/ets2panda/varbinder/scope.h b/ets2panda/varbinder/scope.h index d8701598bd..f816261a47 100644 --- a/ets2panda/varbinder/scope.h +++ b/ets2panda/varbinder/scope.h @@ -249,6 +249,7 @@ public: virtual InsertResult TryInsertBinding(const util::StringView &name, Variable *var); virtual void MergeBindings(VariableMap const &bindings); virtual VariableMap::size_type EraseBinding(const util::StringView &name); + virtual bool CorrectForeignBinding(const util::StringView &name, Variable *builtinVar, Variable *redefinedVar); [[nodiscard]] const VariableMap &Bindings() const noexcept { @@ -894,6 +895,7 @@ public: [[nodiscard]] bool IsForeignBinding(const util::StringView &name) const; InsertResult InsertDynamicBinding(const util::StringView &name, Variable *var); + bool CorrectForeignBinding(const util::StringView &name, Variable *builtinVar, Variable *redefinedVar) override; private: enum class InsertBindingFlags : uint8_t { NONE = 0, FOREIGN = 1U << 0U, DYNAMIC = 1U << 1U, ASSIGN = 1U << 2U }; -- Gitee From a75908f721588e8b16607a22a6848ed450323486 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Sat, 5 Jul 2025 17:09:47 +0800 Subject: [PATCH 079/145] Fix crash in function type with receiver Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICK8DM Description: Return annotation for function type with receiver is this, which is inferred as global, and tstype is set incorrectly. Lead to a crash during the unbox lowering phase. Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/checker/ETSAnalyzer.cpp | 5 ++- .../extensionFunctionType_return_this.ets | 34 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/runtime/ets/function_type_with_receiver/extensionFunctionType_return_this.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 06efd4e454..57661adb46 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -377,7 +377,10 @@ checker::Type *ETSAnalyzer::Check(ir::ETSFunctionType *node) const checker->CheckFunctionSignatureAnnotations(node->Params(), node->TypeParams(), node->ReturnType()); auto *signatureInfo = checker->ComposeSignatureInfo(node->TypeParams(), node->Params()); - auto *returnType = checker->ComposeReturnType(node->ReturnType(), node->IsAsync()); + auto *returnType = node->IsExtensionFunction() && node->ReturnType()->IsTSThisType() + ? signatureInfo->params.front()->TsType() + : checker->ComposeReturnType(node->ReturnType(), node->IsAsync()); + auto *const signature = checker->CreateSignature(signatureInfo, returnType, node->Flags(), node->IsExtensionFunction()); if (signature == nullptr) { // #23134 diff --git a/ets2panda/test/runtime/ets/function_type_with_receiver/extensionFunctionType_return_this.ets b/ets2panda/test/runtime/ets/function_type_with_receiver/extensionFunctionType_return_this.ets new file mode 100644 index 0000000000..56514ff521 --- /dev/null +++ b/ets2panda/test/runtime/ets/function_type_with_receiver/extensionFunctionType_return_this.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 B { + value: T; + x:T; + constructor(value: T) { + this.value = value; + } +} + +type FBSI = (this: B, x: string|Int) => this; +function apply(bb: B[], ff: FBSI) { + for (let b of bb) { + arktest.assertEQ(b.ff("hello").value, b.value) + arktest.assertEQ(b.ff("hello").x, "hello") + arktest.assertEQ(ff(b, "hello").value, b.value) + arktest.assertEQ(ff(b, "hello").x, "hello") + } +} +let bb: B[] = [new B("aa"), new B(1)] +apply(bb, (this: B, x: string|Int): this => {this.x = x; return this;} ) -- Gitee From 6c9a77792d284261c57dc99b7c436dab05d4d6e6 Mon Sep 17 00:00:00 2001 From: anjiaqi Date: Tue, 1 Jul 2025 09:36:02 +0800 Subject: [PATCH 080/145] Cherry-pick !6605 from 0328 to 0603 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJ9MD Reason: Fix the security alert Description: Fix the security alert Test: ninja all tests Signed-off-by: anjiaqi --- codecheck_ignore.json | 9 ++++ ets2panda/checker/ETSAnalyzer.cpp | 6 ++- ets2panda/checker/ETSAnalyzerHelpers.cpp | 8 +++ ets2panda/checker/ETSchecker.cpp | 1 + ets2panda/checker/TSAnalyzer.cpp | 4 ++ ets2panda/checker/ets/aliveAnalyzer.cpp | 1 + ets2panda/checker/ets/arithmetic.cpp | 1 + ets2panda/checker/ets/assignAnalyzer.cpp | 17 +++++-- ets2panda/checker/ets/dynamic.cpp | 5 ++ ets2panda/checker/ets/etsWarningAnalyzer.cpp | 10 ++-- ets2panda/checker/ets/function.cpp | 32 +++++++++--- ets2panda/checker/ets/function_helpers.h | 2 + ets2panda/checker/ets/helpers.cpp | 34 ++++++++++--- ets2panda/checker/ets/object.cpp | 14 ++++-- ets2panda/checker/ets/typeCheckingHelpers.cpp | 28 +++++++++-- ets2panda/checker/ets/typeCreation.cpp | 13 ++++- ets2panda/checker/ets/typeRelationContext.cpp | 1 + ets2panda/checker/ets/utilityTypeHandlers.cpp | 40 +++++++++++---- ets2panda/checker/ts/destructuringContext.cpp | 4 ++ ets2panda/checker/ts/function.cpp | 10 +++- ets2panda/checker/ts/helpers.cpp | 5 +- ets2panda/checker/ts/object.cpp | 4 ++ ets2panda/checker/ts/typeCreation.cpp | 6 ++- .../checker/types/ets/etsFunctionType.cpp | 20 +++++--- ets2panda/checker/types/ets/etsObjectType.cpp | 6 ++- .../types/ets/etsPartialTypeParameter.cpp | 9 +++- ets2panda/checker/types/ets/etsTupleType.cpp | 1 + ets2panda/checker/types/ets/etsTupleType.h | 5 +- .../checker/types/ets/etsTypeParameter.cpp | 1 + ets2panda/checker/types/ets/etsUnionType.cpp | 3 ++ ets2panda/checker/types/signature.cpp | 5 +- ets2panda/checker/types/signature.h | 1 + ets2panda/checker/types/ts/interfaceType.cpp | 3 +- .../checker/types/ts/objectDescriptor.cpp | 4 +- ets2panda/checker/types/ts/unionType.cpp | 4 +- ets2panda/checker/types/typeRelation.cpp | 4 ++ ets2panda/parser/ASparser.cpp | 28 +++++++++++ ets2panda/parser/ETSFormattedParser.cpp | 4 ++ ets2panda/parser/ETSparser.cpp | 43 ++++++++++++++++ ets2panda/parser/ETSparserAnnotations.cpp | 18 +++++-- ets2panda/parser/ETSparserClasses.cpp | 33 ++++++++++--- ets2panda/parser/ETSparserEnums.cpp | 1 + ets2panda/parser/ETSparserExpressions.cpp | 10 ++++ ets2panda/parser/ETSparserJsDocInfo.cpp | 7 ++- ets2panda/parser/ETSparserNamespaces.cpp | 2 + ets2panda/parser/ETSparserStatements.cpp | 2 + ets2panda/parser/ETSparserTypes.cpp | 10 ++++ ets2panda/parser/TSparser.cpp | 24 ++++++++- .../parser/context/classPrivateContext.cpp | 10 ++-- ets2panda/parser/expressionParser.cpp | 49 +++++++++++++++++++ ets2panda/parser/expressionTSParser.cpp | 9 ++++ ets2panda/parser/parserImpl.cpp | 21 +++++++- ets2panda/parser/program/program.cpp | 3 +- ets2panda/parser/statementParser.cpp | 40 +++++++++++++++ ets2panda/parser/statementTSParser.cpp | 6 +++ 55 files changed, 558 insertions(+), 83 deletions(-) diff --git a/codecheck_ignore.json b/codecheck_ignore.json index 775d3e8774..a30bb19d2b 100755 --- a/codecheck_ignore.json +++ b/codecheck_ignore.json @@ -8,9 +8,18 @@ "test_ecma_bcopt": "*", "legacy_bin": "*", "merge_abc": "*", + "ets2panda/bindings/src": "*", + "ets2panda/driver/build_system/src": "*", "ets2panda/public/headers_parser": "*", "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": "*", "*": ["G.CMT.03", "G.FMT.11", "G.NAM.03", "huge_headerfile", "huge_non_headerfile", "bc-30001"] } diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 06efd4e454..d6ecd34a6d 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -160,6 +160,7 @@ checker::Type *ETSAnalyzer::Check(ir::ClassStaticBlock *st) const static void HandleNativeAndAsyncMethods(ETSChecker *checker, ir::MethodDefinition *node) { auto *scriptFunc = node->Function(); + ES2PANDA_ASSERT(scriptFunc != nullptr); if (node->IsNative() && !node->IsConstructor() && !scriptFunc->IsSetter()) { if (scriptFunc->ReturnTypeAnnotation() == nullptr) { checker->LogError(diagnostic::NATIVE_WITHOUT_RETURN, {}, scriptFunc->Start()); @@ -397,6 +398,7 @@ static bool CheckArrayElementType(ETSChecker *checker, T *newArrayInstanceExpr) ES2PANDA_ASSERT(newArrayInstanceExpr != nullptr); checker::Type *elementType = newArrayInstanceExpr->TypeReference()->GetType(checker); + ES2PANDA_ASSERT(elementType != nullptr); if (elementType->IsETSPrimitiveType()) { return true; } @@ -2900,7 +2902,7 @@ checker::Type *ETSAnalyzer::Check(ir::AnnotationUsage *st) const return ReturnTypeForStatement(st); } - if (st->Properties().size() == 1 && + if (st->Properties().size() == 1 && st->Properties().at(0)->AsClassProperty()->Id() != nullptr && st->Properties().at(0)->AsClassProperty()->Id()->Name() == compiler::Signatures::ANNOTATION_KEY_VALUE) { checker->CheckSinglePropertyAnnotation(st, annoDecl); fieldMap.clear(); @@ -3137,6 +3139,7 @@ static bool CheckIsValidReturnTypeAnnotation(ir::ReturnStatement *st, ir::Script return true; } +// CC-OFFNXT(huge_method[C++], G.FUN.01-CPP) solid logic bool ETSAnalyzer::CheckInferredFunctionReturnType(ir::ReturnStatement *st, ir::ScriptFunction *containingFunc, checker::Type *&funcReturnType, ir::TypeNode *returnTypeAnnotation, ETSChecker *checker) const @@ -3161,6 +3164,7 @@ bool ETSAnalyzer::CheckInferredFunctionReturnType(ir::ReturnStatement *st, ir::S // Case when function's return type is defined explicitly: if (st->argument_ == nullptr) { + ES2PANDA_ASSERT(funcReturnType != nullptr); if (!funcReturnType->IsETSVoidType() && funcReturnType != checker->GlobalVoidType() && !funcReturnType->IsETSAsyncFuncReturnType()) { checker->LogError(diagnostic::RETURN_WITHOUT_VALUE, {}, st->Start()); diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index f652f68e78..c6b5124a6e 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -57,6 +57,7 @@ void CheckExtensionIsShadowedInCurrentClassOrInterface(checker::ETSChecker *chec const auto *const funcType = methodVariable->TsType()->AsETSFunctionType(); for (auto *funcSignature : funcType->CallSignatures()) { + ES2PANDA_ASSERT(signature != nullptr); signature->SetReturnType(funcSignature->ReturnType()); if (!checker->Relation()->SignatureIsSupertypeOf(signature, funcSignature) && !checker->HasSameAssemblySignature(signature, funcSignature)) { @@ -149,6 +150,7 @@ void CheckExtensionMethod(checker::ETSChecker *checker, ir::ScriptFunction *exte checker::SignatureInfo *originalExtensionSigInfo = checker->ProgramAllocator()->New( extensionFunc->Signature()->GetSignatureInfo(), checker->ProgramAllocator()); + ES2PANDA_ASSERT(originalExtensionSigInfo != nullptr); originalExtensionSigInfo->minArgCount -= 1U; originalExtensionSigInfo->params.erase(originalExtensionSigInfo->params.begin()); checker::Signature *originalExtensionSignature = @@ -220,6 +222,7 @@ void DoBodyTypeChecking(ETSChecker *checker, ir::MethodDefinition *node, ir::Scr if (scriptFunc->ReturnTypeAnnotation() == nullptr) { if (scriptFunc->IsAsyncFunc()) { auto returnType = checker->CreateETSAsyncFuncReturnTypeFromBaseType(scriptFunc->Signature()->ReturnType()); + ES2PANDA_ASSERT(returnType != nullptr); scriptFunc->Signature()->SetReturnType(returnType->PromiseType()); for (auto &returnStatement : scriptFunc->ReturnStatements()) { returnStatement->SetReturnType(checker, returnType); @@ -248,6 +251,7 @@ void ComposeAsyncImplFuncReturnType(ETSChecker *checker, ir::ScriptFunction *scr auto *returnType = checker->ProgramAllocNode( checker->ProgramAllocNode(objectId, nullptr, nullptr, checker->ProgramAllocator()), checker->ProgramAllocator()); + ES2PANDA_ASSERT(returnType != nullptr); objectId->SetParent(returnType->Part()); returnType->Part()->SetParent(returnType); returnType->SetTsType(checker->ProgramAllocator()->New(checker->ProgramAllocator(), @@ -317,6 +321,7 @@ void CheckIteratorMethodReturnType(ETSChecker *checker, ir::ScriptFunction *scri returnType = checker->GetApparentType(returnType->AsETSTypeParameter()->GetConstraintType()); } + ES2PANDA_ASSERT(returnType != nullptr); if (returnType->IsETSObjectType() && HasIteratorInterface(returnType->AsETSObjectType())) { return; } @@ -689,6 +694,7 @@ void InferReturnType(ETSChecker *checker, ir::ScriptFunction *containingFunc, ch auto typeAnnotation = arrowFunc->CreateTypeAnnotation(checker); auto *argumentType = arrowFunc->TsType(); + ES2PANDA_ASSERT(typeAnnotation != nullptr); funcReturnType = typeAnnotation->GetType(checker); if (!checker::AssignmentContext(checker->Relation(), arrowFunc, argumentType, funcReturnType, stArgument->Start(), std::nullopt, @@ -760,6 +766,7 @@ void ProcessReturnStatements(ETSChecker *checker, ir::ScriptFunction *containing checker::Type *argumentType = checker->GetNonConstantType(stArgument->Check(checker)); // previous return statement(s) don't have any value + ES2PANDA_ASSERT(argumentType != nullptr); if (funcReturnType->IsETSVoidType() && !argumentType->IsETSVoidType()) { checker->LogError(diagnostic::MIXED_VOID_NONVOID, {}, stArgument->Start()); return; @@ -788,6 +795,7 @@ bool CheckReturnTypeNecessity(ir::MethodDefinition *node) auto *scriptFunc = node->Function(); needReturnType &= (node->IsNative() || node->IsDeclare()); needReturnType &= !node->IsConstructor(); + ES2PANDA_ASSERT(scriptFunc != nullptr); needReturnType &= !scriptFunc->IsSetter(); return needReturnType; } diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index 658fb4a498..ef82ec2dee 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -660,6 +660,7 @@ ETSObjectType *ETSChecker::GlobalBuiltinBoxType(Type *contents) default: { auto *base = AsETSObjectType(&GlobalTypesHolder::GlobalBoxBuiltinType); auto *substitution = NewSubstitution(); + ES2PANDA_ASSERT(base != nullptr); substitution->emplace(base->TypeArguments()[0]->AsETSTypeParameter(), contents); return base->Substitute(Relation(), substitution); } diff --git a/ets2panda/checker/TSAnalyzer.cpp b/ets2panda/checker/TSAnalyzer.cpp index cfaad3f534..c353155e2c 100644 --- a/ets2panda/checker/TSAnalyzer.cpp +++ b/ets2panda/checker/TSAnalyzer.cpp @@ -107,6 +107,7 @@ checker::Type *TSAnalyzer::Check(ir::TSMethodSignature *node) const } returnType->Check(checker); + ES2PANDA_ASSERT(callSignature != nullptr); callSignature->SetReturnType(returnType->GetType(checker)); return nullptr; @@ -787,6 +788,7 @@ void TSAnalyzer::CheckNonComputed(checker::ObjectDescriptor *desc, ir::Expressio auto *memberVar = varbinder::Scope::CreateVar(checker->Allocator(), propName, flags, it); + ES2PANDA_ASSERT(memberVar != nullptr); if (inConstContext) { memberVar->AddFlag(varbinder::VariableFlags::READONLY); } else { @@ -1342,6 +1344,7 @@ static void CheckSimpleVariableDeclaration(checker::TSChecker *checker, ir::Vari initializerType = checker->GetBaseTypeOfLiteralType(initializerType); } + ES2PANDA_ASSERT(initializerType != nullptr); if (initializerType->IsNullType()) { checker->ThrowTypeError( {"Cannot infer type for variable '", declarator->Id()->AsIdentifier()->Name(), "'."}, @@ -1729,6 +1732,7 @@ static void AddEnumValueDeclaration(checker::TSChecker *checker, double number, if (res == nullptr) { auto *decl = checker->Allocator()->New(memberStr); + ES2PANDA_ASSERT(decl != nullptr); decl->BindNode(variable->Declaration()->Node()); enumScope->AddDecl(checker->Allocator(), decl, ScriptExtension::TS); res = enumScope->FindLocal(memberStr, varbinder::ResolveBindingOptions::BINDINGS); diff --git a/ets2panda/checker/ets/aliveAnalyzer.cpp b/ets2panda/checker/ets/aliveAnalyzer.cpp index ff2ba27302..eeffc8ac82 100644 --- a/ets2panda/checker/ets/aliveAnalyzer.cpp +++ b/ets2panda/checker/ets/aliveAnalyzer.cpp @@ -234,6 +234,7 @@ void AliveAnalyzer::AnalyzeMethodDef(const ir::MethodDefinition *methodDef) auto *func = methodDef->Function(); + ES2PANDA_ASSERT(func != nullptr); if (func->Body() == nullptr || func->IsProxy()) { return; } diff --git a/ets2panda/checker/ets/arithmetic.cpp b/ets2panda/checker/ets/arithmetic.cpp index 7f9007daec..e45e0f6121 100644 --- a/ets2panda/checker/ets/arithmetic.cpp +++ b/ets2panda/checker/ets/arithmetic.cpp @@ -836,6 +836,7 @@ Type *ETSChecker::CheckBinaryOperatorNullishCoalescing(ir::Expression *left, ir: return leftType; } leftType = GetNonNullishType(leftType); + ES2PANDA_ASSERT(leftType != nullptr); if (leftType->IsTypeError()) { ES2PANDA_ASSERT(IsAnyError()); return GlobalTypeError(); diff --git a/ets2panda/checker/ets/assignAnalyzer.cpp b/ets2panda/checker/ets/assignAnalyzer.cpp index 9ed3378f8b..358a10a992 100644 --- a/ets2panda/checker/ets/assignAnalyzer.cpp +++ b/ets2panda/checker/ets/assignAnalyzer.cpp @@ -536,7 +536,9 @@ static bool IsInitialConstructor(const ir::AstNode *node) return false; } - const auto funcBody = node->AsMethodDefinition()->Function()->Body()->AsBlockStatement(); + const auto *func = node->AsMethodDefinition()->Function(); + ES2PANDA_ASSERT(func != nullptr); + const auto funcBody = func->Body()->AsBlockStatement(); return !(!funcBody->Statements().empty() && funcBody->Statements()[0]->IsExpressionStatement() && funcBody->Statements()[0]->AsExpressionStatement()->GetExpression()->IsCallExpression() && @@ -551,7 +553,7 @@ static bool IsInitialConstructor(const ir::AstNode *node) void AssignAnalyzer::AnalyzeMethodDef(const ir::MethodDefinition *methodDef) { auto *func = methodDef->Function(); - + ES2PANDA_ASSERT(func != nullptr); if (func->Body() == nullptr || func->IsProxy()) { return; } @@ -1204,8 +1206,11 @@ util::StringView AssignAnalyzer::GetVariableType(const ir::AstNode *node) const util::StringView AssignAnalyzer::GetVariableName(const ir::AstNode *node) const { switch (node->Type()) { - case ir::AstNodeType::CLASS_PROPERTY: - return node->AsClassProperty()->Id()->Name(); + case ir::AstNodeType::CLASS_PROPERTY: { + const ir::Identifier *identifier = node->AsClassProperty()->Id(); + ES2PANDA_ASSERT(identifier != nullptr); + return identifier->Name(); + } case ir::AstNodeType::VARIABLE_DECLARATOR: return node->AsVariableDeclarator()->Id()->AsIdentifier()->Name(); default: @@ -1277,7 +1282,9 @@ varbinder::Variable *AssignAnalyzer::GetBoundVariable(const ir::AstNode *node) varbinder::Variable *ret = nullptr; if (node->IsClassProperty()) { - ret = node->AsClassProperty()->Id()->Variable(); + const ir::Identifier *identifier = node->AsClassProperty()->Id(); + ES2PANDA_ASSERT(identifier != nullptr); + ret = identifier->Variable(); } else if (node->IsVariableDeclarator()) { ret = node->AsVariableDeclarator()->Id()->AsIdentifier()->Variable(); } else { diff --git a/ets2panda/checker/ets/dynamic.cpp b/ets2panda/checker/ets/dynamic.cpp index 90abef0f88..3f907d3796 100644 --- a/ets2panda/checker/ets/dynamic.cpp +++ b/ets2panda/checker/ets/dynamic.cpp @@ -50,6 +50,7 @@ namespace ark::es2panda::checker { void ProcessCheckerNode(ETSChecker *checker, ir::AstNode *node) { auto scope = compiler::NearestScope(node); + ES2PANDA_ASSERT(scope != nullptr); if (scope->IsGlobalScope()) { // NOTE(aleksisch): All classes are contained in ETSGlobal class scope (not just Global scope), // however it's parent is ETSModule. It should be fixed @@ -73,6 +74,7 @@ void ProcessCheckerNode(ETSChecker *checker, ir::AstNode *node) void ProcessScopesNode(ETSChecker *checker, ir::AstNode *node) { auto *scope = compiler::NearestScope(node); + ES2PANDA_ASSERT(scope != nullptr); if (scope->IsGlobalScope()) { // NOTE(aleksisch): All classes are contained in ETSGlobal scope, // however it's parent is ETSModule (not ETSGlobal). It should be fixed @@ -260,6 +262,7 @@ std::pair ETSChecker::CreateStaticScript ir::ModifierFlags::STATIC, }); // clang-format on + ES2PANDA_ASSERT(func != nullptr); func->SetIdent(id); return std::make_pair(func, id); @@ -286,6 +289,7 @@ std::pair ETSChecker::CreateScriptFuncti ir::ScriptFunctionFlags::CONSTRUCTOR | ir::ScriptFunctionFlags::EXPRESSION, ir::ModifierFlags::PUBLIC}); + ES2PANDA_ASSERT(func != nullptr); func->SetIdent(id); return std::make_pair(func, id); @@ -302,6 +306,7 @@ ir::ClassStaticBlock *ETSChecker::CreateClassStaticInitializer(const ClassInitia // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *staticBlock = ProgramAllocNode(funcExpr, ProgramAllocator()); + ES2PANDA_ASSERT(staticBlock != nullptr); staticBlock->AddModifier(ir::ModifierFlags::STATIC); return staticBlock; diff --git a/ets2panda/checker/ets/etsWarningAnalyzer.cpp b/ets2panda/checker/ets/etsWarningAnalyzer.cpp index f8709512c2..239398f27f 100644 --- a/ets2panda/checker/ets/etsWarningAnalyzer.cpp +++ b/ets2panda/checker/ets/etsWarningAnalyzer.cpp @@ -105,8 +105,10 @@ void ETSWarningAnalyzer::AnalyzeClassMethodForFinalModifier(const ir::MethodDefi } const util::StringView bodyMethodName = ETSChecker::GetSignatureFromMethodDefinition(bodyPart->AsMethodDefinition())->Function()->Id()->Name(); + const auto *func = methodDef->Function(); + ES2PANDA_ASSERT(func != nullptr); if (bodyPart->IsOverride() && bodyMethodName != compiler::Signatures::CTOR && - bodyMethodName == methodDef->Function()->Id()->Name()) { + bodyMethodName == func->Id()->Name()) { suggestFinal = false; break; } @@ -214,9 +216,9 @@ void ETSWarningAnalyzer::ETSWarningsProhibitTopLevelStatements(const ir::AstNode itBody->AsMethodDefinition()->Id()->Name() != compiler::Signatures::INIT_METHOD) { continue; } - - for (const auto *statement : - itBody->AsMethodDefinition()->Function()->Body()->AsBlockStatement()->Statements()) { + const auto *func = itBody->AsMethodDefinition()->Function(); + ES2PANDA_ASSERT(func != nullptr); + for (const auto *statement : func->Body()->AsBlockStatement()->Statements()) { if (program_->NodeContainsETSNolint(statement, ETSWarnings::ETS_PROHIBIT_TOP_LEVEL_STATEMENTS)) { continue; } diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 432e97432f..00cf70be4e 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -89,6 +89,7 @@ bool ETSChecker::EnhanceSubstitutionForReadonly(const ArenaVector &typeP bool ETSChecker::EnhanceSubstitutionForType(const ArenaVector &typeParams, Type *paramType, Type *argumentType, Substitution *substitution) { + ES2PANDA_ASSERT(argumentType != nullptr); if (argumentType->IsETSPrimitiveType()) { argumentType = MaybeBoxInRelation(argumentType); } @@ -420,6 +421,7 @@ bool ETSChecker::ValidateSignatureRequiredParams(Signature *substitutedSig, // #22952: infer optional parameter heuristics auto const paramType = GetNonNullishType(substitutedSig->Params()[index]->TsType()); if (argument->IsObjectExpression()) { + ES2PANDA_ASSERT(paramType != nullptr); if (paramType->IsETSObjectType()) { // No chance to check the argument at this point continue; @@ -944,6 +946,7 @@ void ETSChecker::CollectSuitableSignaturesForTypeInference( for (auto *sig : signatures) { auto *sigParamType = GetNonNullishType(sig->Params().at(paramIdx)->TsType()); + ES2PANDA_ASSERT(sigParamType != nullptr); if (!sigParamType->IsETSFunctionType()) { continue; } @@ -1237,7 +1240,9 @@ static bool CollectOverload(checker::ETSChecker *checker, ir::MethodDefinition * currentFunc->Function()->Id()->SetVariable(currentFunc->Id()->Variable()); checker->BuildFunctionSignature(currentFunc->Function(), method->IsConstructor()); if (currentFunc->Function()->Signature() == nullptr) { - method->Id()->Variable()->SetTsType(checker->GlobalTypeError()); + auto *methodId = method->Id(); + ES2PANDA_ASSERT(methodId != nullptr); + methodId->Variable()->SetTsType(checker->GlobalTypeError()); return false; } auto *const overloadType = checker->BuildMethodType(currentFunc->Function()); @@ -1277,11 +1282,12 @@ checker::Type *ETSChecker::BuildMethodSignature(ir::MethodDefinition *method) if (method->TsType() != nullptr) { return method->TsType()->AsETSFunctionType(); } - - method->Function()->Id()->SetVariable(method->Id()->Variable()); + auto *methodId = method->Id(); + ES2PANDA_ASSERT(methodId != nullptr); + method->Function()->Id()->SetVariable(methodId->Variable()); BuildFunctionSignature(method->Function(), method->IsConstructor()); if (method->Function()->Signature() == nullptr) { - return method->Id()->Variable()->SetTsType(GlobalTypeError()); + return methodId->Variable()->SetTsType(GlobalTypeError()); } auto *funcType = BuildMethodType(method->Function()); method->InitializeOverloadInfo(); @@ -1295,7 +1301,7 @@ checker::Type *ETSChecker::BuildMethodSignature(ir::MethodDefinition *method) LogDiagnostic(diagnostic::FUNCTION_ASM_SIG_COLLISION, {std::string(funcType->Name())}, method->Start()); } - return method->Id()->Variable()->SetTsType(funcType); + return methodId->Variable()->SetTsType(funcType); } bool ETSChecker::CheckIdenticalOverloads(ETSFunctionType *func, ETSFunctionType *overload, @@ -1419,6 +1425,7 @@ SignatureInfo *ETSChecker::ComposeSignatureInfo(ir::TSTypeParameterDeclaration * if (typeParams != nullptr) { auto [typeParamTypes, ok] = CreateUnconstrainedTypeParameters(typeParams); + ES2PANDA_ASSERT(signatureInfo != nullptr); signatureInfo->typeParams = std::move(typeParamTypes); if (ok) { AssignTypeParameterConstraints(typeParams); @@ -1476,6 +1483,7 @@ void ETSChecker::ValidateMainSignature(ir::ScriptFunction *func) void ETSChecker::BuildFunctionSignature(ir::ScriptFunction *func, bool isConstructSig) { + ES2PANDA_ASSERT(func != nullptr); bool isArrow = func->IsArrow(); auto *nameVar = isArrow ? nullptr : func->Id()->Variable(); auto funcName = nameVar == nullptr ? util::StringView() : nameVar->Name(); @@ -1522,6 +1530,7 @@ void ETSChecker::BuildFunctionSignature(ir::ScriptFunction *func, bool isConstru checker::ETSFunctionType *ETSChecker::BuildMethodType(ir::ScriptFunction *func) { ES2PANDA_ASSERT(!func->IsArrow()); + ES2PANDA_ASSERT(func != nullptr); auto *nameVar = func->Id()->Variable(); ETSFunctionType *funcType; if (func->IsDynamic()) { @@ -1545,7 +1554,7 @@ Signature *ETSChecker::CheckEveryAbstractSignatureIsOverridden(ETSFunctionType * for (auto sourceSig : source->CallSignatures()) { if ((*targetSig)->Function()->Id()->Name() == sourceSig->Function()->Id()->Name() && Relation()->SignatureIsSupertypeOf(*targetSig, sourceSig)) { - target->CallSignatures().erase(targetSig); + targetSig = target->CallSignatures().erase(targetSig); isOverridden = true; break; } @@ -1782,6 +1791,7 @@ bool ETSChecker::CheckOverride(Signature *signature, ETSObjectType *site) void ETSChecker::CheckOverride(Signature *signature) { auto *owner = signature->Owner(); + ES2PANDA_ASSERT(owner != nullptr); bool isOverriding = false; if (!owner->HasObjectFlag(ETSObjectFlags::CLASS | ETSObjectFlags::INTERFACE)) { @@ -1996,7 +2006,9 @@ std::string ETSChecker::GetAsyncImplName(const util::StringView &name) std::string ETSChecker::GetAsyncImplName(ir::MethodDefinition *asyncMethod) { - ir::Identifier *asyncName = asyncMethod->Function()->Id(); + ir::ScriptFunction *scriptFunc = asyncMethod->Function(); + CHECK_NOT_NULL(scriptFunc); + ir::Identifier *asyncName = scriptFunc->Id(); ES2PANDA_ASSERT_POS(asyncName != nullptr, asyncMethod->Start()); return GetAsyncImplName(asyncName->Name()); } @@ -2032,6 +2044,7 @@ ir::MethodDefinition *ETSChecker::CreateMethod(const util::StringView &name, ir: if (body != nullptr && body->IsBlockStatement()) { body->AsBlockStatement()->SetScope(scope); } + ES2PANDA_ASSERT(scope != nullptr); scope->BindNode(func); paramScope->BindNode(func); scope->BindParamScope(paramScope); @@ -2064,7 +2077,9 @@ varbinder::FunctionParamScope *ETSChecker::CopyParams( for (auto *const it : params) { auto *const paramOld = it->AsETSParameterExpression(); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) - auto *const paramNew = paramOld->Clone(ProgramAllocator(), paramOld->Parent())->AsETSParameterExpression(); + auto *typeOld = paramOld->Clone(ProgramAllocator(), paramOld->Parent()); + ES2PANDA_ASSERT(typeOld != nullptr); + auto *const paramNew = typeOld->AsETSParameterExpression(); varbinder::Variable *var = VarBinder()->AddParamDecl(paramNew); Type *paramType = paramOld->Variable()->TsType(); @@ -2200,6 +2215,7 @@ ArenaVector ETSChecker::ExtendArgumentsWithFakeLamda(ir::CallE ArenaVector statements(ProgramAllocator()->Adapter()); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *body = ProgramAllocNode(ProgramAllocator(), std::move(statements)); + ES2PANDA_ASSERT(body != nullptr); body->SetScope(funcScope); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) diff --git a/ets2panda/checker/ets/function_helpers.h b/ets2panda/checker/ets/function_helpers.h index 2ed4c6b430..8009932975 100644 --- a/ets2panda/checker/ets/function_helpers.h +++ b/ets2panda/checker/ets/function_helpers.h @@ -54,6 +54,7 @@ namespace ark::es2panda::checker { static Type *MaybeBoxedType(ETSChecker *checker, Type *type, ir::Expression *expr) { + ES2PANDA_ASSERT(type != nullptr); if (!type->IsETSPrimitiveType()) { return type; } @@ -77,6 +78,7 @@ static void InferUntilFail(Signature const *const signature, const ArenaVectorAddStatus(checker::CheckerStatus::IN_TYPE_INFER); // some ets lib files require type infer from arg index 0,1,... , not fit to build graph + ES2PANDA_ASSERT(substitution != nullptr); while (anyChange && substitution->size() < sigParams.size()) { anyChange = false; for (size_t ix = 0; ix < arguments.size(); ++ix) { diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index e551c2898a..3bbd86a096 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -58,6 +58,7 @@ varbinder::Variable *ETSChecker::FindVariableInGlobal(const ir::Identifier *cons bool ETSChecker::IsVariableStatic(const varbinder::Variable *var) { + CHECK_NOT_NULL(var); if (var->HasFlag(varbinder::VariableFlags::METHOD)) { return var->TsType()->AsETSFunctionType()->CallSignatures()[0]->HasSignatureFlag(SignatureFlags::STATIC); } @@ -758,6 +759,7 @@ static void CheckAssignForDeclare(ir::Identifier *ident, ir::TypeNode *typeAnnot return; } const bool isConst = (flags & ir::ModifierFlags::CONST) != 0; + ES2PANDA_ASSERT(init != nullptr); bool numberLiteralButNotBigInt = init->IsNumberLiteral() && !init->IsBigIntLiteral(); bool multilineLiteralWithNoEmbedding = init->IsTemplateLiteral() && init->AsTemplateLiteral()->Expressions().empty(); @@ -809,6 +811,7 @@ static void CheckRecordType(ir::Expression *init, checker::Type *annotationType, checker::Type *ETSChecker::CheckVariableDeclaration(ir::Identifier *ident, ir::TypeNode *typeAnnotation, ir::Expression *init, ir::ModifierFlags const flags) { + ES2PANDA_ASSERT(ident != nullptr); varbinder::Variable *const bindingVar = ident->Variable(); checker::Type *annotationType = nullptr; @@ -1720,6 +1723,7 @@ void ETSChecker::SetPropertiesForModuleObject(checker::ETSObjectType *moduleObjT parser::Program *program = SelectEntryOrExternalProgram(static_cast(VarBinder()), importPath); // Check imported properties before assigning them to module object + ES2PANDA_ASSERT(program != nullptr); if (!program->IsASTChecked()) { // NOTE: helps to avoid endless loop in case of recursive imports that uses all bindings program->SetASTChecked(); @@ -2334,7 +2338,7 @@ ETSObjectType *ETSChecker::GetRelevantArgumentedTypeFromChild(ETSObjectType *con auto *relevantType = CreateETSObjectType(child->GetDeclNode(), child->ObjectFlags()); ArenaVector params = child->TypeArguments(); - + ES2PANDA_ASSERT(relevantType != nullptr); relevantType->SetTypeArguments(std::move(params)); relevantType->SetEnclosingType(child->EnclosingType()); relevantType->SetSuperType(child->SuperType()); @@ -2351,6 +2355,7 @@ void ETSChecker::EmplaceSubstituted(Substitution *substitution, ETSTypeParameter { // *only* reference type may be substituted, no exceptions ES2PANDA_ASSERT(typeArg->IsETSReferenceType()); + ES2PANDA_ASSERT(substitution != nullptr); substitution->emplace(tparam, typeArg); } @@ -2412,7 +2417,9 @@ util::StringView ETSChecker::GetHashFromFunctionType(ir::ETSFunctionType *type) if (type->ReturnType()->IsTSThisType()) { type->Params()[0]->AsETSParameterExpression()->TypeAnnotation()->TsType()->ToString(ss, true); } else { - type->ReturnType()->GetType(this)->ToString(ss, true); + auto *returnType = type->ReturnType()->GetType(this); + ES2PANDA_ASSERT(returnType != nullptr); + returnType->ToString(ss, true); } ss << "extensionFunction;"; } else { @@ -2648,6 +2655,7 @@ ir::ClassProperty *ETSChecker::ClassPropToImplementationProp(ir::ClassProperty * classProp->AddModifier(ir::ModifierFlags::PRIVATE); auto *fieldDecl = ProgramAllocator()->New(classProp->Key()->AsIdentifier()->Name()); + ES2PANDA_ASSERT(fieldDecl != nullptr); fieldDecl->BindNode(classProp); auto fieldVar = scope->InstanceFieldScope()->AddDecl(ProgramAllocator(), fieldDecl, ScriptExtension::ETS); @@ -2749,6 +2757,7 @@ static ir::BlockStatement *GenGetterSetterBodyHelper(ETSChecker *checker, ArenaV return nullptr; } auto *body = checker->ProgramAllocNode(checker->ProgramAllocator(), std::move(stmts)); + ES2PANDA_ASSERT(body != nullptr); body->SetScope(functionScope); return body; } @@ -2823,8 +2832,10 @@ ir::MethodDefinition *ETSChecker::GenerateDefaultGetterSetter(ir::ClassProperty method->Id()->SetMutator(); method->SetRange(field->Range()); + auto *methodId = method->Id(); + CHECK_NOT_NULL(methodId); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) - method->Function()->SetIdent(method->Id()->Clone(checker->ProgramAllocator(), nullptr)); + method->Function()->SetIdent(methodId->Clone(checker->ProgramAllocator(), nullptr)); method->Function()->AddModifier(method->Modifiers()); method->SetVariable(var); method->SetParent(field->Parent()); @@ -2882,19 +2893,21 @@ void ETSChecker::SetupGetterSetterFlags(ir::ClassProperty *originalProp, ETSObje method->TsType()->AddTypeFlag(tflag); method->Variable()->SetTsType(method->TsType()); + auto *func = method->Function(); + ES2PANDA_ASSERT(func != nullptr); if (((originalProp->Modifiers() & mflag) != 0U)) { - method->Function()->AddModifier(ir::ModifierFlags::OVERRIDE); + func->AddModifier(ir::ModifierFlags::OVERRIDE); } if (inExternal && !getProgram(originalProp)->IsGenAbcForExternal()) { - method->Function()->AddFlag(ir::ScriptFunctionFlags::EXTERNAL); + func->AddFlag(ir::ScriptFunctionFlags::EXTERNAL); } if (originalProp->IsDeclare()) { method->AddModifier(ir::ModifierFlags::DECLARE); - method->Function()->AddModifier(ir::ModifierFlags::DECLARE); + func->AddModifier(ir::ModifierFlags::DECLARE); } - this->CheckOverride(method->Function()->Signature()); + this->CheckOverride(func->Signature()); method->SetParent(classDef); classType->AddProperty(method->Variable()->AsLocalVariable()); } @@ -3038,6 +3051,7 @@ void ETSChecker::ImportNamespaceObjectTypeAddReExportType(ir::ETSImportDeclarati if (reExportType->IsTypeError()) { continue; } + ES2PANDA_ASSERT(lastObjectType != nullptr); lastObjectType->AddReExports(reExportType->AsETSObjectType()); for (auto node : importDecl->Specifiers()) { if (node->IsImportSpecifier()) { @@ -3071,6 +3085,7 @@ Type *ETSChecker::GetImportSpecifierObjectType(ir::ETSImportDeclaration *importD auto *rootDecl = ProgramAllocator()->New(moduleName); varbinder::LocalVariable *rootVar = ProgramAllocator()->New(rootDecl, varbinder::VariableFlags::NONE); + ES2PANDA_ASSERT(rootVar != nullptr); rootVar->SetTsType(moduleObjectType); ImportNamespaceObjectTypeAddReExportType(importDecl, moduleObjectType, ident); @@ -3085,7 +3100,9 @@ ETSChecker::NamedAccessMeta ETSChecker::FormNamedAccessMetadata(varbinder::Varia { const auto *field = prop->Declaration()->Node()->AsClassProperty(); const auto *owner = field->Parent()->AsClassDefinition(); - return {owner->TsType()->AsETSObjectType(), field->TsType(), field->Id()->Name()}; + auto *fieldId = field->Id(); + CHECK_NOT_NULL(fieldId); + return {owner->TsType()->AsETSObjectType(), field->TsType(), fieldId->Name()}; } void ETSChecker::ETSObjectTypeDeclNode(ETSChecker *checker, ETSObjectType *const objectType) @@ -3114,6 +3131,7 @@ ir::CallExpression *ETSChecker::CreateExtensionAccessorCall(ETSChecker *checker, // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) callExpr = checker->ProgramAllocNode(expr, std::move(args), nullptr, false, false); } + ES2PANDA_ASSERT(callExpr != nullptr); callExpr->SetRange(expr->Range()); return callExpr->AsCallExpression(); } diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 2b6cfeac48..7a7fb64409 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -186,6 +186,7 @@ bool ETSChecker::ComputeSuperType(ETSObjectType *type) void ETSChecker::ValidateImplementedInterface(ETSObjectType *type, Type *interface, std::unordered_set *extendsSet, const lexer::SourcePosition &pos) { + ES2PANDA_ASSERT(interface != nullptr); if (!interface->IsETSObjectType() || !interface->AsETSObjectType()->HasObjectFlag(ETSObjectFlags::INTERFACE)) { LogError(diagnostic::NOT_INTERFACE, {}, pos); return; @@ -394,7 +395,7 @@ ETSTypeParameter *ETSChecker::SetUpParameterType(ir::TSTypeParameter *const para } auto *const paramType = CreateTypeParameter(); - + ES2PANDA_ASSERT(paramType != nullptr); paramType->AddTypeFlag(TypeFlag::GENERIC); paramType->SetDeclNode(param); paramType->SetVariable(param->Variable()); @@ -525,6 +526,7 @@ ETSObjectType *ETSChecker::BuildAnonymousClassProperties(ir::ClassDefinition *cl { auto classType = CreateETSObjectType(classDef, checker::ETSObjectFlags::CLASS); classDef->SetTsType(classType); + ES2PANDA_ASSERT(classType != nullptr); classType->SetSuperType(superType); classType->AddObjectFlag(checker::ETSObjectFlags::RESOLVED_SUPER); @@ -550,12 +552,14 @@ static void ResolveDeclaredFieldsOfObject(ETSChecker *checker, const ETSObjectTy } } +// CC-OFFNXT(huge_method[C++], G.FUN.01-CPP) solid logic static void ResolveDeclaredMethodsOfObject(ETSChecker *checker, const ETSObjectType *type, varbinder::ClassScope *scope) { for (auto &[_, it] : scope->InstanceMethodScope()->Bindings()) { (void)_; auto *method = it->Declaration()->Node()->AsMethodDefinition(); auto *function = method->Function(); + ES2PANDA_ASSERT(function != nullptr); if (function->IsProxy()) { continue; } @@ -864,6 +868,7 @@ void ETSChecker::CheckFunctionRedeclarationInInterface(ETSObjectType *classType, if (sig == sigFunc) { return; } + ES2PANDA_ASSERT(sigFunc != nullptr); if (sigFunc->Function()->Id()->Name() == sig->Function()->Id()->Name()) { if (classType->IsSameBasedGeneric(Relation(), sig->Owner())) { return; @@ -883,6 +888,7 @@ static void CallRedeclarationCheckForCorrectSignature(ir::MethodDefinition *meth ETSObjectType *classType, ETSChecker *checker) { ir::ScriptFunction *func = method->Function(); + ES2PANDA_ASSERT(func != nullptr); if (!func->IsAbstract()) { auto *sigFunc = funcType->FindSignature(func); checker->CheckFunctionRedeclarationInInterface(classType, similarSignatures, sigFunc); @@ -1771,6 +1777,7 @@ void ETSChecker::CheckCyclicConstructorCall(Signature *signature) ETSObjectType *ETSChecker::CheckExceptionOrErrorType(checker::Type *type, const lexer::SourcePosition pos) { + ES2PANDA_ASSERT(type != nullptr); if (!type->IsETSObjectType() || (!Relation()->IsAssignableTo(type, GlobalBuiltinExceptionType()) && !Relation()->IsAssignableTo(type, GlobalBuiltinErrorType()))) { LogError(diagnostic::CATCH_OR_THROW_OF_INVALID_TYPE, @@ -2266,7 +2273,8 @@ void ETSChecker::WarnForEndlessLoopInGetterSetter(const ir::MemberExpression *co !parent->AsMethodDefinition()->Function()->IsSetter()))) { parent = parent->Parent(); } - if (parent != nullptr && ident->Name() == parent->AsMethodDefinition()->Function()->Id()->Name()) { + if (parent != nullptr && parent->AsMethodDefinition()->Function() != nullptr && + ident->Name() == parent->AsMethodDefinition()->Function()->Id()->Name()) { if (parent->AsMethodDefinition()->Function()->IsGetter()) { LogDiagnostic(diagnostic::GETTER_LOOP, memberExpr->Property()->AsIdentifier()->Start()); } else { @@ -2499,7 +2507,7 @@ Type *ETSChecker::GetApparentType(Type *type) apparentTypes_.insert({res, res}); return res; }; - + ES2PANDA_ASSERT(type != nullptr); if (type->IsETSTypeParameter()) { // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) return cached(GetApparentType(type->AsETSTypeParameter()->GetConstraintType())); diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index f43c3daf55..2d99239514 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -377,6 +377,7 @@ bool ETSChecker::IsConstantExpression(ir::Expression *expr, Type *type) Type *ETSChecker::GetNonConstantType(Type *type) { + ES2PANDA_ASSERT(type != nullptr); if (type->IsETSStringType()) { return GlobalBuiltinETSStringType(); } @@ -431,7 +432,9 @@ Type *ETSChecker::GetTypeOfSetterGetter(varbinder::Variable *const var) { auto *propType = var->TsType()->AsETSFunctionType(); if (propType->HasTypeFlag(checker::TypeFlag::GETTER)) { - return propType->FindGetter()->ReturnType(); + auto *getter = propType->FindGetter(); + ES2PANDA_ASSERT(getter != nullptr); + return getter->ReturnType(); } return propType->FindSetter()->Params()[0]->TsType(); @@ -447,7 +450,9 @@ void ETSChecker::IterateInVariableContext(varbinder::Variable *const var) if (iter->IsMethodDefinition()) { auto *methodDef = iter->AsMethodDefinition(); ES2PANDA_ASSERT(methodDef->TsType()); - Context().SetContainingSignature(methodDef->Function()->Signature()); + auto *func = methodDef->Function(); + ES2PANDA_ASSERT(func != nullptr); + Context().SetContainingSignature(func->Signature()); } else if (iter->IsClassDefinition()) { auto *classDef = iter->AsClassDefinition(); Type *containingClass {}; @@ -610,7 +615,9 @@ Type *ETSChecker::GuaranteedTypeForUncheckedPropertyAccess(varbinder::Variable * switch (auto node = prop->Declaration()->Node(); node->Type()) { case ir::AstNodeType::CLASS_PROPERTY: { - auto baseProp = node->AsClassProperty()->Id()->Variable(); + auto *id = node->AsClassProperty()->Id(); + ES2PANDA_ASSERT(id != nullptr); + auto baseProp = id->Variable(); if (baseProp == prop) { return nullptr; } @@ -630,7 +637,9 @@ Type *ETSChecker::GuaranteedTypeForUncheckedPropertyAccess(varbinder::Variable * // Determine if substituted method cast requires cast from erased type Type *ETSChecker::GuaranteedTypeForUncheckedCallReturn(Signature *sig) { + ES2PANDA_ASSERT(sig != nullptr); ES2PANDA_ASSERT(sig->HasFunction()); + ES2PANDA_ASSERT(sig); if (sig->HasSignatureFlag(SignatureFlags::THIS_RETURN_TYPE)) { return sig->ReturnType(); } @@ -648,6 +657,7 @@ Type *ETSChecker::ResolveUnionUncheckedType(ArenaVector &&appar return nullptr; } auto *unionType = CreateETSUnionType(std::move(apparentTypes)); + ES2PANDA_ASSERT(unionType != nullptr); if (unionType->IsETSUnionType()) { checker::Type *typeLUB = unionType->AsETSUnionType()->GetAssemblerLUB(); return typeLUB; @@ -751,6 +761,7 @@ Type *ETSChecker::GetTypeFromTypeAliasReference(varbinder::Variable *var) typeAliasType = CreateETSTypeAliasType(aliasTypeNode->Id()->Name(), aliasTypeNode); if (aliasTypeNode->TypeParams() != nullptr) { auto [typeParamTypes, ok] = CreateUnconstrainedTypeParameters(aliasTypeNode->TypeParams()); + ES2PANDA_ASSERT(typeAliasType != nullptr); typeAliasType->AsETSTypeAliasType()->SetTypeArguments(std::move(typeParamTypes)); if (ok) { AssignTypeParameterConstraints(aliasTypeNode->TypeParams()); @@ -905,7 +916,9 @@ void ETSChecker::CheckAmbientAnnotation(ir::AnnotationDeclaration *annoImpl, ir: for (auto *prop : annoImpl->Properties()) { auto *field = prop->AsClassProperty(); - auto fieldName = field->Id()->Name(); + auto *id = field->Id(); + ES2PANDA_ASSERT(id != nullptr); + auto fieldName = id->Name(); auto fieldDeclIter = fieldMap.find(fieldName); if (fieldDeclIter == fieldMap.end()) { LogError(diagnostic::AMBIENT_ANNOT_IMPL_OF_UNDEFINED_FIELD, {fieldName, annoDecl->GetBaseName()->Name()}, @@ -1149,7 +1162,9 @@ void ETSChecker::CheckMultiplePropertiesAnnotation(ir::AnnotationUsage *st, util auto *param = it->AsClassProperty(); auto result = fieldMap.find(param->Id()->Name()); if (result == fieldMap.end()) { - LogError(diagnostic::ANNOT_PROP_UNDEFINED, {param->Id()->Name(), baseName}, param->Start()); + auto *id = param->Id(); + ES2PANDA_ASSERT(id != nullptr); + LogError(diagnostic::ANNOT_PROP_UNDEFINED, {id->Name(), baseName}, param->Start()); continue; } @@ -1231,11 +1246,13 @@ Type *ETSChecker::MaybeBoxInRelation(Type *objectType) Type *ETSChecker::MaybeBoxType(Type *type) const { + ES2PANDA_ASSERT(type != nullptr); return type->IsETSPrimitiveType() ? BoxingConverter::Convert(this, type) : type; } Type *ETSChecker::MaybeUnboxType(Type *type) const { + ES2PANDA_ASSERT(type != nullptr); return type->IsETSUnboxableObject() ? UnboxingConverter::Convert(this, type->AsETSObjectType()) : type; } @@ -1483,6 +1500,7 @@ bool ETSChecker::CheckLambdaTypeAnnotation(ir::AstNode *typeAnnotation, auto param = typeAnnotation->Parent()->Parent()->AsETSParameterExpression(); // #22952: infer optional parameter heuristics auto nonNullishParam = param->IsOptional() ? GetNonNullishType(parameterType) : parameterType; + ES2PANDA_ASSERT(nonNullishParam != nullptr); if (!nonNullishParam->IsETSFunctionType()) { return true; } diff --git a/ets2panda/checker/ets/typeCreation.cpp b/ets2panda/checker/ets/typeCreation.cpp index 4c35d829af..67339ba322 100644 --- a/ets2panda/checker/ets/typeCreation.cpp +++ b/ets2panda/checker/ets/typeCreation.cpp @@ -103,7 +103,9 @@ ETSStringType *ETSChecker::CreateETSStringLiteralType(util::StringView value) ETSResizableArrayType *ETSChecker::CreateETSMultiDimResizableArrayType(Type *element, size_t dimSize) { - ETSResizableArrayType *const arrayType = GlobalBuiltinETSResizableArrayType()->AsETSResizableArrayType(); + ETSObjectType *type = GlobalBuiltinETSResizableArrayType(); + ES2PANDA_ASSERT(type != nullptr); + ETSResizableArrayType *const arrayType = type->AsETSResizableArrayType(); ES2PANDA_ASSERT(arrayType->TypeArguments().size() == 1U); Type *baseArrayType = element; @@ -119,7 +121,9 @@ ETSResizableArrayType *ETSChecker::CreateETSMultiDimResizableArrayType(Type *ele ETSResizableArrayType *ETSChecker::CreateETSResizableArrayType(Type *element) { - ETSResizableArrayType *arrayType = GlobalBuiltinETSResizableArrayType()->AsETSResizableArrayType(); + ETSObjectType *type = GlobalBuiltinETSResizableArrayType(); + ES2PANDA_ASSERT(type != nullptr); + ETSResizableArrayType *arrayType = type->AsETSResizableArrayType(); ES2PANDA_ASSERT(arrayType->TypeArguments().size() == 1U); Substitution *substitution = NewSubstitution(); @@ -137,6 +141,7 @@ ETSArrayType *ETSChecker::CreateETSArrayType(Type *elementType, bool isCachePoll auto *arrayType = ProgramAllocator()->New(elementType); + ES2PANDA_ASSERT(arrayType != nullptr); std::stringstream ss; arrayType->ToAssemblerTypeWithRank(ss); // arrayType->SetAssemblerName(util::UString(ss.str(), ProgramAllocator()).View()); @@ -234,6 +239,7 @@ Signature *ETSChecker::CreateSignature(SignatureInfo *info, Type *returnType, ir } auto signature = ProgramAllocator()->New(info, returnType, func); auto convertedFlag = ConvertToSignatureFlags(func->Modifiers(), func->Flags()); + ES2PANDA_ASSERT(signature != nullptr); func->HasReceiver() ? signature->AddSignatureFlag(SignatureFlags::EXTENSION_FUNCTION | convertedFlag) : signature->AddSignatureFlag(convertedFlag); return signature; @@ -426,6 +432,7 @@ std::tuple ETSChecker::CreateBuiltinArraySign arrayType->ToAssemblerTypeWithRank(ss); auto *info = CreateSignatureInfo(); + ES2PANDA_ASSERT(info != nullptr); info->minArgCount = dim; for (size_t i = 0; i < dim; i++) { @@ -455,6 +462,7 @@ Signature *ETSChecker::CreateBuiltinArraySignature(const ETSArrayType *arrayType auto [internalName, info] = CreateBuiltinArraySignatureInfo(arrayType, dim); auto *signature = CreateSignature(info, GlobalVoidType(), ir::ScriptFunctionFlags::NONE, false); + ES2PANDA_ASSERT(signature != nullptr); signature->SetInternalName(internalName); globalArraySignatures_.insert({arrayType, signature}); @@ -467,6 +475,7 @@ ETSObjectType *ETSChecker::CreatePromiseOf(Type *type) ES2PANDA_ASSERT(promiseType->TypeArguments().size() == 1U); Substitution *substitution = NewSubstitution(); + ES2PANDA_ASSERT(promiseType != nullptr); EmplaceSubstituted(substitution, promiseType->TypeArguments()[0]->AsETSTypeParameter()->GetOriginal(), type); return promiseType->Substitute(Relation(), substitution); diff --git a/ets2panda/checker/ets/typeRelationContext.cpp b/ets2panda/checker/ets/typeRelationContext.cpp index 00dcde0ae4..d50f534f2c 100644 --- a/ets2panda/checker/ets/typeRelationContext.cpp +++ b/ets2panda/checker/ets/typeRelationContext.cpp @@ -73,6 +73,7 @@ void InstantiationContext::InstantiateType(ETSObjectType *type, ir::TSTypeParame if (typeArgs != nullptr) { for (auto *const it : typeArgs->Params()) { auto *paramType = it->GetType(checker_); + ES2PANDA_ASSERT(paramType != nullptr); if (paramType->IsTypeError()) { result_ = paramType; return; diff --git a/ets2panda/checker/ets/utilityTypeHandlers.cpp b/ets2panda/checker/ets/utilityTypeHandlers.cpp index 3b44ea5941..64ccd5a22c 100644 --- a/ets2panda/checker/ets/utilityTypeHandlers.cpp +++ b/ets2panda/checker/ets/utilityTypeHandlers.cpp @@ -220,8 +220,10 @@ Type *ETSChecker::HandlePartialInterface(ir::TSInterfaceDeclaration *interfaceDe ir::ClassProperty *ETSChecker::CreateNullishPropertyFromAccessor(ir::MethodDefinition *const accessor, ir::ClassDefinition *const newClassDefinition) { + auto *id = accessor->Id(); + ES2PANDA_ASSERT(id != nullptr); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) - auto *ident = accessor->Id()->Clone(ProgramAllocator(), nullptr); + auto *ident = id->Clone(ProgramAllocator(), nullptr); auto modifierFlag = accessor->Function()->IsGetter() && accessor->Overloads().empty() ? ir::ModifierFlags::READONLY : ir::ModifierFlags::NONE; @@ -357,6 +359,7 @@ ir::TSTypeParameterDeclaration *ETSChecker::ProcessTypeParamAndGenSubstitution( CloneNodeIfNotNullptr(classOrInterfaceDefTypeParam->DefaultType(), ProgramAllocator()), ProgramAllocator()); newTypeParams->AddParam(newTypeParam); newTypeParam->SetParent(newTypeParams); + ES2PANDA_ASSERT(likeSubstitution != nullptr); (*likeSubstitution)[classOrInterfaceDefTypeParam] = newTypeParam; } return newTypeParams; @@ -389,6 +392,7 @@ ir::TSTypeParameterInstantiation *ETSChecker::CreateNewSuperPartialRefTypeParams // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) ProgramAllocNode(it->second->Name()->Clone(ProgramAllocator(), nullptr), ProgramAllocator()); + ES2PANDA_ASSERT(typeParamRefPart != nullptr); typeParamRefPart->Name()->SetParent(typeParamRefPart); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *typeParamRef = ProgramAllocNode(typeParamRefPart, ProgramAllocator()); @@ -417,6 +421,7 @@ ir::ETSTypeReference *ETSChecker::BuildSuperPartialTypeReference( // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) ProgramAllocNode(clonedId, superPartialRefTypeParams, nullptr, ProgramAllocator()); + ES2PANDA_ASSERT(superPartialRefPart != nullptr); superPartialRefPart->Name()->SetParent(superPartialRefPart); if (superPartialRefTypeParams != nullptr) { superPartialRefTypeParams->SetParent(superPartialRefPart); @@ -472,9 +477,9 @@ void ETSChecker::CreatePartialClassDeclaration(ir::ClassDefinition *const newCla // Put the new property into the class declaration newClassDefinition->Body().emplace_back(newProp); } - - if (prop->IsMethodDefinition() && (prop->AsMethodDefinition()->Function()->IsGetter() || - prop->AsMethodDefinition()->Function()->IsSetter())) { + if (prop->IsMethodDefinition() && prop->AsMethodDefinition()->Function() != nullptr && + (prop->AsMethodDefinition()->Function()->IsGetter() || + prop->AsMethodDefinition()->Function()->IsSetter())) { auto *method = prop->AsMethodDefinition(); if (newClassDefinition->Scope()->FindLocal(method->Id()->Name(), varbinder::ResolveBindingOptions::VARIABLES) != nullptr) { @@ -502,6 +507,7 @@ ir::MethodDefinition *ETSChecker::CreateNullishAccessor(ir::MethodDefinition *co const auto interfaceCtx = varbinder::LexicalScope::Enter(VarBinder(), interface->Scope()); auto *paramScope = ProgramAllocator()->New(ProgramAllocator(), interface->Scope()); auto *functionScope = ProgramAllocator()->New(ProgramAllocator(), paramScope); + ES2PANDA_ASSERT(functionScope != nullptr); functionScope->BindParamScope(paramScope); paramScope->BindFunctionScope(functionScope); @@ -578,8 +584,10 @@ ir::TSInterfaceDeclaration *ETSChecker::CreateInterfaceProto(util::StringView na // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *const interfaceId = ProgramAllocNode(name, ProgramAllocator()); + ES2PANDA_ASSERT(interfaceId); const auto [decl, var] = VarBinder()->NewVarDecl(interfaceId->Start(), ProgramAllocator(), interfaceId->Name()); + ES2PANDA_ASSERT(interfaceId != nullptr); interfaceId->SetVariable(var); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) @@ -647,9 +655,11 @@ void ETSChecker::CreatePartialTypeInterfaceMethods(ir::TSInterfaceDeclaration *c } auto *const method = prop->AsMethodDefinition(); - ES2PANDA_ASSERT((method->Function()->Flags() & ir::ScriptFunctionFlags::OVERLOAD) == 0U); + auto *func = method->Function(); + ES2PANDA_ASSERT(func != nullptr); + ES2PANDA_ASSERT((func->Flags() & ir::ScriptFunctionFlags::OVERLOAD) == 0U); - if (method->Function()->IsGetter() || method->Function()->IsSetter()) { + if (func->IsGetter() || func->IsSetter()) { // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) addNullishAccessor(CreateNullishAccessor(method, partialInterface)); } @@ -685,7 +695,9 @@ Type *ETSChecker::CreatePartialTypeInterfaceDecl(ir::TSInterfaceDeclaration *con auto methodscope = partialInterface->Scope()->AsClassScope()->InstanceMethodScope(); // Add getter methods to instancemethodscope. for (auto *const prop : partialInterface->Body()->Body()) { - if (prop->IsMethodDefinition() && prop->AsMethodDefinition()->Function()->IsGetter()) { + auto *func = prop->AsMethodDefinition()->Function(); + ES2PANDA_ASSERT(func != nullptr); + if (prop->IsMethodDefinition() && func->IsGetter()) { auto *decl = ProgramAllocator()->New( ProgramAllocator(), prop->AsMethodDefinition()->Key()->AsIdentifier()->Name(), prop); methodscope->AddDecl(ProgramAllocator(), decl, ScriptExtension::ETS); @@ -770,6 +782,7 @@ ir::ClassDefinition *ETSChecker::CreateClassPrototype(util::StringView name, par // Create class declaration node // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *const classDecl = ProgramAllocNode(classDef, ProgramAllocator()); + ES2PANDA_ASSERT(classDecl != nullptr); classDecl->SetParent(classDeclProgram->Ast()); // Class definition is scope bearer, not class declaration @@ -871,6 +884,7 @@ std::pair ETSChecker::CreateScriptFuncti // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *const body = ProgramAllocNode(ProgramAllocator(), std::move(statements)); + ES2PANDA_ASSERT(body != nullptr); body->SetScope(scope); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) id = ProgramAllocNode(util::UString(std::string("constructor"), ProgramAllocator()).View(), @@ -939,7 +953,7 @@ Type *ETSChecker::GetReadonlyType(Type *type) } NamedTypeStackElement ntse(this, type); - + ES2PANDA_ASSERT(type != nullptr); if (type->IsETSArrayType()) { ETSArrayType *const clonedArrayType = ProgramAllocator()->New(type->AsETSArrayType()->ElementType()); @@ -1005,6 +1019,7 @@ Type *ETSChecker::HandleRequiredType(Type *typeToBeRequired) for (auto *type : typeToBeRequired->AsETSUnionType()->ConstituentTypes()) { if (type->IsETSObjectType()) { type = type->Clone(this); + ES2PANDA_ASSERT(type != nullptr); MakePropertiesNonNullish(type->AsETSObjectType()); } @@ -1056,7 +1071,7 @@ void ETSChecker::MakePropertyNonNullish(ETSObjectType *const classType, varbinde auto *const nonNullishPropType = GetNonNullishType(propType); auto *const propCopy = prop->Copy(ProgramAllocator(), prop->Declaration()); - + ES2PANDA_ASSERT(propCopy != nullptr); propCopy->SetTsType(nonNullishPropType); classType->RemoveProperty(prop); classType->AddProperty(propCopy); @@ -1086,7 +1101,12 @@ void ETSChecker::ValidateObjectLiteralForRequiredType(const ETSObjectType *const if (requiredType->HasObjectFlag(ETSObjectFlags::INTERFACE)) { for (const auto *method : requiredType->GetDeclNode()->AsTSInterfaceDeclaration()->Body()->Body()) { - if (!method->IsMethodDefinition() || !method->AsMethodDefinition()->Function()->IsGetter()) { + if (!method->IsMethodDefinition()) { + continue; + } + auto *func = method->AsMethodDefinition()->Function(); + ES2PANDA_ASSERT(func != nullptr); + if (!func->IsGetter()) { continue; } diff --git a/ets2panda/checker/ts/destructuringContext.cpp b/ets2panda/checker/ts/destructuringContext.cpp index 95f65a54bb..db1636c4d1 100644 --- a/ets2panda/checker/ts/destructuringContext.cpp +++ b/ets2panda/checker/ts/destructuringContext.cpp @@ -201,6 +201,7 @@ void DestructuringContext::HandleAssignmentPattern(ir::AssignmentExpression *ass void ArrayDestructuringContext::ValidateInferredType() { + ES2PANDA_ASSERT(inferredType_ != nullptr); if (!inferredType_->IsArrayType() && !inferredType_->IsUnionType() && (!inferredType_->IsObjectType() || !inferredType_->AsObjectType()->IsTupleType())) { checker_->ThrowTypeError( @@ -328,6 +329,7 @@ Type *ArrayDestructuringContext::CreateTupleTypeForRest(TupleType *tuple) util::StringView memberIndex = util::Helpers::ToStringView(checker_->Allocator(), iterIndex); auto *memberVar = varbinder::Scope::CreateVar(checker_->Allocator(), memberIndex, varbinder::VariableFlags::PROPERTY, nullptr); + ES2PANDA_ASSERT(memberVar != nullptr); memberVar->SetTsType(tupleElementType); elementFlags.push_back(memberFlag); desc->properties.push_back(memberVar); @@ -528,6 +530,7 @@ void ArrayDestructuringContext::Start() void ObjectDestructuringContext::ValidateInferredType() { + ES2PANDA_ASSERT(inferredType_ != nullptr); // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) if (!inferredType_->IsObjectType()) { return; @@ -559,6 +562,7 @@ Type *ObjectDestructuringContext::CreateObjectTypeForRest(ObjectType *objType) varbinder::Scope::CreateVar(checker_->Allocator(), it->Name(), varbinder::VariableFlags::NONE, nullptr); memberVar->SetTsType(it->TsType()); memberVar->AddFlag(it->Flags()); + ES2PANDA_ASSERT(desc != nullptr); desc->properties.push_back(memberVar); } } diff --git a/ets2panda/checker/ts/function.cpp b/ets2panda/checker/ts/function.cpp index e4419c3f8c..b572291219 100644 --- a/ets2panda/checker/ts/function.cpp +++ b/ets2panda/checker/ts/function.cpp @@ -54,7 +54,7 @@ Type *TSChecker::HandleFunctionReturn(ir::ScriptFunction *func) if (func->IsArrow() && func->Body()->IsExpression()) { ElaborateElementwise(returnType, func->Body()->AsExpression(), func->Body()->Start()); } - + ES2PANDA_ASSERT(returnType != nullptr); if (returnType->IsNeverType()) { ThrowTypeError("A function returning 'never' cannot have a reachable end point.", func->ReturnTypeAnnotation()->Start()); @@ -156,6 +156,7 @@ Type *TSChecker::CreateParameterTypeForArrayAssignmentPattern(ir::ArrayExpressio util::StringView memberIndex = util::Helpers::ToStringView(Allocator(), index); varbinder::LocalVariable *newMember = varbinder::Scope::CreateVar( Allocator(), memberIndex, varbinder::VariableFlags::PROPERTY | varbinder::VariableFlags::OPTIONAL, nullptr); + ES2PANDA_ASSERT(newMember != nullptr); newMember->SetTsType(GlobalAnyType()); newTuple->AddProperty(newMember); } @@ -193,6 +194,7 @@ Type *TSChecker::CreateParameterTypeForObjectAssignmentPattern(ir::ObjectExpress varbinder::LocalVariable *newProp = varbinder::Scope::CreateVar( Allocator(), prop->Key()->AsIdentifier()->Name(), varbinder::VariableFlags::PROPERTY | varbinder::VariableFlags::OPTIONAL, nullptr); + ES2PANDA_ASSERT(newProp != nullptr); newProp->SetTsType(GetBaseTypeOfLiteralType(CheckTypeCached(assignmentPattern->Right()))); newObject->AddProperty(newProp); } @@ -246,6 +248,7 @@ ReturnedVariable TSChecker::CheckFunctionAssignmentPatternParameter(ir::Assignme util::UString pn(ss.str(), Allocator()); varbinder::LocalVariable *patternVar = varbinder::Scope::CreateVar(Allocator(), pn.View(), varbinder::VariableFlags::NONE, param); + ES2PANDA_ASSERT(patternVar != nullptr); patternVar->SetTsType(paramType); patternVar->AddFlag(varbinder::VariableFlags::OPTIONAL); return {patternVar->AsLocalVariable(), nullptr, true}; @@ -264,6 +267,7 @@ std::tuple TSCheck if (typeAnnotation != nullptr) { typeAnnotation->Check(this); restType = typeAnnotation->GetType(this); + ES2PANDA_ASSERT(restType != nullptr); if (!restType->IsArrayType()) { ThrowTypeError("A rest parameter must be of an array type", param->Start()); } @@ -315,6 +319,7 @@ std::tuple TSCheck auto destructuringContext = ArrayDestructuringContext({this, param->AsArrayPattern(), false, false, param->TypeAnnotation(), nullptr}); destructuringContext.Start(); + ES2PANDA_ASSERT(patternVar != nullptr); patternVar->SetTsType(destructuringContext.InferredType()); return {patternVar->AsLocalVariable(), nullptr, false}; } @@ -337,6 +342,7 @@ std::tuple TSCheck auto destructuringContext = ObjectDestructuringContext( {this, param->AsObjectPattern(), false, false, param->TypeAnnotation(), nullptr}); destructuringContext.Start(); + ES2PANDA_ASSERT(patternVar != nullptr); patternVar->SetTsType(destructuringContext.InferredType()); return {patternVar->AsLocalVariable(), nullptr, false}; } @@ -396,6 +402,7 @@ std::tuple TSCheck void TSChecker::CheckFunctionParameterDeclarations(const ArenaVector ¶ms, SignatureInfo *signatureInfo) { + ES2PANDA_ASSERT(signatureInfo != nullptr); signatureInfo->restVar = nullptr; signatureInfo->minArgCount = 0; @@ -590,6 +597,7 @@ void TSChecker::InferFunctionDeclarationType(const varbinder::FunctionDecl *decl } Signature *overloadSignature = Allocator()->New(overloadSignatureInfo, returnType, func); + ES2PANDA_ASSERT(descWithOverload != nullptr); descWithOverload->callSignatures.push_back(overloadSignature); } diff --git a/ets2panda/checker/ts/helpers.cpp b/ets2panda/checker/ts/helpers.cpp index 9c2455f558..7e654d6f7a 100644 --- a/ets2panda/checker/ts/helpers.cpp +++ b/ets2panda/checker/ts/helpers.cpp @@ -59,7 +59,7 @@ Type *TSChecker::GetBaseTypeOfLiteralType(Type *type) if (HasStatus(CheckerStatus::KEEP_LITERAL_TYPE)) { return type; } - + ES2PANDA_ASSERT(type != nullptr); if (type->IsStringLiteralType()) { return GlobalStringType(); } @@ -370,6 +370,7 @@ void TSChecker::GetTypeVar(varbinder::Decl *decl) util::Helpers::FindAncestorGivenByType(decl->Node(), ir::AstNodeType::VARIABLE_DECLARATOR); ES2PANDA_ASSERT(declarator); + ES2PANDA_ASSERT(declarator); if (declarator->AsVariableDeclarator()->Id()->IsIdentifier()) { InferSimpleVariableDeclaratorType(declarator->AsVariableDeclarator()); return; @@ -382,6 +383,7 @@ void TSChecker::GetTypeParam(varbinder::Variable *var, varbinder::Decl *decl) { ir::AstNode *declaration = FindAncestorUntilGivenType(decl->Node(), ir::AstNodeType::SCRIPT_FUNCTION); + ES2PANDA_ASSERT(declaration != nullptr); if (declaration->IsIdentifier()) { auto *ident = declaration->AsIdentifier(); if (ident->TypeAnnotation() != nullptr) { @@ -499,6 +501,7 @@ Type *TSChecker::GetTypeFromClassOrInterfaceReference([[maybe_unused]] ir::TSTyp if (resolvedType == nullptr) { ObjectDescriptor *desc = Allocator()->New(Allocator()); resolvedType = Allocator()->New(Allocator(), var->Name(), desc); + ES2PANDA_ASSERT(resolvedType != nullptr); resolvedType->SetVariable(var); var->SetTsType(resolvedType); } diff --git a/ets2panda/checker/ts/object.cpp b/ets2panda/checker/ts/object.cpp index d0b36c61dc..bf9d836a98 100644 --- a/ets2panda/checker/ts/object.cpp +++ b/ets2panda/checker/ts/object.cpp @@ -139,6 +139,7 @@ void TSChecker::ResolveUnionTypeMembers(UnionType *type) } } + ES2PANDA_ASSERT(desc != nullptr); desc->callSignatures = callSignatures; desc->constructSignatures = constructSignatures; @@ -333,6 +334,7 @@ varbinder::Variable *TSChecker::GetPropertyOfUnionType(UnionType *type, const ut } varbinder::Variable *syntheticProp = varbinder::Scope::CreateVar(Allocator(), name, flags, nullptr); + ES2PANDA_ASSERT(syntheticProp != nullptr); syntheticProp->SetTsType(CreateUnionType(std::move(collectedTypes))); type->CachedSyntheticProperties().insert({name, syntheticProp}); return syntheticProp; @@ -390,6 +392,7 @@ Type *TSChecker::GetPropertyTypeForIndexType(Type *type, Type *indexType) return type->AsArrayType()->ElementType(); } + ES2PANDA_ASSERT(indexType != nullptr); if (indexType->HasTypeFlag(TypeFlag::STRING_LITERAL | TypeFlag::NUMBER_LITERAL)) { varbinder::Variable *prop = nullptr; @@ -453,6 +456,7 @@ ArenaVector TSChecker::GetBaseTypes(InterfaceType *type) for (auto *extends : declaration->Extends()) { Type *baseType = extends->Expr()->GetType(this); + ES2PANDA_ASSERT(baseType != nullptr); if (!baseType->HasTypeFlag(TypeFlag::OBJECT | TypeFlag::NON_PRIMITIVE | TypeFlag::ANY)) { ThrowTypeError( "An interface can only extend an object type or intersection of object types with statically " diff --git a/ets2panda/checker/ts/typeCreation.cpp b/ets2panda/checker/ts/typeCreation.cpp index c40b8b1ed7..08b9a7ae9b 100644 --- a/ets2panda/checker/ts/typeCreation.cpp +++ b/ets2panda/checker/ts/typeCreation.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 @@ -125,6 +125,7 @@ Type *TSChecker::CreateUnionType(ArenaVector &&constituentTypes) Type *TSChecker::CreateObjectTypeWithCallSignature(Signature *callSignature) { auto *objType = Allocator()->New(Allocator()->New(Allocator())); + ES2PANDA_ASSERT(objType != nullptr); objType->AddCallSignature(callSignature); return objType; } @@ -132,6 +133,7 @@ Type *TSChecker::CreateObjectTypeWithCallSignature(Signature *callSignature) Type *TSChecker::CreateObjectTypeWithConstructSignature(Signature *constructSignature) { auto *objType = Allocator()->New(Allocator()->New(Allocator())); + ES2PANDA_ASSERT(objType != nullptr); objType->AddConstructSignature(constructSignature); return objType; } @@ -139,6 +141,7 @@ Type *TSChecker::CreateObjectTypeWithConstructSignature(Signature *constructSign Type *TSChecker::CreateFunctionTypeWithSignature(Signature *callSignature) { auto *funcObjType = Allocator()->New(Allocator()->New(Allocator())); + ES2PANDA_ASSERT(funcObjType != nullptr); funcObjType->AddCallSignature(callSignature); return funcObjType; } @@ -146,6 +149,7 @@ Type *TSChecker::CreateFunctionTypeWithSignature(Signature *callSignature) Type *TSChecker::CreateConstructorTypeWithSignature(Signature *constructSignature) { auto *constructObjType = Allocator()->New(Allocator()->New(Allocator())); + ES2PANDA_ASSERT(constructObjType != nullptr); constructObjType->AddConstructSignature(constructSignature); return constructObjType; } diff --git a/ets2panda/checker/types/ets/etsFunctionType.cpp b/ets2panda/checker/types/ets/etsFunctionType.cpp index 1df9fd28ea..7f9898dbd0 100644 --- a/ets2panda/checker/types/ets/etsFunctionType.cpp +++ b/ets2panda/checker/types/ets/etsFunctionType.cpp @@ -45,9 +45,12 @@ ETSFunctionType::ETSFunctionType(ETSChecker *checker, Signature *signature) extensionFunctionSigs_(ArenaVector(checker->ProgramAllocator()->Adapter())), extensionAccessorSigs_(ArenaVector(checker->ProgramAllocator()->Adapter())), name_(""), - assemblerName_(checker->GlobalBuiltinFunctionType(signature->MinArgCount(), signature->HasRestParameter()) - ->AsETSObjectType() - ->AssemblerName()) + assemblerName_(checker->GlobalBuiltinFunctionType(signature->MinArgCount(), signature->HasRestParameter()) != + nullptr + ? checker->GlobalBuiltinFunctionType(signature->MinArgCount(), signature->HasRestParameter()) + ->AsETSObjectType() + ->AssemblerName() + : "") { } @@ -55,11 +58,12 @@ ETSFunctionType::ETSFunctionType(ETSChecker *checker, Signature *signature) static void HackThisParameterInExtensionFunctionInvoke(ETSObjectType *interface, size_t arity) { auto invokeName = FunctionalInterfaceInvokeName(arity, false); - auto &callSigsOfInvoke0 = interface->AsETSObjectType() - ->GetOwnProperty(util::StringView(invokeName)) - ->TsType() - ->AsETSFunctionType() - ->CallSignatures(); + auto *property = interface->AsETSObjectType()->GetOwnProperty( + util::StringView(invokeName)); + ES2PANDA_ASSERT(property != nullptr); + auto *tsType = property->TsType(); + ES2PANDA_ASSERT(tsType != nullptr); + auto &callSigsOfInvoke0 = tsType->AsETSFunctionType()->CallSignatures(); for (auto sig : callSigsOfInvoke0) { sig->AddSignatureFlag(SignatureFlags::THIS_RETURN_TYPE); } diff --git a/ets2panda/checker/types/ets/etsObjectType.cpp b/ets2panda/checker/types/ets/etsObjectType.cpp index 733f658a53..ae6d6a8f21 100644 --- a/ets2panda/checker/types/ets/etsObjectType.cpp +++ b/ets2panda/checker/types/ets/etsObjectType.cpp @@ -188,7 +188,7 @@ varbinder::LocalVariable *ETSObjectType::CreateSyntheticVarFromEverySignature(co for (auto &s : signatures) { funcType->AddCallSignature(s); } - + ES2PANDA_ASSERT(res != nullptr); res->SetTsType(funcType); funcType->SetVariable(res); @@ -915,6 +915,7 @@ varbinder::LocalVariable *ETSObjectType::CopyProperty(varbinder::LocalVariable * if (copiedPropType->Variable() == prop) { copiedPropType->SetVariable(copiedProp); } + ES2PANDA_ASSERT(copiedProp != nullptr); copiedProp->SetTsType(copiedPropType); return copiedProp; } @@ -934,6 +935,7 @@ Type *ETSObjectType::Instantiate(ArenaAllocator *const allocator, TypeRelation * auto *const copiedType = checker->CreateETSObjectType(declNode_, flags_); ES2PANDA_ASSERT(copiedType->internalName_ == internalName_); ES2PANDA_ASSERT(copiedType->name_ == name_); + ES2PANDA_ASSERT(copiedType != nullptr); copiedType->typeFlags_ = typeFlags_; copiedType->RemoveObjectFlag(ETSObjectFlags::CHECKED_COMPATIBLE_ABSTRACTS | ETSObjectFlags::INCOMPLETE_INSTANTIATION | ETSObjectFlags::CHECKED_INVOKE_LEGITIMACY); @@ -982,6 +984,7 @@ static varbinder::LocalVariable *CopyPropertyWithTypeArguments(varbinder::LocalV if (copiedPropType->Variable() == prop || copiedPropType->Variable() == nullptr) { copiedPropType->SetVariable(copiedProp); } + ES2PANDA_ASSERT(copiedProp != nullptr); copiedProp->SetTsType(copiedPropType); return copiedProp; } @@ -1032,6 +1035,7 @@ static Substitution *ComputeEffectiveSubstitution(TypeRelation *const relation, void ETSObjectType::SetCopiedTypeProperties(TypeRelation *const relation, ETSObjectType *const copiedType, ArenaVector &&newTypeArgs, ETSObjectType *base) { + ES2PANDA_ASSERT(copiedType != nullptr); copiedType->typeFlags_ = typeFlags_; copiedType->RemoveObjectFlag(ETSObjectFlags::CHECKED_COMPATIBLE_ABSTRACTS | ETSObjectFlags::INCOMPLETE_INSTANTIATION | ETSObjectFlags::CHECKED_INVOKE_LEGITIMACY); diff --git a/ets2panda/checker/types/ets/etsPartialTypeParameter.cpp b/ets2panda/checker/types/ets/etsPartialTypeParameter.cpp index 14b5577976..fc451fd070 100644 --- a/ets2panda/checker/types/ets/etsPartialTypeParameter.cpp +++ b/ets2panda/checker/types/ets/etsPartialTypeParameter.cpp @@ -82,8 +82,13 @@ void ETSPartialTypeParameter::IsSubtypeOf(TypeRelation *relation, Type *target) ETSPartialTypeParameter *ETSPartialTypeParameter::Instantiate(ArenaAllocator *allocator, TypeRelation *relation, GlobalTypesHolder *globalTypes) { - return allocator->New( - GetUnderlying()->Instantiate(allocator, relation, globalTypes)->AsETSTypeParameter(), checker_); + auto *underlying = GetUnderlying(); + ES2PANDA_ASSERT(underlying != nullptr); + auto *instantiated = underlying->Instantiate(allocator, relation, globalTypes); + ES2PANDA_ASSERT(instantiated != nullptr); + auto *typeParam = instantiated->AsETSTypeParameter(); + ES2PANDA_ASSERT(typeParam != nullptr); + return allocator->New(typeParam, checker_); } Type *ETSPartialTypeParameter::Substitute(TypeRelation *relation, const Substitution *substitution) diff --git a/ets2panda/checker/types/ets/etsTupleType.cpp b/ets2panda/checker/types/ets/etsTupleType.cpp index cd7ffe68c1..8453e085f2 100644 --- a/ets2panda/checker/types/ets/etsTupleType.cpp +++ b/ets2panda/checker/types/ets/etsTupleType.cpp @@ -196,6 +196,7 @@ Type *ETSTupleType::Instantiate([[maybe_unused]] ArenaAllocator *allocator, [[ma { auto *const checker = relation->GetChecker()->AsETSChecker(); auto *const tupleType = allocator->New(checker, GetTupleTypesList()); + ES2PANDA_ASSERT(tupleType != nullptr); tupleType->typeFlags_ = typeFlags_; return tupleType; } diff --git a/ets2panda/checker/types/ets/etsTupleType.h b/ets2panda/checker/types/ets/etsTupleType.h index 53418a226c..f28d95d965 100644 --- a/ets2panda/checker/types/ets/etsTupleType.h +++ b/ets2panda/checker/types/ets/etsTupleType.h @@ -28,7 +28,10 @@ public: explicit ETSTupleType(ETSChecker *checker, const ArenaVector &typeList) : Type(checker::TypeFlag::ETS_TUPLE), typeList_(typeList), - wrapperType_(checker->GlobalBuiltinTupleType(typeList_.size())->AsETSObjectType()) + // NOLINTNEXTLINE(readability-implicit-bool-conversion) + wrapperType_(checker->GlobalBuiltinTupleType(typeList_.size()) != nullptr + ? checker->GlobalBuiltinTupleType(typeList_.size())->AsETSObjectType() + : nullptr) { typeFlags_ |= TypeFlag::ETS_TUPLE; } diff --git a/ets2panda/checker/types/ets/etsTypeParameter.cpp b/ets2panda/checker/types/ets/etsTypeParameter.cpp index 518a42441b..ebb370321d 100644 --- a/ets2panda/checker/types/ets/etsTypeParameter.cpp +++ b/ets2panda/checker/types/ets/etsTypeParameter.cpp @@ -127,6 +127,7 @@ Type *ETSTypeParameter::Instantiate([[maybe_unused]] ArenaAllocator *allocator, auto *const checker = relation->GetChecker()->AsETSChecker(); auto *const copiedType = checker->CreateTypeParameter(); + ES2PANDA_ASSERT(copiedType != nullptr); copiedType->AddTypeFlag(TypeFlag::GENERIC); copiedType->SetDeclNode(GetDeclNode()); copiedType->SetDefaultType(GetDefaultType()); diff --git a/ets2panda/checker/types/ets/etsUnionType.cpp b/ets2panda/checker/types/ets/etsUnionType.cpp index 7893a517a9..94aefa04f9 100644 --- a/ets2panda/checker/types/ets/etsUnionType.cpp +++ b/ets2panda/checker/types/ets/etsUnionType.cpp @@ -65,6 +65,7 @@ bool ETSUnionType::TypeRelatedToSomeType(TypeRelation *relation, Type *source, E Type *ETSUnionType::ComputeAssemblerLUB(ETSChecker *checker, ETSUnionType *un) { auto *const apparent = checker->GetApparentType(un); + ES2PANDA_ASSERT(apparent != nullptr); if (!apparent->IsETSUnionType()) { return apparent; } @@ -482,6 +483,7 @@ checker::Type *ETSUnionType::GetAssignableBuiltinType( return assignableType; } +// CC-OFFNXT(G.FUN.01, huge_method) solid logic bool ETSUnionType::ExtractType(checker::ETSChecker *checker, checker::ETSObjectType *sourceType, ArenaVector &unionTypes) noexcept { @@ -500,6 +502,7 @@ bool ETSUnionType::ExtractType(checker::ETSChecker *checker, checker::ETSObjectT constituentType = constituentType->AsETSTypeParameter()->GetConstraintType(); } else if (constituentType->HasTypeFlag(checker::TypeFlag::GENERIC)) { constituentType = constituentType->Clone(checker); + ES2PANDA_ASSERT(constituentType != nullptr); constituentType->RemoveTypeFlag(checker::TypeFlag::GENERIC); } diff --git a/ets2panda/checker/types/signature.cpp b/ets2panda/checker/types/signature.cpp index 5ced79c411..1c9991b3ad 100644 --- a/ets2panda/checker/types/signature.cpp +++ b/ets2panda/checker/types/signature.cpp @@ -35,7 +35,7 @@ Signature *Signature::Substitute(TypeRelation *relation, const Substitution *sub auto *allocator = checker->ProgramAllocator(); bool anyChange = false; SignatureInfo *newSigInfo = allocator->New(allocator); - + ES2PANDA_ASSERT(newSigInfo != nullptr); if (!signatureInfo_->typeParams.empty()) { for (auto *tparam : signatureInfo_->typeParams) { auto *newTparam = tparam->Substitute(relation, substitution); @@ -82,6 +82,7 @@ Signature *Signature::Substitute(TypeRelation *relation, const Substitution *sub Signature *Signature::CreateSignatureForSubstitute(ArenaAllocator *allocator, SignatureInfo *sigInfo, Type *returnType) { auto *result = allocator->New(sigInfo, returnType, func_); + ES2PANDA_ASSERT(result != nullptr); result->flags_ = flags_; result->internalName_ = internalName_; result->ownerObj_ = ownerObj_; @@ -124,6 +125,7 @@ Signature *Signature::Copy(ArenaAllocator *allocator, TypeRelation *relation, Gl } auto *const copiedSignature = allocator->New(copiedInfo, returnType_, func_); + ES2PANDA_ASSERT(copiedSignature != nullptr); copiedSignature->flags_ = flags_; copiedSignature->internalName_ = internalName_; copiedSignature->ownerObj_ = ownerObj_; @@ -289,6 +291,7 @@ Signature *Signature::ToArrowSignature(ETSChecker *checker) { auto *allocator = checker->ProgramAllocator(); auto *sigInfo = allocator->New(signatureInfo_, allocator); + ES2PANDA_ASSERT(sigInfo != nullptr); for (auto param : sigInfo->params) { param->SetTsType(checker->MaybeBoxType(param->TsType())); } diff --git a/ets2panda/checker/types/signature.h b/ets2panda/checker/types/signature.h index 2a4f8ec06d..12af6cd4dc 100644 --- a/ets2panda/checker/types/signature.h +++ b/ets2panda/checker/types/signature.h @@ -49,6 +49,7 @@ public: if (other->restVar != nullptr) { restVar = other->restVar->Copy(allocator, other->restVar->Declaration()); + ES2PANDA_ASSERT(restVar != nullptr); restVar->SetTsType(other->restVar->TsType()); } } diff --git a/ets2panda/checker/types/ts/interfaceType.cpp b/ets2panda/checker/types/ts/interfaceType.cpp index 724bee9caa..ff846e5d8e 100644 --- a/ets2panda/checker/types/ts/interfaceType.cpp +++ b/ets2panda/checker/types/ts/interfaceType.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 @@ -148,6 +148,7 @@ Type *InterfaceType::Instantiate(ArenaAllocator *allocator, TypeRelation *relati Type *newInterfaceType = allocator->New(allocator, name_, copiedDesc); + ES2PANDA_ASSERT(newInterfaceType != nullptr); for (auto *it : bases_) { newInterfaceType->AsObjectType()->AsInterfaceType()->AddBase( it->Instantiate(allocator, relation, globalTypes)->AsObjectType()); diff --git a/ets2panda/checker/types/ts/objectDescriptor.cpp b/ets2panda/checker/types/ts/objectDescriptor.cpp index a418e6815b..6dfe4e610e 100644 --- a/ets2panda/checker/types/ts/objectDescriptor.cpp +++ b/ets2panda/checker/types/ts/objectDescriptor.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 @@ -34,10 +34,12 @@ varbinder::LocalVariable *ObjectDescriptor::FindProperty(const util::StringView void ObjectDescriptor::Copy(ArenaAllocator *allocator, ObjectDescriptor *copiedDesc, TypeRelation *relation, GlobalTypesHolder *globalTypes) { + ES2PANDA_ASSERT(copiedDesc != nullptr); // copy by hand for (auto *it : properties) { auto *copiedProp = it->Copy(allocator, it->Declaration()); copiedProp->SetTsType(it->TsType()->Instantiate(allocator, relation, globalTypes)); + ES2PANDA_ASSERT(copiedDesc != nullptr); copiedDesc->properties.push_back(copiedProp); } diff --git a/ets2panda/checker/types/ts/unionType.cpp b/ets2panda/checker/types/ts/unionType.cpp index 8ba291ba7b..fe540ce69e 100644 --- a/ets2panda/checker/types/ts/unionType.cpp +++ b/ets2panda/checker/types/ts/unionType.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 @@ -111,6 +111,7 @@ void UnionType::RemoveDuplicatedTypes(TypeRelation *relation, ArenaVectorHasConstituentFlag(TypeFlag::ANY)) { return globalTypesHolder->GlobalAnyType(); } @@ -184,6 +185,7 @@ Type *UnionType::Instantiate(ArenaAllocator *allocator, TypeRelation *relation, Type *newUnionType = allocator->New(allocator, std::move(copiedConstituents)); + ES2PANDA_ASSERT(newUnionType != nullptr); return HandleUnionType(newUnionType->AsUnionType(), globalTypes); } } // namespace ark::es2panda::checker diff --git a/ets2panda/checker/types/typeRelation.cpp b/ets2panda/checker/types/typeRelation.cpp index 965d2172bb..69deb56a2d 100644 --- a/ets2panda/checker/types/typeRelation.cpp +++ b/ets2panda/checker/types/typeRelation.cpp @@ -121,10 +121,14 @@ bool TypeRelation::IsAssignableTo(Type *source, Type *target) return Result(true); } + ES2PANDA_ASSERT(source); + ES2PANDA_ASSERT(target); result_ = CacheLookup(source, target, checker_->AssignableResults(), RelationType::ASSIGNABLE); if (result_ == RelationResult::CACHE_MISS) { // NOTE: we support assigning T to Readonly, but do not support assigning Readonly to T // more details in spec + ES2PANDA_ASSERT(source != nullptr); + ES2PANDA_ASSERT(target != nullptr); if (source->HasTypeFlag(TypeFlag::READONLY) && !target->HasTypeFlag(TypeFlag::READONLY)) { result_ = RelationResult::FALSE; } diff --git a/ets2panda/parser/ASparser.cpp b/ets2panda/parser/ASparser.cpp index b7dbd5b0f1..9c5f9cb7cc 100644 --- a/ets2panda/parser/ASparser.cpp +++ b/ets2panda/parser/ASparser.cpp @@ -95,6 +95,7 @@ ir::Decorator *ASParser::ParseDecorator() auto *expr = ParseLeftHandSideExpression(); auto *decorator = AllocNode(expr); + ES2PANDA_ASSERT(decorator != nullptr); decorator->SetRange({start, expr->End()}); return decorator; } @@ -124,6 +125,7 @@ ir::TSTypeAliasDeclaration *ASParser::ParseTypeAliasDeclaration() const util::StringView &ident = Lexer()->GetToken().Ident(); auto *id = AllocNode(ident, Allocator()); + ES2PANDA_ASSERT(id != nullptr); id->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -343,6 +345,7 @@ std::tuple ASParser::ParsePatternElementToken(E } case lexer::TokenType::LITERAL_IDENT: { returnNode = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(returnNode != nullptr); returnNode->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -430,6 +433,7 @@ ir::Expression *ASParser::ParsePropertyDefinition([[maybe_unused]] ExpressionPar key = AllocNode(Lexer()->GetToken().Ident(), Allocator()); } + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -446,6 +450,7 @@ ir::Expression *ASParser::ParsePropertyDefinition([[maybe_unused]] ExpressionPar } auto *property = AllocNode(key, value); + ES2PANDA_ASSERT(property != nullptr); property->SetRange({key->Start(), value->End()}); return property; } @@ -570,6 +575,7 @@ ir::TypeNode *ASParser::ParseParenthesizedOrFunctionType(bool throwError) ir::TypeNode *ASParser::ParseTypeAnnotationLiteralIdentHelper(ir::TypeNode *type, TypeAnnotationParsingOptions *options) { auto *typeName = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(typeName != nullptr); typeName->SetRange(Lexer()->GetToken().Loc()); type = AllocNode(typeName, Allocator()); type->SetRange(Lexer()->GetToken().Loc()); @@ -584,6 +590,7 @@ ir::TypeNode *ASParser::ParseTypeAnnotationLiteralIdentHelper(ir::TypeNode *type } typeName = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(typeName != nullptr); typeName->SetRange(Lexer()->GetToken().Loc()); auto *next = AllocNode(typeName, Allocator()); current->SetRange(Lexer()->GetToken().Loc()); @@ -646,6 +653,7 @@ ir::TypeNode *ASParser::ParseTypeAnnotationTokens(ir::TypeNode *type, bool throw } auto *typeName = AllocNode(name, Allocator()); + ES2PANDA_ASSERT(typeName != nullptr); typeName->SetRange(Lexer()->GetToken().Loc()); type = AllocNode(typeName, Allocator()); type->SetRange(Lexer()->GetToken().Loc()); @@ -717,6 +725,7 @@ ir::TypeNode *ASParser::ParseTypeAnnotationTokenLeftSquareBracket(ir::TypeNode * util::StringView name = "Array"; auto *typeName = AllocNode(name, Allocator()); + ES2PANDA_ASSERT(typeName != nullptr); typeName->SetRange(Lexer()->GetToken().Loc()); ArenaVector params(Allocator()->Adapter()); @@ -768,6 +777,8 @@ bool ASParser::ParsePotentialNonNullExpression(ir::Expression **returnExpression } *returnExpression = AllocNode(*returnExpression); + ES2PANDA_ASSERT(*returnExpression != nullptr); + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) (*returnExpression)->SetRange({startLoc, Lexer()->GetToken().End()}); Lexer()->NextToken(); return false; @@ -814,6 +825,7 @@ bool ASParser::ParsePotentialGenericFunctionCall(ir::Expression *primaryExpr, ir lexer::SourcePosition endLoc = propertyNode->End(); *returnExpression = AllocNode(*returnExpression, propertyNode, typeParams); + ES2PANDA_ASSERT(returnExpression != nullptr); // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) (*returnExpression)->SetRange({startLoc, endLoc}); return false; @@ -845,6 +857,7 @@ ir::Expression *ASParser::ParsePotentialAsExpression(ir::Expression *primaryExpr ir::Identifier *ASParser::ParsePrimaryExpressionIdent([[maybe_unused]] ExpressionParseFlags flags) { auto *identNode = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(identNode != nullptr); identNode->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -865,6 +878,7 @@ bool ASParser::ValidateArrowFunctionRestParameter([[maybe_unused]] ir::SpreadEle return true; } +// CC-OFFNXT(huge_method[C++], G.FUN.01-CPP) solid logic ArenaVector ASParser::ParseInterfaceExtendsClause() { Lexer()->NextToken(); // eat extends keyword @@ -876,6 +890,7 @@ ArenaVector ASParser::ParseInterfaceExtendsClause() const lexer::SourcePosition &heritageStart = Lexer()->GetToken().Start(); lexer::SourcePosition heritageEnd = Lexer()->GetToken().End(); auto *extendsName = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(extendsName != nullptr); extendsName->SetRange(Lexer()->GetToken().Loc()); auto *extendsClause = AllocNode(extendsName, Allocator()); extendsClause->SetRange(Lexer()->GetToken().Loc()); @@ -942,6 +957,7 @@ ir::TSIndexSignature *ASParser::ParseIndexSignature(const lexer::SourcePosition } auto *key = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); // eat key @@ -991,12 +1007,14 @@ std::tuple ASParser::ParseInterfacePropertyKey() case lexer::TokenType::LITERAL_IDENT: { const util::StringView &ident = Lexer()->GetToken().Ident(); key = AllocNode(ident, Allocator()); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); break; } case lexer::TokenType::LITERAL_STRING: { const util::StringView &string = Lexer()->GetToken().String(); key = AllocNode(string); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); break; } @@ -1007,6 +1025,7 @@ std::tuple ASParser::ParseInterfacePropertyKey() key = AllocNode(Lexer()->GetToken().GetNumber()); } + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); break; } @@ -1102,6 +1121,7 @@ ArenaVector ASParser::ParseClassImplementClause() auto *implementsName = AllocNode(Lexer()->GetToken().Ident(), Allocator()); implementsName->SetRange(Lexer()->GetToken().Loc()); auto *implementsClause = AllocNode(implementsName, Allocator()); + ES2PANDA_ASSERT(implementsClause != nullptr); implementsClause->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -1280,6 +1300,7 @@ std::tuple ASParser::ParseComputedClassFieldOrIndexSignature(i } auto id = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(id != nullptr); id->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); // eat param @@ -1345,6 +1366,7 @@ std::tuple ASParser::Pa ThrowSyntaxError("An implementation cannot be declared in ambient contexts."); } else { body = ParseBlockStatement(); + ES2PANDA_ASSERT(body != nullptr); endLoc = body->End(); } @@ -1357,6 +1379,7 @@ ir::AstNode *ASParser::ParseImportDefaultSpecifier(ArenaVector *s Lexer()->NextToken(); // eat local name auto *specifier = AllocNode(local); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange(specifier->Local()->Range()); specifiers->push_back(specifier); @@ -1502,6 +1525,7 @@ ir::Statement *ASParser::ParseConstStatement(StatementParsingFlags flags) } auto *variableDecl = ParseVariableDeclaration(VariableParsingFlags::CONST | VariableParsingFlags::NO_SKIP_VAR_KIND); + ES2PANDA_ASSERT(variableDecl != nullptr); variableDecl->SetStart(constVarStar); ConsumeSemicolon(variableDecl); @@ -1518,6 +1542,7 @@ ir::AnnotatedExpression *ASParser::ParseVariableDeclaratorKey(VariableParsingFla const util::StringView &identStr = Lexer()->GetToken().Ident(); auto init = AllocNode(identStr, Allocator()); + ES2PANDA_ASSERT(init != nullptr); init->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -1591,6 +1616,7 @@ ir::ExportDefaultDeclaration *ASParser::ParseExportDefaultDeclaration(const lexe lexer::SourcePosition endLoc = declNode->End(); auto *exportDeclaration = AllocNode(declNode, isExportEquals); + ES2PANDA_ASSERT(exportDeclaration != nullptr); exportDeclaration->SetRange({startLoc, endLoc}); if (eatSemicolon) { @@ -1665,6 +1691,7 @@ ir::Statement *ASParser::ParseNamedExportDeclaration(const lexer::SourcePosition ArenaVector specifiers(Allocator()->Adapter()); auto *exportDeclaration = AllocNode(Allocator(), decl, std::move(specifiers)); + ES2PANDA_ASSERT(exportDeclaration != nullptr); exportDeclaration->SetRange({startLoc, decl->End()}); return exportDeclaration; @@ -1711,6 +1738,7 @@ ir::Statement *ASParser::ParseImportDeclaration([[maybe_unused]] StatementParsin lexer::SourcePosition endLoc = source->End(); auto *importDeclaration = AllocNode(source, std::move(specifiers)); + ES2PANDA_ASSERT(importDeclaration != nullptr); importDeclaration->SetRange({startLoc, endLoc}); ConsumeSemicolon(importDeclaration); diff --git a/ets2panda/parser/ETSFormattedParser.cpp b/ets2panda/parser/ETSFormattedParser.cpp index 4be9f1d50c..cfda403d42 100644 --- a/ets2panda/parser/ETSFormattedParser.cpp +++ b/ets2panda/parser/ETSFormattedParser.cpp @@ -301,6 +301,7 @@ ir::Statement *ETSParser::CreateStatement(std::string_view const sourceCode) } auto *const blockStmt = AllocNode(Allocator(), std::move(statements)); + ES2PANDA_ASSERT(blockStmt != nullptr); blockStmt->SetRange({startLoc, lexer->GetToken().End()}); for (auto *statement : blockStmt->Statements()) { @@ -378,6 +379,7 @@ ir::AstNode *ETSParser::CreateFormattedClassFieldDefinition(std::string_view sou insertingNodes_.swap(insertingNodes); auto *const property = CreateClassElement(sourceCode, DUMMY_ARRAY, ir::ClassDefinitionModifiers::NONE); + ES2PANDA_ASSERT(property != nullptr); if (!property->IsTSInterfaceBody() || property->AsTSInterfaceBody()->Body().empty()) { LogError(diagnostic::INVALID_CLASS_FIELD, {}, Lexer()->GetToken().Start()); ES2PANDA_UNREACHABLE(); @@ -394,6 +396,7 @@ ir::AstNode *ETSParser::CreateFormattedClassMethodDefinition(std::string_view so insertingNodes_.swap(insertingNodes); auto *const property = CreateClassElement(sourceCode, DUMMY_ARRAY, ir::ClassDefinitionModifiers::NONE); + ES2PANDA_ASSERT(property != nullptr); if (!property->IsMethodDefinition()) { LogError(diagnostic::INVALID_CLASS_METHOD, {}, Lexer()->GetToken().Start()); ES2PANDA_UNREACHABLE(); @@ -512,6 +515,7 @@ ir::MethodDefinition *ETSParser::CreateConstructorDefinition(ir::ModifierFlags m Lexer()->NextToken(); auto *const methodDefinition = ParseClassMethodDefinition(memberName, modifiers, true); + ES2PANDA_ASSERT(methodDefinition != nullptr); methodDefinition->SetStart(startLoc); return methodDefinition; diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index d45233034c..d2b5c61022 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -163,6 +163,7 @@ ir::ETSModule *ETSParser::ParseETSGlobalScript(lexer::SourcePosition startLoc, A auto ident = AllocNode(compiler::Signatures::ETS_GLOBAL, Allocator()); auto *etsModule = AllocNode(Allocator(), std::move(statements), ident, ir::ModuleFlag::ETSSCRIPT, GetProgram()); + ES2PANDA_ASSERT(etsModule != nullptr); etsModule->SetRange({startLoc, Lexer()->GetToken().End()}); return etsModule; } @@ -183,6 +184,7 @@ ir::ETSModule *ETSParser::ParseImportsOnly(lexer::SourcePosition startLoc, Arena auto ident = AllocNode(compiler::Signatures::ETS_GLOBAL, Allocator()); auto *etsModule = AllocNode(Allocator(), std::move(statements), ident, ir::ModuleFlag::ETSSCRIPT, GetProgram()); + ES2PANDA_ASSERT(etsModule != nullptr); etsModule->SetRange({startLoc, Lexer()->GetToken().End()}); return etsModule; } @@ -277,6 +279,7 @@ void ETSParser::ParseParseListElement(const util::ImportPathManager::ParseInfo & auto src = importData.HasSpecifiedDeclPath() ? importData.declPath : importData.resolvedSource; SourceFile sf {src, extSrc->View().Utf8(), importData.resolvedSource, false, importData.HasSpecifiedDeclPath()}; parser::Program *newProg = ParseSource(sf); + ES2PANDA_ASSERT(newProg != nullptr); if (!importData.IsImplicitPackageImported() || newProg->IsPackage()) { AddDirectImportsToDirectExternalSources(directImportsFromMainSource, newProg); // don't insert the separate modules into the programs, when we collect implicit package imports @@ -397,6 +400,7 @@ parser::Program *ETSParser::ParseSource(const SourceFile &sourceFile) { importPathManager_->MarkAsParsed(sourceFile.filePath); auto *program = Allocator()->New(Allocator(), GetProgram()->VarBinder()); + ES2PANDA_ASSERT(program != nullptr); auto esp = ExternalSourceParser(this, program); auto lexer = InitLexer(sourceFile); @@ -496,6 +500,7 @@ ir::ScriptFunction *ETSParser::ParseFunction(ParserStatus newStatus) auto *funcNode = AllocNode( Allocator(), ir::ScriptFunction::ScriptFunctionData {body, std::move(signature), funcFlags, mFlags, GetContext().GetLanguage()}); + ES2PANDA_ASSERT(funcNode != nullptr); funcNode->SetRange({startLoc, endLoc}); // clang-format on @@ -513,6 +518,7 @@ std::tuple ETSParser::P } ir::BlockStatement *body = ParseBlockStatement(); + ES2PANDA_ASSERT(body != nullptr); return {true, body, body->End(), false}; } @@ -580,6 +586,7 @@ ir::AstNode *ETSParser::ParseInnerConstructorDeclaration(ir::ModifierFlags membe memberModifiers |= ir::ModifierFlags::CONSTRUCTOR; Lexer()->NextToken(); auto *classMethod = ParseClassMethodDefinition(memberName, memberModifiers, isDefault); + ES2PANDA_ASSERT(classMethod != nullptr); classMethod->SetStart(startLoc); return classMethod; @@ -589,6 +596,7 @@ ir::Identifier *ETSParser::CreateInvokeIdentifier() { util::StringView tokenName = util::StringView {compiler::Signatures::STATIC_INVOKE_METHOD}; auto ident = AllocNode(tokenName, Allocator()); + ES2PANDA_ASSERT(ident != nullptr); ident->SetRange({Lexer()->GetToken().Start(), Lexer()->GetToken().End()}); return ident; } @@ -627,6 +635,7 @@ ir::AstNode *ETSParser::ParseInnerRest(const ArenaVector &propert auto parseClassMethod = [&memberModifiers, &startLoc, isDefault, this](ir::Identifier *methodName) { auto *classMethod = ParseClassMethodDefinition(methodName, memberModifiers, isDefault); + ES2PANDA_ASSERT(classMethod != nullptr); classMethod->SetStart(startLoc); return classMethod; }; @@ -653,6 +662,7 @@ ir::AstNode *ETSParser::ParseInnerRest(const ArenaVector &propert ArenaVector fieldDeclarations(Allocator()->Adapter()); auto *placeholder = AllocNode(std::move(fieldDeclarations)); + ES2PANDA_ASSERT(placeholder != nullptr); ParseClassFieldDefinition(memberName, memberModifiers, placeholder->BodyPtr(), isDefault); return placeholder; } @@ -749,6 +759,7 @@ ir::TSTypeAliasDeclaration *ETSParser::ParseTypeAliasDeclaration() ir::Identifier *id = ExpectIdentifier(); auto *typeAliasDecl = AllocNode(Allocator(), id); + ES2PANDA_ASSERT(typeAliasDecl != nullptr); if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_LESS_THAN) { auto options = @@ -1001,6 +1012,7 @@ ir::TypeNode *ETSParser::ParseTypeReference(TypeAnnotationParsingOptions *option } auto *typeReference = AllocNode(typeRefPart, Allocator()); + ES2PANDA_ASSERT(typeReference != nullptr); typeReference->SetRange({startPos, Lexer()->GetToken().End()}); return typeReference; } @@ -1037,6 +1049,7 @@ ir::TypeNode *ETSParser::ParseLiteralIdent(TypeAnnotationParsingOptions *options if (Lexer()->TryEatTokenFromKeywordType(lexer::TokenType::KEYW_KEYOF)) { auto *typeAnnotation = ParseTypeAnnotationNoPreferParam(options); + ES2PANDA_ASSERT(typeAnnotation != nullptr); typeAnnotation = AllocNode(typeAnnotation, Allocator()); typeAnnotation->SetRange(Lexer()->GetToken().Loc()); return typeAnnotation; @@ -1106,6 +1119,7 @@ ir::Statement *ETSParser::ParseExport(lexer::SourcePosition startLoc, ir::Modifi auto result = AllocNode(Allocator(), static_cast(nullptr), std::move(exports)); + ES2PANDA_ASSERT(result != nullptr); result->AddModifier(modifiers); return result; } @@ -1144,6 +1158,7 @@ ir::ETSPackageDeclaration *ETSParser::ParsePackageDeclaration() ir::Expression *name = ParseQualifiedName(); auto *packageDeclaration = AllocNode(name); + ES2PANDA_ASSERT(packageDeclaration != nullptr); packageDeclaration->SetRange({startLoc, Lexer()->GetToken().End()}); ConsumeSemicolon(packageDeclaration); @@ -1171,6 +1186,7 @@ ir::ETSImportDeclaration *ETSParser::ParseImportPathBuildImport(ArenaVectorSetRange(Lexer()->GetToken().Loc()); auto *const importDeclaration = AllocNode( errorLiteral, util::ImportPathManager::ImportMetadata {}, std::move(specifiers), importKind); + ES2PANDA_ASSERT(importDeclaration != nullptr); importDeclaration->SetRange({startLoc, errorLiteral->End()}); return importDeclaration; } @@ -1186,6 +1202,7 @@ ir::ETSImportDeclaration *ETSParser::ParseImportPathBuildImport(ArenaVector(GetContext().GetProgram()), importFlags); + ES2PANDA_ASSERT(importDeclaration != nullptr); importDeclaration->SetRange({startLoc, importPathStringLiteral->End()}); ConsumeSemicolon(importDeclaration); return importDeclaration; @@ -1247,6 +1264,7 @@ ArenaVector ETSParser::ParseImportDeclarations() Lexer()->Rewind(pos); auto *const importDeclDefault = ParseImportPathBuildImport(std::move(defaultSpecifiers), true, startLoc, importKind); + ES2PANDA_ASSERT(importDeclDefault != nullptr); if (!importDeclDefault->IsBrokenStatement()) { util::Helpers::CheckDefaultImport(statements); statements.push_back(importDeclDefault->AsETSImportDeclaration()); @@ -1268,6 +1286,7 @@ ir::ExportNamedDeclaration *ETSParser::ParseSingleExportForAnonymousConst(ir::Mo ir::Expression *constantExpression = ParseExpression(); auto *exported = AllocNode(compiler::Signatures::EXPORT_DEFAULT_CONSTANT_ANONYMOUSLY, Allocator()); + ES2PANDA_ASSERT(exported != nullptr); exported->SetRange(Lexer()->GetToken().Loc()); ArenaVector exports(Allocator()->Adapter()); @@ -1278,6 +1297,7 @@ ir::ExportNamedDeclaration *ETSParser::ParseSingleExportForAnonymousConst(ir::Mo auto result = AllocNode(Allocator(), static_cast(nullptr), std::move(exports)); + ES2PANDA_ASSERT(result != nullptr); result->AddModifier(modifiers); ConsumeSemicolon(result); @@ -1296,6 +1316,7 @@ ir::ExportNamedDeclaration *ETSParser::ParseSingleExport(ir::ModifierFlags modif return nullptr; } auto *exported = AllocNode(token.Ident(), Allocator()); + ES2PANDA_ASSERT(exported != nullptr); exported->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); // eat exported variable name @@ -1305,6 +1326,7 @@ ir::ExportNamedDeclaration *ETSParser::ParseSingleExport(ir::ModifierFlags modif exports.emplace_back(AllocNode(exported, ParseNamedExport(&token))); auto result = AllocNode(Allocator(), static_cast(nullptr), std::move(exports)); + ES2PANDA_ASSERT(result != nullptr); result->AddModifier(modifiers); ConsumeSemicolon(result); @@ -1345,9 +1367,11 @@ void ETSParser::ParseNamedSpecifiesDefaultImport(ArenaVector(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(imported != nullptr); imported->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); auto *specifier = AllocNode(imported); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange({imported->Start(), imported->End()}); util::Helpers::CheckDefaultImportedName(*resultDefault, specifier, fileName); @@ -1363,8 +1387,10 @@ bool ETSParser::ParseNamedSpecifiesImport(ArenaVector *re ir::Expression *constantExpression = ParseUnaryOrPrefixUpdateExpression(); auto *exported = AllocNode(compiler::Signatures::EXPORT_DEFAULT_CONSTANT_ANONYMOUSLY, Allocator()); + ES2PANDA_ASSERT(exported != nullptr); exported->SetRange(Lexer()->GetToken().Loc()); auto *exportedAnonyConst = AllocNode(exported, exported->Clone(Allocator(), nullptr)); + ES2PANDA_ASSERT(exportedAnonyConst != nullptr); exportedAnonyConst->SetConstantExpression(constantExpression); exportedAnonyConst->SetDefault(); resultExportDefault->emplace_back(exportedAnonyConst); @@ -1390,6 +1416,7 @@ bool ETSParser::ParseNamedSpecifiesImport(ArenaVector *re } auto *specifier = AllocNode(imported, local); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange({imported->Start(), local->End()}); util::Helpers::CheckImportedName(*result, specifier, fileName); @@ -1452,6 +1479,7 @@ void ETSParser::ParseNameSpaceSpecifier(ArenaVector *specifiers, if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_COMMA || Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_FROM) { auto *specifier = AllocNode(local); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange({namespaceStart, Lexer()->GetToken().End()}); specifiers->push_back(specifier); return; @@ -1461,6 +1489,7 @@ void ETSParser::ParseNameSpaceSpecifier(ArenaVector *specifiers, local = ParseNamedImport(&Lexer()->GetToken()); auto *specifier = AllocNode(local); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange({namespaceStart, Lexer()->GetToken().End()}); specifiers->push_back(specifier); @@ -1474,6 +1503,7 @@ ir::AstNode *ETSParser::ParseImportDefaultSpecifier(ArenaVector * } auto *imported = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(imported != nullptr); imported->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); // Eat import specifier. @@ -1536,6 +1566,7 @@ ir::AnnotatedExpression *ETSParser::GetAnnotatedExpressionFromParam() } auto *const restIdent = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(restIdent != nullptr); restIdent->SetRange(Lexer()->GetToken().Loc()); parameter = AllocNode(ir::AstNodeType::REST_ELEMENT, Allocator(), restIdent); @@ -1644,6 +1675,7 @@ ir::Expression *ETSParser::ParseFunctionParameter() if (Lexer()->TryEatTokenType(lexer::TokenType::PUNCTUATOR_COLON)) { TypeAnnotationParsingOptions options = TypeAnnotationParsingOptions::REPORT_ERROR; ir::TypeNode *typeAnnotation = ParseTypeAnnotation(&options); + ES2PANDA_ASSERT(typeAnnotation != nullptr); if (typeAnnotation->IsBrokenTypeNode()) { // the compiler can't process "declare class A { static foo(x: {key: string}[]):void; }" correctly // and resolve "{key: string}" as function body, so skip invalid types @@ -1662,12 +1694,14 @@ ir::Expression *ETSParser::ParseFunctionParameter() ir::Expression *ETSParser::CreateParameterThis(ir::TypeNode *typeAnnotation) { auto *paramIdent = AllocNode(varbinder::TypedBinder::MANDATORY_PARAM_THIS, Allocator()); + ES2PANDA_ASSERT(paramIdent != nullptr); paramIdent->SetRange(Lexer()->GetToken().Loc()); typeAnnotation->SetParent(paramIdent); paramIdent->SetTsTypeAnnotation(typeAnnotation); auto *paramExpression = AllocNode(paramIdent, false, Allocator()); + ES2PANDA_ASSERT(paramExpression != nullptr); paramExpression->SetRange({paramIdent->Start(), paramIdent->End()}); return paramExpression; @@ -1676,6 +1710,7 @@ ir::Expression *ETSParser::CreateParameterThis(ir::TypeNode *typeAnnotation) ir::AnnotatedExpression *ETSParser::ParseVariableDeclaratorKey([[maybe_unused]] VariableParsingFlags flags) { ir::Identifier *init = ExpectIdentifier(); + ES2PANDA_ASSERT(init != nullptr); ir::TypeNode *typeAnnotation = nullptr; if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_QUESTION_MARK) { if ((flags & VariableParsingFlags::FOR_OF) != 0U) { @@ -1770,6 +1805,7 @@ void ETSParser::ParseCatchParamTypeAnnotation([[maybe_unused]] ir::AnnotatedExpr if (Lexer()->TryEatTokenType(lexer::TokenType::PUNCTUATOR_COLON)) { TypeAnnotationParsingOptions options = TypeAnnotationParsingOptions::REPORT_ERROR; if (auto *typeAnnotation = ParseTypeAnnotation(&options); typeAnnotation != nullptr) { + ES2PANDA_ASSERT(param != nullptr); typeAnnotation->SetParent(param); param->SetTsTypeAnnotation(typeAnnotation); } @@ -1828,6 +1864,7 @@ ir::Expression *ETSParser::ParseExpressionOrTypeAnnotation(lexer::TokenType type if (Lexer()->GetToken().Type() == lexer::TokenType::LITERAL_NULL) { auto *typeAnnotation = AllocNode(); + ES2PANDA_ASSERT(typeAnnotation != nullptr); typeAnnotation->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -1975,6 +2012,7 @@ ir::AstNode *ETSParser::ParseAmbientSignature(const lexer::SourcePosition &start auto dummyNode = AllocNode(compiler::Signatures::AMBIENT_INDEXER, indexName, returnType, ir::DummyNodeFlag::INDEXER); + ES2PANDA_ASSERT(dummyNode != nullptr); dummyNode->SetRange({startPos, Lexer()->GetToken().End()}); Lexer()->NextToken(); // eat return type return dummyNode; @@ -2024,7 +2062,9 @@ ir::TSTypeParameter *ETSParser::ParseTypeParameter([[maybe_unused]] TypeAnnotati auto *typeParam = AllocNode(paramIdent, constraint, defaultType, varianceModifier, Allocator()); + ES2PANDA_ASSERT(typeParam); + ES2PANDA_ASSERT(typeParam != nullptr); ApplyAnnotationsToNode(typeParam, std::move(annotations), saveLoc); typeParam->SetRange({startLoc, Lexer()->GetToken().End()}); return typeParam; @@ -2118,6 +2158,7 @@ ir::FunctionDeclaration *ETSParser::ParseFunctionDeclaration(bool canBeAnonymous ir::ScriptFunction *func = ParseFunction(newStatus | ParserStatus::FUNCTION_DECLARATION | ParserStatus::ALLOW_RECEIVER); + ES2PANDA_ASSERT(func != nullptr); if (funcIdentNode != nullptr) { // Error processing. func->SetIdent(funcIdentNode); } @@ -2146,10 +2187,12 @@ ir::FunctionDeclaration *ETSParser::ParseAccessorWithReceiver(ir::ModifierFlags ParserStatus::EXTENSION_ACCESSOR; ir::Identifier *funcIdentNode = ExpectIdentifier(); + ES2PANDA_ASSERT(funcIdentNode != nullptr); CheckRestrictedBinding(funcIdentNode->Name(), funcIdentNode->Start()); ir::ScriptFunction *func = isGetter ? ParseFunction(newStatus | ParserStatus::NEED_RETURN_TYPE) : ParseFunction(newStatus); + ES2PANDA_ASSERT(func != nullptr); size_t paramCount = func->Params().size(); size_t getterValidParamCount = 1; size_t setterValidParamCount = 2; diff --git a/ets2panda/parser/ETSparserAnnotations.cpp b/ets2panda/parser/ETSparserAnnotations.cpp index 1f37cf4605..f5f9d5c3a9 100644 --- a/ets2panda/parser/ETSparserAnnotations.cpp +++ b/ets2panda/parser/ETSparserAnnotations.cpp @@ -60,6 +60,7 @@ ir::Expression *ETSParser::ParseAnnotationName() if (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_PERIOD_PERIOD_PERIOD) { Lexer()->Rewind(save); expr = ExpectIdentifier(); + ES2PANDA_ASSERT(expr != nullptr); setAnnotation(expr->AsIdentifier()); return expr; } @@ -67,9 +68,11 @@ ir::Expression *ETSParser::ParseAnnotationName() if (Lexer()->Lookahead() == '.') { auto opt = TypeAnnotationParsingOptions::NO_OPTS; expr = ParseTypeReference(&opt); + ES2PANDA_ASSERT(expr != nullptr); setAnnotation(expr->AsETSTypeReference()->Part()->GetIdent()); } else { expr = ExpectIdentifier(); + ES2PANDA_ASSERT(expr != nullptr); setAnnotation(expr->AsIdentifier()); } @@ -94,6 +97,7 @@ ir::AnnotationDeclaration *ETSParser::ParseAnnotationDeclaration(ir::ModifierFla lexer::SourcePosition endLoc = Lexer()->GetToken().End(); auto *annotationDecl = AllocNode(expr, std::move(properties), Allocator()); + ES2PANDA_ASSERT(annotationDecl != nullptr); annotationDecl->SetRange({startLoc, endLoc}); annotationDecl->AddModifier(flags); return annotationDecl; @@ -133,7 +137,9 @@ ArenaVector ETSParser::ParseAnnotationProperties(ir::ModifierFlag // Probably we can seek for identifier till the enclosing right brace (staring after the next comma?) // if the simplest case failed. auto const pos = Lexer()->Save(); - if (auto *fieldName1 = ExpectIdentifier(); fieldName1->IsErrorPlaceHolder()) { + auto *fieldName1 = ExpectIdentifier(); + ES2PANDA_ASSERT(fieldName1 != nullptr); + if (fieldName1->IsErrorPlaceHolder()) { Lexer()->Rewind(pos); } else { fieldName = fieldName1; @@ -216,6 +222,7 @@ ir::AstNode *ETSParser::ParseAnnotationProperty(ir::Identifier *fieldName, ir::M memberModifiers |= ir::ModifierFlags::ABSTRACT; auto *field = AllocNode(fieldName, initializer, typeAnnotation, memberModifiers, Allocator(), false); + ES2PANDA_ASSERT(field != nullptr); field->SetRange({fieldName->Start(), initializer != nullptr ? initializer->End() : endLoc}); return field; } @@ -287,9 +294,12 @@ void ETSParser::ApplyAnnotationsToSpecificNodeType(ir::AstNode *node, ArenaVecto lexer::SourcePosition pos) { switch (node->Type()) { - case ir::AstNodeType::METHOD_DEFINITION: - node->AsMethodDefinition()->Function()->SetAnnotations(std::move(annotations)); + case ir::AstNodeType::METHOD_DEFINITION: { + auto *func = node->AsMethodDefinition()->Function(); + ES2PANDA_ASSERT(func != nullptr); + func->SetAnnotations(std::move(annotations)); break; + } case ir::AstNodeType::CLASS_DECLARATION: node->AsClassDeclaration()->Definition()->SetAnnotations(std::move(annotations)); break; @@ -357,6 +367,7 @@ void ETSParser::ApplyAnnotationsToSpecificNodeType(ir::AstNode *node, ArenaVecto static lexer::SourcePosition GetExpressionEndLoc(ir::Expression *expr) { + ES2PANDA_ASSERT(expr != nullptr); if (expr->IsIdentifier()) { return expr->AsIdentifier()->End(); } @@ -398,6 +409,7 @@ ir::AnnotationUsage *ETSParser::ParseAnnotationUsage() } auto *annotationUsage = AllocNode(expr, std::move(properties)); + ES2PANDA_ASSERT(annotationUsage != nullptr); annotationUsage->AddModifier(flags); annotationUsage->SetRange({startLoc, Lexer()->GetToken().End()}); return annotationUsage; diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index ed1e1bc050..a1cbd70d36 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -525,6 +525,7 @@ void ETSParser::ParseClassFieldDefinition(ir::Identifier *fieldName, ir::Modifie ValidateFieldModifiers(modifiers, optionalField, initializer, start); auto *field = AllocNode(fieldName, initializer, typeAnnotation, modifiers, Allocator(), false); + ES2PANDA_ASSERT(field != nullptr); field->SetDefaultAccessModifier(isDefault); if (optionalField) { field->AddModifier(ir::ModifierFlags::OPTIONAL); @@ -554,8 +555,10 @@ ir::MethodDefinition *ETSParser::ParseClassMethodDefinition(ir::Identifier *meth } ir::ScriptFunction *func = ParseFunction(newStatus); + ES2PANDA_ASSERT(func != nullptr); func->SetIdent(methodName); auto *funcExpr = AllocNode(func); + ES2PANDA_ASSERT(funcExpr != nullptr); funcExpr->SetRange(func->Range()); func->AddModifier(modifiers); @@ -576,11 +579,13 @@ ir::MethodDefinition *ETSParser::ParseClassMethod(ClassElementDescriptor *desc, } ir::ScriptFunction *func = ParseFunction(desc->newStatus); + ES2PANDA_ASSERT(func != nullptr); if (propName->IsIdentifier()) { func->SetIdent(propName->AsIdentifier()->Clone(Allocator(), nullptr)); } auto *funcExpr = AllocNode(func); + ES2PANDA_ASSERT(funcExpr != nullptr); funcExpr->SetRange(func->Range()); if (desc->methodKind == ir::MethodDefinitionKind::SET) { @@ -730,7 +735,9 @@ void *ETSParser::ApplyAnnotationsToClassElement(ir::AstNode *property, ArenaVect for (auto *node : property->AsTSInterfaceBody()->Body()) { ArenaVector cloneAnnotations(Allocator()->Adapter()); for (auto *annotationUsage : annotations) { - cloneAnnotations.push_back(annotationUsage->Clone(Allocator(), node)->AsAnnotationUsage()); + auto cloneAnnotationUsage = annotationUsage->Clone(Allocator(), node); + ES2PANDA_ASSERT(cloneAnnotationUsage != nullptr); + cloneAnnotations.push_back(cloneAnnotationUsage->AsAnnotationUsage()); } ApplyAnnotationsToNode(node, std::move(cloneAnnotations), pos); } @@ -785,6 +792,7 @@ ir::MethodDefinition *ETSParser::ParseClassGetterSetterMethod(const ArenaVector< : ir::MethodDefinitionKind::SET; Lexer()->NextToken(); // eat get/set auto *methodName = ExpectIdentifier(); + ES2PANDA_ASSERT(methodName != nullptr); if (desc.methodKind == ir::MethodDefinitionKind::GET) { methodName->SetAccessor(); } else { @@ -821,17 +829,19 @@ ir::MethodDefinition *ETSParser::ParseInterfaceGetterSetterMethod(const ir::Modi return nullptr; } method->AddModifier(ir::ModifierFlags::PUBLIC); + auto id = method->Id(); + ES2PANDA_ASSERT(id != nullptr); method->SetRange({Lexer()->GetToken().Start(), method->Id()->End()}); if (methodKind == ir::MethodDefinitionKind::GET) { - method->Id()->SetAccessor(); + id->SetAccessor(); method->Function()->AddFlag(ir::ScriptFunctionFlags::GETTER); } else { - method->Id()->SetMutator(); + id->SetMutator(); method->Function()->AddFlag(ir::ScriptFunctionFlags::SETTER); } method->AddModifier(ir::ModifierFlags::PUBLIC); - method->Function()->SetIdent(method->Id()->Clone(Allocator(), nullptr)); + method->Function()->SetIdent(id->Clone(Allocator(), nullptr)); method->Function()->AddModifier(method->Modifiers()); bool hasReturn = method->Function()->ReturnTypeAnnotation() != nullptr; @@ -871,6 +881,7 @@ ir::TSInterfaceDeclaration *ETSParser::ParseInterfaceBody(ir::Identifier *name, } auto *body = AllocNode(std::move(members)); + ES2PANDA_ASSERT(body != nullptr); body->SetRange({bodyStart, Lexer()->GetToken().End()}); const auto isExternal = IsExternal(); @@ -893,6 +904,7 @@ ir::Statement *ETSParser::ParseInterfaceDeclaration(bool isStatic) auto *id = ExpectIdentifier(false, true); auto *declNode = ParseInterfaceBody(id, isStatic); + ES2PANDA_ASSERT(declNode != nullptr); declNode->SetRange({interfaceStart, Lexer()->GetToken().End()}); return declNode; @@ -949,6 +961,7 @@ ir::ClassDefinition *ETSParser::ParseClassDefinition(ir::ClassDefinitionModifier auto *classDefinition = AllocNode(identNode, typeParamDecl, superTypeParams, std::move(implements), ctor, superClass, std::move(properties), modifiers, flags, GetContext().GetLanguage()); + ES2PANDA_ASSERT(classDefinition != nullptr); classDefinition->SetRange(bodyRange); @@ -1031,6 +1044,7 @@ ir::AstNode *ETSParser::ParseInterfaceField() auto parseClassMethod = [&fieldModifiers, &startLoc, this](ir::Identifier *methodName) { auto *classMethod = ParseClassMethodDefinition(methodName, fieldModifiers, false); + ES2PANDA_ASSERT(classMethod != nullptr); classMethod->SetStart(startLoc); return classMethod; }; @@ -1055,6 +1069,7 @@ ir::AstNode *ETSParser::ParseInterfaceField() } auto *field = AllocNode(name, nullptr, typeAnnotation->Clone(Allocator(), nullptr), fieldModifiers, Allocator(), false); + ES2PANDA_ASSERT(field != nullptr); if (optionalField) { field->AddModifier(ir::ModifierFlags::OPTIONAL); } @@ -1080,6 +1095,7 @@ static lexer::SourcePosition GetEndLoc(ir::BlockStatement *body, ir::ScriptFunct return lexer->GetToken().End(); } +// CC-OFFNXT(huge_method[C++], G.FUN.01-CPP) solid logic ir::MethodDefinition *ETSParser::ParseInterfaceMethod(ir::ModifierFlags flags, ir::MethodDefinitionKind methodKind) { ir::Identifier *name = nullptr; @@ -1124,7 +1140,7 @@ ir::MethodDefinition *ETSParser::ParseInterfaceMethod(ir::ModifierFlags flags, i auto *func = AllocNode( Allocator(), ir::ScriptFunction::ScriptFunctionData {body, std::move(signature), functionContext.Flags(), flags, GetContext().GetLanguage()}); - + ES2PANDA_ASSERT(func != nullptr); if ((flags & ir::ModifierFlags::STATIC) == 0 && body == nullptr) { func->AddModifier(ir::ModifierFlags::ABSTRACT); } @@ -1132,6 +1148,7 @@ ir::MethodDefinition *ETSParser::ParseInterfaceMethod(ir::ModifierFlags flags, i func->SetRange({startLoc, GetEndLoc(body, func, Lexer())}); auto *funcExpr = AllocNode(func); + ES2PANDA_ASSERT(funcExpr != nullptr); funcExpr->SetRange(func->Range()); func->AddFlag(ir::ScriptFunctionFlags::METHOD); @@ -1209,6 +1226,7 @@ ir::AstNode *ETSParser::ParseTypeLiteralOrInterfaceMember() LogError(diagnostic::READONLY_INTERFACE_METHOD, {}, startLoc); } auto *method = ParseInterfaceMethod(modifiers, ir::MethodDefinitionKind::METHOD); + ES2PANDA_ASSERT(method != nullptr); method->SetStart(startLoc); return method; } @@ -1265,6 +1283,7 @@ bool ETSParser::CheckClassElement(ir::AstNode *property, [[maybe_unused]] ir::Me void ETSParser::CheckPredefinedMethods(ir::ScriptFunction const *function, const lexer::SourcePosition &position) { + ES2PANDA_ASSERT(function != nullptr); auto const name = function->Id()->Name(); auto const checkAsynchronous = [this, function, &name, &position]() -> void { @@ -1325,7 +1344,9 @@ void ETSParser::CreateImplicitConstructor([[maybe_unused]] ir::MethodDefinition auto *methodDef = BuildImplicitConstructor(ir::ClassDefinitionModifiers::SET_CTOR_ID, startLoc); if ((flags & ir::ModifierFlags::DECLARE) != 0) { - methodDef->Function()->AddFlag(ir::ScriptFunctionFlags::EXTERNAL); + auto func = methodDef->Function(); + ES2PANDA_ASSERT(func != nullptr); + func->AddFlag(ir::ScriptFunctionFlags::EXTERNAL); } properties.push_back(methodDef); } diff --git a/ets2panda/parser/ETSparserEnums.cpp b/ets2panda/parser/ETSparserEnums.cpp index b38077398c..c4f6989c72 100644 --- a/ets2panda/parser/ETSparserEnums.cpp +++ b/ets2panda/parser/ETSparserEnums.cpp @@ -167,6 +167,7 @@ ir::TSEnumDeclaration *ETSParser::ParseEnumMembers(ir::Identifier *const key, co auto *const enumDeclaration = AllocNode( Allocator(), key, std::move(members), ir::TSEnumDeclaration::ConstructorFlags {isConst, isStatic, InAmbientContext()}); + ES2PANDA_ASSERT(enumDeclaration != nullptr); if (InAmbientContext()) { enumDeclaration->AddModifier(ir::ModifierFlags::DECLARE); } diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index 7c0bd342e9..f8425e7790 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -75,6 +75,7 @@ ir::Expression *ETSParser::ParseFunctionParameterExpression(ir::AnnotatedExpress } paramExpression = AllocNode(paramIdent->AsIdentifier(), defaultValue, Allocator()); + ES2PANDA_ASSERT(paramExpression != nullptr); std::string value = GetArgumentsSourceView(Lexer(), lexerPos); paramExpression->SetLexerSaved(util::UString(value, Allocator()).View()); @@ -160,6 +161,7 @@ ir::Expression *ETSParser::ParseUnaryOrPrefixUpdateExpression(ExpressionParseFla ir::Expression *argument = ResolveArgumentUnaryExpr(flags); if (operatorType == lexer::TokenType::KEYW_AWAIT) { auto *awaitExpr = AllocNode(argument); + ES2PANDA_ASSERT(awaitExpr != nullptr); awaitExpr->SetRange({start, argument->End()}); return awaitExpr; } @@ -205,6 +207,7 @@ ir::Expression *ETSParser::ParsePropertyDefinition(ExpressionParseFlags flags) ir::Expression *key = ParsePropertyKey(flags); ir::Expression *value = ParsePropertyValue(&propertyKind, &methodStatus, flags); + ES2PANDA_ASSERT(value != nullptr); lexer::SourcePosition end = value->End(); ir::Expression *returnProperty = nullptr; @@ -252,6 +255,7 @@ ir::Expression *ETSParser::ParseDefaultPrimaryExpression(ExpressionParseFlags fl if (Lexer()->GetToken().Type() == lexer::TokenType::KEYW_CLASS || IsStructKeyword()) { Lexer()->NextToken(); // eat 'class' and 'struct' auto *classLiteral = AllocNode(potentialType); + ES2PANDA_ASSERT(classLiteral != nullptr); classLiteral->SetRange({startLoc, Lexer()->GetToken().End()}); return classLiteral; } @@ -470,6 +474,7 @@ ir::ArrowFunctionExpression *ETSParser::ParseArrowFunctionExpression() auto newStatus = ParserStatus::ARROW_FUNCTION | ParserStatus::ALLOW_RECEIVER; auto *func = ParseFunction(newStatus); auto *arrowFuncNode = AllocNode(func, Allocator()); + ES2PANDA_ASSERT(arrowFuncNode != nullptr); arrowFuncNode->SetRange(func->Range()); return arrowFuncNode; } @@ -595,6 +600,7 @@ ir::Expression *ETSParser::ParsePotentialAsExpression(ir::Expression *primaryExp } auto *asExpression = AllocNode(primaryExpr, type, false); + ES2PANDA_ASSERT(asExpression != nullptr); asExpression->SetRange(primaryExpr->Range()); return asExpression; } @@ -662,6 +668,7 @@ ir::Expression *ETSParser::ParseNewExpression() } while (Lexer()->GetToken().Type() == lexer::TokenType::PUNCTUATOR_LEFT_SQUARE_BRACKET); auto *multiArray = AllocNode(typeReference, std::move(dimensions)); + ES2PANDA_ASSERT(multiArray != nullptr); multiArray->SetRange({start, endLoc}); return multiArray; } @@ -689,6 +696,7 @@ ir::Expression *ETSParser::ParseAsyncExpression() return nullptr; } auto *arrowFuncNode = AllocNode(func, Allocator()); + ES2PANDA_ASSERT(arrowFuncNode != nullptr); arrowFuncNode->SetRange(func->Range()); return arrowFuncNode; } @@ -699,6 +707,7 @@ ir::Expression *ETSParser::ParseAwaitExpression() Lexer()->NextToken(); ir::Expression *argument = ParseExpression(); auto *awaitExpression = AllocNode(argument); + ES2PANDA_ASSERT(awaitExpression != nullptr); awaitExpression->SetRange({start, Lexer()->GetToken().End()}); return awaitExpression; } @@ -725,6 +734,7 @@ bool ETSParser::ParsePotentialNonNullExpression(ir::Expression **expression, con } const auto nonNullExpr = AllocNode(*expression); + ES2PANDA_ASSERT(nonNullExpr != nullptr); nonNullExpr->SetRange({startLoc, Lexer()->GetToken().End()}); *expression = nonNullExpr; diff --git a/ets2panda/parser/ETSparserJsDocInfo.cpp b/ets2panda/parser/ETSparserJsDocInfo.cpp index 8ddf1be020..e0dbcb2344 100644 --- a/ets2panda/parser/ETSparserJsDocInfo.cpp +++ b/ets2panda/parser/ETSparserJsDocInfo.cpp @@ -237,9 +237,12 @@ void ETSParser::ApplyJsDocInfoToSpecificNodeType(ir::AstNode *node, ArenaVector< } switch (node->Type()) { - case ir::AstNodeType::METHOD_DEFINITION: - node->AsMethodDefinition()->Function()->SetJsDocInformation(std::move(jsDocInformation)); + case ir::AstNodeType::METHOD_DEFINITION: { + auto *func = node->AsMethodDefinition()->Function(); + ES2PANDA_ASSERT(func != nullptr); + func->SetJsDocInformation(std::move(jsDocInformation)); break; + } case ir::AstNodeType::CLASS_DECLARATION: node->AsClassDeclaration()->Definition()->SetJsDocInformation(std::move(jsDocInformation)); break; diff --git a/ets2panda/parser/ETSparserNamespaces.cpp b/ets2panda/parser/ETSparserNamespaces.cpp index 53e582726f..bf8a1f3662 100644 --- a/ets2panda/parser/ETSparserNamespaces.cpp +++ b/ets2panda/parser/ETSparserNamespaces.cpp @@ -60,6 +60,7 @@ ir::Statement *ETSParser::ParseNamespace(ir::ModifierFlags flags) } auto start = Lexer()->GetToken().Start(); ir::ETSModule *ns = ParseNamespaceImp(flags); + ES2PANDA_ASSERT(ns != nullptr); ns->SetRange({start, Lexer()->GetToken().Start()}); return ns; } @@ -76,6 +77,7 @@ ir::ETSModule *ETSParser::ParseNamespaceImp(ir::ModifierFlags flags) auto start = Lexer()->GetToken().Start(); child = AllocNode(Allocator(), ArenaVector(Allocator()->Adapter()), ExpectIdentifier(), ir::ModuleFlag::NAMESPACE, globalProgram_); + ES2PANDA_ASSERT(child != nullptr); child->SetParent(parent); child->SetRange({start, Lexer()->GetToken().Start()}); child->AddModifier(ir::ModifierFlags::EXPORT); diff --git a/ets2panda/parser/ETSparserStatements.cpp b/ets2panda/parser/ETSparserStatements.cpp index 3a3bcf9294..065a0a5966 100644 --- a/ets2panda/parser/ETSparserStatements.cpp +++ b/ets2panda/parser/ETSparserStatements.cpp @@ -191,6 +191,7 @@ ir::Statement *ETSParser::ParseTopLevelDeclStatement(StatementParsingFlags flags switch (token.Type()) { case lexer::TokenType::KEYW_FUNCTION: { result = ParseFunctionDeclaration(false, memberModifiers); + ES2PANDA_ASSERT(result != nullptr); result->SetStart(startLoc); break; } @@ -339,6 +340,7 @@ ir::Statement *ETSParser::ParseTryStatement() ArenaVector> finalizerInsertions(Allocator()->Adapter()); auto *tryStatement = AllocNode(body, std::move(catchClauses), finalizer, finalizerInsertions); + ES2PANDA_ASSERT(tryStatement != nullptr); tryStatement->SetRange({startLoc, endLoc}); ConsumeSemicolon(tryStatement); diff --git a/ets2panda/parser/ETSparserTypes.cpp b/ets2panda/parser/ETSparserTypes.cpp index ba9bc16a21..06ff498422 100644 --- a/ets2panda/parser/ETSparserTypes.cpp +++ b/ets2panda/parser/ETSparserTypes.cpp @@ -99,6 +99,7 @@ ir::TypeNode *ETSParser::ParsePrimitiveType(TypeAnnotationParsingOptions *option } auto *const typeAnnotation = AllocNode(type, Allocator()); + ES2PANDA_ASSERT(typeAnnotation != nullptr); typeAnnotation->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); return typeAnnotation; @@ -121,6 +122,7 @@ ir::TypeNode *ETSParser::ParseUnionType(ir::TypeNode *const firstType) auto const endLoc = types.back()->End(); auto *const unionType = AllocNode(std::move(types), Allocator()); + ES2PANDA_ASSERT(unionType != nullptr); unionType->SetRange({firstType->Start(), endLoc}); return unionType; } @@ -180,6 +182,7 @@ ir::TypeNode *ETSParser::ParseWildcardType(TypeAnnotationParsingOptions *options } auto *wildcardType = AllocNode(typeReference, varianceModifier, Allocator()); + ES2PANDA_ASSERT(wildcardType != nullptr); wildcardType->SetRange({varianceStartLoc, typeReference == nullptr ? varianceEndLoc : typeReference->End()}); return wildcardType; @@ -261,6 +264,7 @@ ir::TypeNode *ETSParser::ParseETSTupleType(TypeAnnotationParsingOptions *const o lexer::SourcePosition endLoc; ParseList(lexer::TokenType::PUNCTUATOR_RIGHT_SQUARE_BRACKET, lexer::NextTokenFlags::NONE, parseElem, &endLoc, true); + ES2PANDA_ASSERT(tupleType != nullptr); tupleType->SetTypeAnnotationsList(std::move(tupleTypeList)); tupleType->SetRange({startLoc, endLoc}); @@ -306,6 +310,7 @@ ir::TypeNode *ETSParser::ParsePotentialFunctionalType(TypeAnnotationParsingOptio return nullptr; } +// CC-OFFNXT(huge_method[C++], G.FUN.01-CPP) solid logic // Just to reduce the size of ParseTypeAnnotation(...) method std::pair ETSParser::GetTypeAnnotationFromToken(TypeAnnotationParsingOptions *options) { @@ -322,18 +327,21 @@ std::pair ETSParser::GetTypeAnnotationFromToken(TypeAnnota switch (tokenType) { case lexer::TokenType::LITERAL_NULL: { auto typeAnnotation = AllocNode(Allocator()); + ES2PANDA_ASSERT(typeAnnotation != nullptr); typeAnnotation->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); return std::make_pair(typeAnnotation, true); } case lexer::TokenType::KEYW_UNDEFINED: { auto typeAnnotation = AllocNode(Allocator()); + ES2PANDA_ASSERT(typeAnnotation != nullptr); typeAnnotation->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); return std::make_pair(typeAnnotation, true); } case lexer::TokenType::LITERAL_STRING: { auto typeAnnotation = AllocNode(Lexer()->GetToken().String(), Allocator()); + ES2PANDA_ASSERT(typeAnnotation != nullptr); typeAnnotation->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); return std::make_pair(typeAnnotation, true); @@ -428,6 +436,7 @@ ir::TypeNode *ETSParser::ParseThisType(TypeAnnotationParsingOptions *options) } auto *const thisType = AllocNode(Allocator()); + ES2PANDA_ASSERT(thisType != nullptr); thisType->SetRange(tokenLoc); return thisType; @@ -553,6 +562,7 @@ ir::TypeNode *ETSParser::ParseMultilineString() Lexer()->ScanTemplateStringEnd(); auto typeAnnotation = AllocNode(multilineStr, Allocator()); + ES2PANDA_ASSERT(typeAnnotation != nullptr); typeAnnotation->SetRange({startPos, Lexer()->GetToken().End()}); Lexer()->NextToken(); diff --git a/ets2panda/parser/TSparser.cpp b/ets2panda/parser/TSparser.cpp index 164f34c170..9d47819baa 100644 --- a/ets2panda/parser/TSparser.cpp +++ b/ets2panda/parser/TSparser.cpp @@ -149,6 +149,7 @@ ir::Decorator *TSParser::ParseDecorator() } auto *identNode = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(identNode != nullptr); identNode->SetRange(Lexer()->GetToken().Loc()); expr = @@ -161,6 +162,7 @@ ir::Decorator *TSParser::ParseDecorator() } auto *result = AllocNode(expr); + ES2PANDA_ASSERT(result != nullptr); result->SetRange({start, expr->End()}); return result; @@ -199,6 +201,7 @@ ir::TSTypeAliasDeclaration *TSParser::ParseTypeAliasDeclaration() const util::StringView &ident = Lexer()->GetToken().Ident(); auto *id = AllocNode(ident, Allocator()); + ES2PANDA_ASSERT(id != nullptr); id->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -441,6 +444,7 @@ ir::TypeNode *TSParser::ParseThisType(bool throwError) } auto *returnType = AllocNode(Allocator()); + ES2PANDA_ASSERT(returnType != nullptr); returnType->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -544,6 +548,7 @@ ir::TypeNode *TSParser::ParseTypeOperatorOrTypeReference() auto *inferType = AllocNode(typeParam, Allocator()); + ES2PANDA_ASSERT(inferType != nullptr); inferType->SetRange({inferStart, Lexer()->GetToken().End()}); return inferType; @@ -638,6 +643,7 @@ ir::TSTupleType *TSParser::ParseTupleType() Lexer()->NextToken(); // eat ']' auto *tupleType = AllocNode(std::move(elements), Allocator()); + ES2PANDA_ASSERT(tupleType != nullptr); tupleType->SetRange({tupleStart, tupleEnd}); return tupleType; } @@ -858,6 +864,7 @@ ir::TSTypePredicate *TSParser::ParseTypePredicate() if (isAsserts && Lexer()->GetToken().KeywordType() != lexer::TokenType::KEYW_IS) { endPos = parameterName->End(); result = AllocNode(parameterName, typeAnnotation, isAsserts, Allocator()); + ES2PANDA_ASSERT(result != nullptr); result->SetRange({startPos, endPos}); return result; } @@ -869,7 +876,7 @@ ir::TSTypePredicate *TSParser::ParseTypePredicate() endPos = typeAnnotation->End(); result = AllocNode(parameterName, typeAnnotation, isAsserts, Allocator()); - + ES2PANDA_ASSERT(result != nullptr); result->SetRange({startPos, endPos}); return result; @@ -938,6 +945,7 @@ ir::TSArrayType *TSParser::ParseArrayType(ir::TypeNode *elementType) lexer::SourcePosition startLoc = elementType->Start(); auto *arrayType = AllocNode(elementType, Allocator()); + ES2PANDA_ASSERT(arrayType != nullptr); arrayType->SetRange({startLoc, endLoc}); return arrayType; @@ -976,6 +984,7 @@ ir::TSUnionType *TSParser::ParseUnionType(ir::TypeNode *type, bool restrictExten auto *unionType = AllocNode(std::move(types), Allocator()); auto *typeVar = varbinder::Scope::CreateVar(Allocator(), "__type", varbinder::VariableFlags::TYPE, unionType); + ES2PANDA_ASSERT(unionType != nullptr); unionType->SetVariable(typeVar); unionType->SetRange({startLoc, endLoc}); @@ -1020,6 +1029,7 @@ ir::TSIntersectionType *TSParser::ParseIntersectionType(ir::Expression *type, bo auto *intersectionType = AllocNode(std::move(types), Allocator()); auto *typeVar = varbinder::Scope::CreateVar(Allocator(), "__type", varbinder::VariableFlags::TYPE, intersectionType); + ES2PANDA_ASSERT(intersectionType != nullptr); intersectionType->SetVariable(typeVar); intersectionType->SetRange({startLoc, endLoc}); @@ -1041,6 +1051,7 @@ private: return parser->AllocNode(bigintNode, parser->Allocator()); } auto *numberNode = parser->AllocNode(lexer->GetToken().GetNumber()); + CHECK_NOT_NULL(numberNode); numberNode->SetRange(lexer->GetToken().Loc()); return parser->AllocNode(numberNode, parser->Allocator()); @@ -1136,6 +1147,7 @@ ir::TypeNode *TSParser::ParseBasicType() return typeAnnotation; } +// CC-OFFNXT(huge_method[C++], G.FUN.01-CPP) solid logic ir::TypeNode *TSParser::ParseParenthesizedOrFunctionType(ir::TypeNode *typeAnnotation, bool throwError) { if (typeAnnotation != nullptr) { @@ -1200,6 +1212,7 @@ ir::TypeNode *TSParser::ParseParenthesizedOrFunctionType(ir::TypeNode *typeAnnot } auto *result = AllocNode(type, Allocator()); + ES2PANDA_ASSERT(result != nullptr); result->SetRange({typeStart, endLoc}); return result; @@ -1466,6 +1479,7 @@ bool TSParser::IsNamedFunctionExpression() ir::Identifier *TSParser::ParsePrimaryExpressionIdent([[maybe_unused]] ExpressionParseFlags flags) { auto *identNode = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(identNode != nullptr); identNode->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -1508,6 +1522,7 @@ ir::TSSignatureDeclaration *TSParser::ParseSignatureMember(bool isCallSignature) : ir::TSSignatureDeclaration::TSSignatureDeclarationKind::CONSTRUCT_SIGNATURE; auto *signatureMember = AllocNode( kind, ir::FunctionSignature(typeParamDecl, std::move(params), typeAnnotation)); + ES2PANDA_ASSERT(signatureMember != nullptr); signatureMember->SetRange({memberStartLoc, Lexer()->GetToken().End()}); return signatureMember; @@ -1534,6 +1549,7 @@ ir::TSIndexSignature *TSParser::ParseIndexSignature(const lexer::SourcePosition ES2PANDA_ASSERT(Lexer()->GetToken().Type() == lexer::TokenType::LITERAL_IDENT); auto *key = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); // eat key @@ -1581,12 +1597,14 @@ std::tuple TSParser::ParseInterfacePropertyKey() case lexer::TokenType::LITERAL_IDENT: { const util::StringView &ident = Lexer()->GetToken().Ident(); key = AllocNode(ident, Allocator()); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); break; } case lexer::TokenType::LITERAL_STRING: { const util::StringView &string = Lexer()->GetToken().String(); key = AllocNode(string); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); break; } @@ -1597,6 +1615,7 @@ std::tuple TSParser::ParseInterfacePropertyKey() key = AllocNode(Lexer()->GetToken().GetNumber()); } + ES2PANDA_ASSERT(key != nullptr); key->SetRange(Lexer()->GetToken().Loc()); break; } @@ -1905,6 +1924,7 @@ ir::MethodDefinition *TSParser::ParseClassMethod(ClassElementDescriptor *desc, ir::ScriptFunction *func = ParseFunction(desc->newStatus); + ES2PANDA_ASSERT(func != nullptr); if (func->IsOverload() && !desc->decorators.empty()) { ThrowSyntaxError("A decorator can only decorate a method implementation, not an overload.", desc->decorators.front()->Start()); @@ -2089,6 +2109,7 @@ std::tuple TSParser::Pa ThrowSyntaxError("An implementation cannot be declared in ambient contexts."); } else { body = ParseBlockStatement(); + ES2PANDA_ASSERT(body != nullptr); endLoc = body->End(); } @@ -2110,6 +2131,7 @@ ir::AstNode *TSParser::ParseImportDefaultSpecifier(ArenaVector *s } auto *specifier = AllocNode(local); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange(specifier->Local()->Range()); specifiers->push_back(specifier); diff --git a/ets2panda/parser/context/classPrivateContext.cpp b/ets2panda/parser/context/classPrivateContext.cpp index a902e95455..d191b3b597 100644 --- a/ets2panda/parser/context/classPrivateContext.cpp +++ b/ets2panda/parser/context/classPrivateContext.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 @@ -24,7 +24,9 @@ namespace ark::es2panda::parser { bool ClassPrivateContext::AddElement(const ir::ClassElement *elem) { bool newPropIsStatic = elem->IsStatic(); - util::StringView newPropName = elem->Id()->Name(); + auto id = elem->Id(); + ES2PANDA_ASSERT(id); + util::StringView newPropName = id->Name(); ir::MethodDefinitionKind newPropMethodKind = ir::MethodDefinitionKind::METHOD; if (elem->IsMethodDefinition()) { @@ -61,7 +63,9 @@ bool ClassPrivateContext::AddElement(const ir::ClassElement *elem) bool ClassPrivateContext::FindElement(const ir::Identifier *elem) const { for (const auto *it : elements_) { - if (it->Id()->Name().Compare(elem->Name()) == 0) { + auto id = it->Id(); + ES2PANDA_ASSERT(id); + if (id->Name().Compare(elem->Name()) == 0) { return true; } } diff --git a/ets2panda/parser/expressionParser.cpp b/ets2panda/parser/expressionParser.cpp index 37c03683eb..d1f53aa414 100644 --- a/ets2panda/parser/expressionParser.cpp +++ b/ets2panda/parser/expressionParser.cpp @@ -114,6 +114,7 @@ ir::YieldExpression *ParserImpl::ParseYieldExpression() } auto *yieldNode = AllocNode(argument, isDelegate); + ES2PANDA_ASSERT(yieldNode); yieldNode->SetRange({startLoc, endLoc}); return yieldNode; @@ -208,6 +209,7 @@ ir::ArrayExpression *ParserImpl::ParseArrayExpression(ExpressionParseFlags flags auto nodeType = inPattern ? ir::AstNodeType::ARRAY_PATTERN : ir::AstNodeType::ARRAY_EXPRESSION; auto *arrayExpressionNode = AllocNode(nodeType, std::move(elements), Allocator(), trailingComma); + ES2PANDA_ASSERT(arrayExpressionNode); arrayExpressionNode->SetRange({startLoc, endLoc}); if (inPattern) { @@ -321,6 +323,7 @@ ir::ArrowFunctionExpression *ParserImpl::ParseArrowFunctionExpressionBody(ArrowF lexer_->NextToken(); auto statements = ParseStatementList(); body = AllocNode(Allocator(), std::move(statements)); + ES2PANDA_ASSERT(body); body->SetRange({bodyStart, lexer_->GetToken().End()}); // This check is redundant since we have ParseStatementList() @@ -574,6 +577,7 @@ ir::Expression *ParserImpl::CreateBinaryAssignmentExpression(ir::Expression *ass { auto *binaryAssignmentExpression = AllocNode(lhsExpression, assignmentExpression, tokenType); + ES2PANDA_ASSERT(binaryAssignmentExpression); binaryAssignmentExpression->SetRange({lhsExpression->Start(), assignmentExpression->End()}); return binaryAssignmentExpression; @@ -589,6 +593,7 @@ ir::Expression *ParserImpl::ParseAssignmentExpression(ir::Expression *lhsExpress ir::Expression *consequent = ParseAssignmentExpressionHelper(); ir::Expression *alternate = ParseExpression(); auto *conditionalExpr = AllocNode(lhsExpression, consequent, alternate); + ES2PANDA_ASSERT(conditionalExpr); conditionalExpr->SetRange({lhsExpression->Start(), alternate->End()}); return conditionalExpr; } @@ -702,6 +707,7 @@ ir::Expression *ParserImpl::ParseAssignmentEqualExpression(const lexer::TokenTyp auto *binaryAssignmentExpression = AllocNode(lhsExpression, assignmentExpression, tokenType); + ES2PANDA_ASSERT(binaryAssignmentExpression); binaryAssignmentExpression->SetRange({lhsExpression->Start(), assignmentExpression->End()}); return binaryAssignmentExpression; @@ -791,6 +797,7 @@ ir::Expression *ParserImpl::ParseNewExpression() if (lexer_->GetToken().Type() != lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS) { lexer::SourcePosition endLoc = callee->End(); auto *newExprNode = AllocNode(callee, std::move(arguments)); + ES2PANDA_ASSERT(newExprNode); newExprNode->SetRange({start, endLoc}); return newExprNode; @@ -816,6 +823,7 @@ ir::Expression *ParserImpl::ParseNewExpression() &endLoc, true); auto *newExprNode = AllocNode(callee, std::move(arguments)); + ES2PANDA_ASSERT(newExprNode); newExprNode->SetRange({start, endLoc}); return newExprNode; @@ -844,6 +852,7 @@ ir::MetaProperty *ParserImpl::ParsePotentialNewTarget() } auto *metaProperty = AllocNode(ir::MetaProperty::MetaPropertyKind::NEW_TARGET); + ES2PANDA_ASSERT(metaProperty); metaProperty->SetRange(loc); lexer_->NextToken(); return metaProperty; @@ -856,6 +865,7 @@ ir::MetaProperty *ParserImpl::ParsePotentialNewTarget() ir::Identifier *ParserImpl::ParsePrimaryExpressionIdent([[maybe_unused]] ExpressionParseFlags flags) { auto *identNode = AllocNode(lexer_->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(identNode); identNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -868,6 +878,7 @@ ir::BooleanLiteral *ParserImpl::ParseBooleanLiteral() lexer_->GetToken().Type() == lexer::TokenType::LITERAL_FALSE); auto *booleanNode = AllocNode(lexer_->GetToken().Type() == lexer::TokenType::LITERAL_TRUE); + ES2PANDA_ASSERT(booleanNode); booleanNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -878,6 +889,7 @@ ir::NullLiteral *ParserImpl::ParseNullLiteral() { ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::LITERAL_NULL); auto *nullNode = AllocNode(); + ES2PANDA_ASSERT(nullNode); nullNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -896,6 +908,7 @@ ir::Literal *ParserImpl::ParseNumberLiteral() numberNode = AllocNode(lexer_->GetToken().GetNumber()); } + ES2PANDA_ASSERT(numberNode); numberNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -907,6 +920,7 @@ ir::CharLiteral *ParserImpl::ParseCharLiteral() ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::LITERAL_CHAR); auto *charNode = AllocNode(lexer_->GetToken().Utf16()); + ES2PANDA_ASSERT(charNode); charNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -918,6 +932,7 @@ ir::StringLiteral *ParserImpl::ParseStringLiteral() ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::LITERAL_STRING); auto *stringNode = AllocNode(lexer_->GetToken().String()); + ES2PANDA_ASSERT(stringNode); stringNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -928,6 +943,7 @@ ir::UndefinedLiteral *ParserImpl::ParseUndefinedLiteral() { ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::KEYW_UNDEFINED); auto *undefinedNode = AllocNode(); + ES2PANDA_ASSERT(undefinedNode); undefinedNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -939,6 +955,7 @@ ir::ThisExpression *ParserImpl::ParseThisExpression() ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::KEYW_THIS); auto *thisExprNode = AllocNode(); + ES2PANDA_ASSERT(thisExprNode); thisExprNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -958,6 +975,7 @@ ir::RegExpLiteral *ParserImpl::ParseRegularExpression() reParser.ParsePattern(); auto *regexpNode = AllocNode(regexp.patternStr, regexp.flags, regexp.flagsStr); + ES2PANDA_ASSERT(regexpNode); regexpNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -969,6 +987,7 @@ ir::SuperExpression *ParserImpl::ParseSuperExpression() ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::KEYW_SUPER); auto *superExprNode = AllocNode(); + ES2PANDA_ASSERT(superExprNode); superExprNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); // eat super @@ -1017,6 +1036,7 @@ ir::Expression *ParserImpl::ParseHashMaskOperator() } auto *privateIdent = AllocNode(lexer_->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(privateIdent); privateIdent->SetPrivate(true); lexer_->NextToken(); @@ -1038,6 +1058,7 @@ ir::Expression *ParserImpl::ParseClassExpression() } auto *classExpr = AllocNode(classDefinition); + ES2PANDA_ASSERT(classExpr); classExpr->SetRange({startLoc, classDefinition->End()}); return classExpr; @@ -1276,6 +1297,7 @@ void ParserImpl::CreateAmendedBinaryExpression(ir::Expression *const left, ir::E amended->SetParent(nullptr); // Next line overwrite parent auto *binaryExpr = AllocNode(left, amended, operatorType); + ES2PANDA_ASSERT(binaryExpr); binaryExpr->SetRange({left->Start(), amended->End()}); SetAmendedChildExpression(right, binaryExpr); } @@ -1334,6 +1356,7 @@ ir::Expression *ParserImpl::ParseBinaryExpression(ir::Expression *left, const le } const lexer::SourcePosition &endPos = rightExpr->End(); rightExpr = AllocNode(left, rightExpr, operatorType); + ES2PANDA_ASSERT(rightExpr); rightExpr->SetRange({left->Start(), endPos}); } @@ -1399,6 +1422,7 @@ ir::CallExpression *ParserImpl::ParseCallExpression(ir::Expression *callee, bool callExpr = AllocNode(callee, std::move(arguments), nullptr, isOptionalChain, trailingComma); } + ES2PANDA_ASSERT(callExpr); callExpr->SetRange({callee->Start(), endLoc}); isOptionalChain = false; @@ -1433,6 +1457,7 @@ ir::Expression *ParserImpl::ParseOptionalChain(ir::Expression *leftSideExpr) returnExpression = AllocNode(leftSideExpr, identNode, ir::MemberExpressionKind::PROPERTY_ACCESS, false, true); + ES2PANDA_ASSERT(returnExpression); returnExpression->SetRange({leftSideExpr->Start(), identNode->End()}); lexer_->NextToken(); } @@ -1449,6 +1474,7 @@ ir::Expression *ParserImpl::ParseOptionalChain(ir::Expression *leftSideExpr) returnExpression = AllocNode(leftSideExpr, propertyNode, ir::MemberExpressionKind::ELEMENT_ACCESS, true, true); + ES2PANDA_ASSERT(returnExpression); returnExpression->SetRange({leftSideExpr->Start(), endLoc}); lexer_->NextToken(); } @@ -1472,6 +1498,7 @@ ir::ArrowFunctionExpression *ParserImpl::ParsePotentialArrowExpression(ir::Expre switch (lexer_->GetToken().Type()) { case lexer::TokenType::KEYW_FUNCTION: { *returnExpression = ParseFunctionExpression(ParserStatus::ASYNC_FUNCTION); + ES2PANDA_ASSERT(returnExpression); (*returnExpression)->SetStart(startLoc); break; } @@ -1547,6 +1574,7 @@ ir::MemberExpression *ParserImpl::ParseElementAccess(ir::Expression *primaryExpr auto *memberExpr = AllocNode(primaryExpr, propertyNode, ir::MemberExpressionKind::ELEMENT_ACCESS, true, isOptional); + ES2PANDA_ASSERT(memberExpr); memberExpr->SetRange({primaryExpr->Start(), lexer_->GetToken().End()}); lexer_->NextToken(); return memberExpr; @@ -1560,12 +1588,14 @@ ir::MemberExpression *ParserImpl::ParsePrivatePropertyAccess(ir::Expression *pri ValidatePrivateIdentifier(); auto *privateIdent = AllocNode(lexer_->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(privateIdent); privateIdent->SetRange({memberStart, lexer_->GetToken().End()}); privateIdent->SetPrivate(true); lexer_->NextToken(); auto *memberExpr = AllocNode(primaryExpr, privateIdent, ir::MemberExpressionKind::PROPERTY_ACCESS, false, false); + ES2PANDA_ASSERT(memberExpr); memberExpr->SetRange({primaryExpr->Start(), privateIdent->End()}); return memberExpr; } @@ -1575,6 +1605,7 @@ ir::MemberExpression *ParserImpl::ParsePropertyAccess(ir::Expression *primaryExp ir::Identifier *ident = ExpectIdentifier(true); auto *memberExpr = AllocNode(primaryExpr, ident, ir::MemberExpressionKind::PROPERTY_ACCESS, false, isOptional); + ES2PANDA_ASSERT(memberExpr); memberExpr->SetRange({primaryExpr->Start(), ident->End()}); return memberExpr; @@ -1637,9 +1668,11 @@ ir::Expression *ParserImpl::ParsePostPrimaryExpressionBackTick(ir::Expression *r const lexer::SourcePosition startLoc) { ir::TemplateLiteral *propertyNode = ParseTemplateLiteral(); + ES2PANDA_ASSERT(propertyNode); lexer::SourcePosition endLoc = propertyNode->End(); returnExpression = AllocNode(returnExpression, propertyNode, nullptr); + ES2PANDA_ASSERT(returnExpression); returnExpression->SetRange({startLoc, endLoc}); return returnExpression; @@ -1700,6 +1733,7 @@ ir::Expression *ParserImpl::SetupChainExpr(ir::Expression *const top, lexer::Sou lexer::SourcePosition endLoc = expr->End(); auto chain = AllocNode(expr); + ES2PANDA_ASSERT(chain); chain->SetRange({startLoc, endLoc}); if (expr == top) { @@ -1748,6 +1782,7 @@ ir::Expression *ParserImpl::ParseMemberExpression(bool ignoreCallExpression, Exp returnExpression = AllocNode(returnExpression, lexer_->GetToken().Type(), false); + ES2PANDA_ASSERT(returnExpression); returnExpression->SetRange({start, lexer_->GetToken().End()}); lexer_->NextToken(); } @@ -1798,6 +1833,7 @@ ir::Expression *ParserImpl::ParsePatternElement(ExpressionParseFlags flags, bool ir::Expression *rightNode = ParseExpression(); auto *assignmentExpression = AllocNode( ir::AstNodeType::ASSIGNMENT_PATTERN, returnNode, rightNode, lexer::TokenType::PUNCTUATOR_SUBSTITUTION); + ES2PANDA_ASSERT(assignmentExpression); assignmentExpression->SetRange({returnNode->Start(), rightNode->End()}); return assignmentExpression; @@ -1904,6 +1940,7 @@ ir::Property *ParserImpl::ParseShorthandProperty(const lexer::LexerPosition *sta const util::StringView &ident = lexer_->GetToken().Ident(); auto *key = AllocNode(ident, Allocator()); + ES2PANDA_ASSERT(key); key->SetRange(lexer_->GetToken().Loc()); ir::Expression *value = AllocNode(ident, Allocator()); @@ -1930,6 +1967,7 @@ ir::Property *ParserImpl::ParseShorthandProperty(const lexer::LexerPosition *sta } auto *returnProperty = AllocNode(key, value); + ES2PANDA_ASSERT(returnProperty); returnProperty->SetRange({start, end}); return returnProperty; @@ -1996,6 +2034,7 @@ ir::Expression *ParserImpl::ParsePropertyKey(ExpressionParseFlags flags) case lexer::TokenType::LITERAL_IDENT: { const util::StringView &ident = lexer_->GetToken().Ident(); key = AllocNode(ident, Allocator()); + ES2PANDA_ASSERT(key); key->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); return key; @@ -2003,6 +2042,7 @@ ir::Expression *ParserImpl::ParsePropertyKey(ExpressionParseFlags flags) case lexer::TokenType::LITERAL_STRING: { const util::StringView &string = lexer_->GetToken().String(); key = AllocNode(string); + ES2PANDA_ASSERT(key); key->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); return key; @@ -2013,6 +2053,7 @@ ir::Expression *ParserImpl::ParsePropertyKey(ExpressionParseFlags flags) } else { key = AllocNode(lexer_->GetToken().GetNumber()); } + ES2PANDA_ASSERT(key); key->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); return key; @@ -2083,6 +2124,7 @@ ir::Expression *ParserImpl::ParsePropertyValue(const ir::PropertyKind *propertyK size_t paramsSize = methodDefinitonNode->Params().size(); auto *value = AllocNode(methodDefinitonNode); + ES2PANDA_ASSERT(value); value->SetRange(methodDefinitonNode->Range()); if (*propertyKind == ir::PropertyKind::SET && paramsSize != 1) { @@ -2132,10 +2174,12 @@ ir::Expression *ParserImpl::ParsePropertyDefinition([[maybe_unused]] ExpressionP } ir::Expression *value = ParsePropertyValue(&propertyKind, &methodStatus, flags); + ES2PANDA_ASSERT(value); lexer::SourcePosition end = value->End(); auto *returnProperty = AllocNode(propertyKind, key, value, methodStatus != ParserStatus::NO_OPTS, isComputed); + ES2PANDA_ASSERT(returnProperty); returnProperty->SetRange({start, end}); return returnProperty; @@ -2211,6 +2255,7 @@ ir::ObjectExpression *ParserImpl::ParseObjectExpression(ExpressionParseFlags fla auto nodeType = inPattern ? ir::AstNodeType::OBJECT_PATTERN : ir::AstNodeType::OBJECT_EXPRESSION; auto *objectExpression = AllocNode(nodeType, Allocator(), std::move(properties), trailingComma); + ES2PANDA_ASSERT(objectExpression); objectExpression->SetRange({start, lexer_->GetToken().End()}); lexer_->NextToken(); @@ -2257,6 +2302,7 @@ ir::SequenceExpression *ParserImpl::ParseSequenceExpression(ir::Expression *star lexer::SourcePosition end = sequence.back()->End(); auto *sequenceNode = AllocNode(std::move(sequence)); + ES2PANDA_ASSERT(sequenceNode); sequenceNode->SetRange({start, end}); return sequenceNode; @@ -2317,6 +2363,7 @@ ir::Expression *ParserImpl::ParseUnaryOrPrefixUpdateExpression(ExpressionParseFl returnExpr = AllocNode(argument, operatorType); } + ES2PANDA_ASSERT(returnExpr); returnExpr->SetRange({start, end}); return returnExpr; @@ -2347,6 +2394,7 @@ ir::Expression *ParserImpl::ParseImportExpression() } auto *metaProperty = AllocNode(ir::MetaProperty::MetaPropertyKind::IMPORT_META); + ES2PANDA_ASSERT(metaProperty); metaProperty->SetRange({startLoc, endLoc}); lexer_->NextToken(); @@ -2399,6 +2447,7 @@ ir::FunctionExpression *ParserImpl::ParseFunctionExpression(ParserStatus newStat functionNode->SetStart(startLoc); auto *funcExpr = AllocNode(ident, functionNode); + ES2PANDA_ASSERT(funcExpr); funcExpr->SetRange(functionNode->Range()); return funcExpr; diff --git a/ets2panda/parser/expressionTSParser.cpp b/ets2panda/parser/expressionTSParser.cpp index 86f1232891..fe80a876b9 100644 --- a/ets2panda/parser/expressionTSParser.cpp +++ b/ets2panda/parser/expressionTSParser.cpp @@ -137,6 +137,7 @@ ir::Expression *TSParser::ParsePotentialAsExpression(ir::Expression *expr) lexer::SourcePosition startLoc = expr->Start(); auto *asExpr = AllocNode(expr, typeAnnotation, isConst); + ES2PANDA_ASSERT(asExpr); asExpr->SetRange({startLoc, Lexer()->GetToken().End()}); if (Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_AS) { @@ -169,6 +170,7 @@ ir::AnnotatedExpression *TSParser::ParsePatternElementGetReturnNode(ExpressionPa } case lexer::TokenType::LITERAL_IDENT: { ir::AnnotatedExpression *returnNode = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(returnNode); if (returnNode->AsIdentifier()->Decorators().empty()) { returnNode->SetRange(Lexer()->GetToken().Loc()); @@ -340,6 +342,7 @@ ir::Expression *TSParser::ParseModuleReference() Lexer()->NextToken(); // eat ')' } else { result = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(result); result->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -357,6 +360,7 @@ ir::TSTypeReference *TSParser::ParseConstExpression() identRef->SetRange(Lexer()->GetToken().Loc()); auto *typeReference = AllocNode(identRef, nullptr, Allocator()); + ES2PANDA_ASSERT(typeReference); typeReference->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -379,6 +383,8 @@ bool TSParser::ParsePotentialNonNullExpression(ir::Expression **returnExpression } *returnExpression = AllocNode(*returnExpression); + ES2PANDA_ASSERT(*returnExpression); + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) (*returnExpression)->SetRange({startLoc, Lexer()->GetToken().End()}); Lexer()->NextToken(); return false; @@ -435,6 +441,8 @@ private: } }; +// NOLINTNEXTLINE(readability-function-size) +// CC-OFFNXT(huge_method[C++], G.FUN.01-CPP) solid logic ir::ArrowFunctionExpression *TSParser::ParsePotentialArrowExpression(ir::Expression **returnExpression, const lexer::SourcePosition &startLoc) { @@ -443,6 +451,7 @@ ir::ArrowFunctionExpression *TSParser::ParsePotentialArrowExpression(ir::Express switch (Lexer()->GetToken().Type()) { case lexer::TokenType::KEYW_FUNCTION: { *returnExpression = ParseFunctionExpression(ParserStatus::ASYNC_FUNCTION); + ES2PANDA_ASSERT(*returnExpression); (*returnExpression)->SetStart(startLoc); break; } diff --git a/ets2panda/parser/parserImpl.cpp b/ets2panda/parser/parserImpl.cpp index ade0b8337b..d3ff773b2c 100644 --- a/ets2panda/parser/parserImpl.cpp +++ b/ets2panda/parser/parserImpl.cpp @@ -82,6 +82,7 @@ void ParserImpl::ParseProgram(ScriptKind kind) auto statements = ParseStatementList(StatementParsingFlags::STMT_GLOBAL_LEXICAL); auto *blockStmt = AllocNode(Allocator(), std::move(statements)); + ES2PANDA_ASSERT(blockStmt); blockStmt->SetRange({startLoc, lexer_->GetToken().End()}); program_->SetAst(blockStmt); @@ -337,6 +338,7 @@ std::tuple ParserImpl::ParseComputedClassFieldOrIndexSignature return {true, false, false}; } +// CC-OFFNXT(huge_method[C++], G.FUN.01-CPP) solid logic ir::Expression *ParserImpl::ParseClassKey(ClassElementDescriptor *desc) { ir::Expression *propName = nullptr; @@ -350,6 +352,7 @@ ir::Expression *ParserImpl::ParseClassKey(ClassElementDescriptor *desc) ValidateClassKey(desc); propName = AllocNode(lexer_->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(propName); propName->SetRange(lexer_->GetToken().Loc()); propName->AsIdentifier()->SetPrivate(desc->isPrivateIdent); break; @@ -366,6 +369,7 @@ ir::Expression *ParserImpl::ParseClassKey(ClassElementDescriptor *desc) } propName = AllocNode(lexer_->GetToken().String()); + ES2PANDA_ASSERT(propName); propName->SetRange(lexer_->GetToken().Loc()); break; } @@ -377,6 +381,7 @@ ir::Expression *ParserImpl::ParseClassKey(ClassElementDescriptor *desc) } else { propName = AllocNode(lexer_->GetToken().GetNumber()); } + ES2PANDA_ASSERT(propName); propName->SetRange(lexer_->GetToken().Loc()); break; @@ -456,6 +461,7 @@ ir::MethodDefinition *ParserImpl::ParseClassMethod(ClassElementDescriptor *desc, ir::ScriptFunction *func = ParseFunction(desc->newStatus); auto *funcExpr = AllocNode(func); + ES2PANDA_ASSERT(funcExpr); funcExpr->SetRange(func->Range()); if (desc->methodKind == ir::MethodDefinitionKind::SET) { @@ -481,6 +487,7 @@ ir::ClassElement *ParserImpl::ParseClassProperty(ClassElementDescriptor *desc, const ArenaVector &properties, ir::Expression *propName, ir::TypeNode *typeAnnotation) { + ES2PANDA_ASSERT(propName); lexer::SourcePosition propEnd = propName->End(); ir::ClassElement *property = nullptr; @@ -588,6 +595,7 @@ ir::ClassElement *ParserImpl::ParseClassStaticBlock() auto *funcExpr = AllocNode(func); auto *staticBlock = AllocNode(funcExpr, Allocator()); + ES2PANDA_ASSERT(staticBlock); staticBlock->SetRange({startPos, lexer_->GetToken().End()}); lexer_->NextToken(); // eat '}' @@ -684,7 +692,7 @@ ir::MethodDefinition *ParserImpl::BuildImplicitConstructor(ir::ClassDefinitionMo auto *ctor = AllocNode(ir::MethodDefinitionKind::CONSTRUCTOR, key, funcExpr, ir::ModifierFlags::NONE, Allocator(), false); - + ES2PANDA_ASSERT(ctor != nullptr); const auto rangeImplicitContstuctor = lexer::SourceRange(startLoc, startLoc); ctor->IterateRecursively( [&rangeImplicitContstuctor](ir::AstNode *node) -> void { node->SetRange(rangeImplicitContstuctor); }); @@ -703,7 +711,9 @@ void ParserImpl::CreateImplicitConstructor(ir::MethodDefinition *&ctor, ctor = BuildImplicitConstructor(modifiers, startLoc); if ((flags & ir::ModifierFlags::DECLARE) != 0) { - ctor->Function()->AddFlag(ir::ScriptFunctionFlags::EXTERNAL); + auto *ctorFunc = ctor->Function(); + ES2PANDA_ASSERT(ctorFunc); + ctorFunc->AddFlag(ir::ScriptFunctionFlags::EXTERNAL); } } @@ -789,6 +799,7 @@ ir::ClassDefinition *ParserImpl::ParseClassDefinition(ir::ClassDefinitionModifie auto *classDefinition = AllocNode(identNode, nullptr, superTypeParams, std::move(implements), ctor, superClass, std::move(properties), modifiers, flags, GetContext().GetLanguage()); + ES2PANDA_ASSERT(classDefinition); classDefinition->SetInternalName(privateBinding.View()); classDefinition->SetRange(bodyRange); @@ -939,6 +950,7 @@ std::tuple ParserImpl:: } ir::BlockStatement *body = ParseBlockStatement(); + ES2PANDA_ASSERT(body); return {true, body, body->End(), false}; } @@ -1004,6 +1016,7 @@ ir::ScriptFunction *ParserImpl::ParseFunction(ParserStatus newStatus) functionContext.Flags(), // CC-OFFNXT(G.FMT.02-CPP) project code style {}, // CC-OFFNXT(G.FMT.02-CPP) project code style context_.GetLanguage()}); // CC-OFF(G.FMT.02-CPP) project code style + ES2PANDA_ASSERT(funcNode); funcNode->SetRange({startLoc, endLoc}); @@ -1033,6 +1046,7 @@ ir::SpreadElement *ParserImpl::ParseSpreadElement(ExpressionParseFlags flags) auto nodeType = inPattern ? ir::AstNodeType::REST_ELEMENT : ir::AstNodeType::SPREAD_ELEMENT; auto *spreadElementNode = AllocNode(nodeType, Allocator(), argument); + ES2PANDA_ASSERT(spreadElementNode); spreadElementNode->SetRange({startLocation, argument->End()}); return spreadElementNode; } @@ -1273,6 +1287,7 @@ ir::Identifier *ParserImpl::ExpectIdentifier([[maybe_unused]] bool isReference, } auto *ident = AllocNode(tokenName, Allocator()); + ES2PANDA_ASSERT(ident); // NOTE: here actual token can be changed! ident->SetRange({tokenStart, lexer_->GetToken().End()}); lexer_->NextToken(); @@ -1448,6 +1463,7 @@ ir::Identifier *ParserImpl::AllocBrokenExpression(const lexer::SourcePosition &p ir::Identifier *ParserImpl::AllocBrokenExpression(const lexer::SourceRange &range) { auto *node = AllocNode(Allocator()); + ES2PANDA_ASSERT(node); node->SetRange(range); return node; } @@ -1460,6 +1476,7 @@ ir::TypeNode *ParserImpl::AllocBrokenType(const lexer::SourcePosition &pos) ir::TypeNode *ParserImpl::AllocBrokenType(const lexer::SourceRange &range) { auto node = AllocNode(Allocator()); + ES2PANDA_ASSERT(node); node->SetRange(range); return node; } diff --git a/ets2panda/parser/program/program.cpp b/ets2panda/parser/program/program.cpp index 60d533c526..403d7d8830 100644 --- a/ets2panda/parser/program/program.cpp +++ b/ets2panda/parser/program/program.cpp @@ -32,7 +32,7 @@ Program::Program(ArenaAllocator *allocator, varbinder::VarBinder *varbinder) varbinder_(varbinder), externalSources_(allocator_->Adapter()), directExternalSources_(allocator_->Adapter()), - extension_(varbinder->Extension()), + extension_(varbinder != nullptr ? varbinder->Extension() : ScriptExtension::INVALID), etsnolintCollection_(allocator_->Adapter()), cfg_(allocator_->New(allocator_)), functionScopes_(allocator_->Adapter()) @@ -98,6 +98,7 @@ void Program::SetPackageInfo(const util::StringView &name, util::ModuleKind kind // NOTE(vpukhov): part of ongoing design void Program::MaybeTransformToDeclarationModule() { + ES2PANDA_ASSERT(ast_); if (IsPackage() || ast_->Statements().empty()) { return; } diff --git a/ets2panda/parser/statementParser.cpp b/ets2panda/parser/statementParser.cpp index 9039a1b441..3fefb15d68 100644 --- a/ets2panda/parser/statementParser.cpp +++ b/ets2panda/parser/statementParser.cpp @@ -225,6 +225,7 @@ ir::Statement *ParserImpl::ParseLetStatement(StatementParsingFlags flags) } auto *variableDecl = ParseVariableDeclaration(VariableParsingFlags::LET); + ES2PANDA_ASSERT(variableDecl); if (variableDecl->IsBrokenStatement()) { // Error processing. return variableDecl; } @@ -243,6 +244,7 @@ ir::Statement *ParserImpl::ParseConstStatement(StatementParsingFlags flags) lexer_->NextToken(); auto *variableDecl = ParseVariableDeclaration(VariableParsingFlags::CONST | VariableParsingFlags::NO_SKIP_VAR_KIND); + ES2PANDA_ASSERT(variableDecl); if (variableDecl->IsBrokenStatement()) { // Error processing. return variableDecl; } @@ -256,6 +258,7 @@ ir::Statement *ParserImpl::ParseConstStatement(StatementParsingFlags flags) ir::EmptyStatement *ParserImpl::ParseEmptyStatement() { auto *empty = AllocNode(); + ES2PANDA_ASSERT(empty); empty->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); return empty; @@ -264,6 +267,7 @@ ir::EmptyStatement *ParserImpl::ParseEmptyStatement() ir::Statement *ParserImpl::ParseDebuggerStatement() { auto *debuggerNode = AllocNode(); + ES2PANDA_ASSERT(debuggerNode); debuggerNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); ConsumeSemicolon(debuggerNode); @@ -283,6 +287,7 @@ ir::Statement *ParserImpl::ParseFunctionStatement(StatementParsingFlags flags) stmts.push_back(funcDecl); auto *localBlockStmt = AllocNode(Allocator(), std::move(stmts)); + ES2PANDA_ASSERT(localBlockStmt); localBlockStmt->SetRange(funcDecl->Range()); return funcDecl; @@ -328,6 +333,7 @@ ir::Statement *ParserImpl::ParseStructDeclaration(ir::ClassDefinitionModifiers m lexer::SourcePosition endLoc = classDefinition->End(); auto *structDecl = AllocNode(classDefinition, Allocator()); + ES2PANDA_ASSERT(structDecl); structDecl->SetRange({startLoc, endLoc}); return structDecl; } @@ -348,6 +354,7 @@ ir::Statement *ParserImpl::ParseClassDeclaration(ir::ClassDefinitionModifiers mo lexer::SourcePosition endLoc = classDefinition->End(); auto *classDecl = AllocNode(classDefinition, Allocator()); + ES2PANDA_ASSERT(classDecl); classDecl->SetRange({startLoc, endLoc}); return classDecl; } @@ -374,6 +381,7 @@ void ParserImpl::ConsumeSemicolon(ir::Statement *statement) auto const &token = lexer_->GetToken(); auto tokenType = token.Type(); if (tokenType == lexer::TokenType::PUNCTUATOR_SEMI_COLON) { + ES2PANDA_ASSERT(statement); statement->SetEnd(token.End()); lexer_->NextToken(); return; @@ -429,6 +437,7 @@ bool ParserImpl::ParseDirective(ArenaVector *statements) bool isDirective = exprNode->IsStringLiteral(); auto *exprStatement = AllocNode(exprNode); + ES2PANDA_ASSERT(exprStatement); exprStatement->SetRange(exprNode->Range()); ConsumeSemicolon(exprStatement); @@ -459,6 +468,7 @@ ir::BlockStatement *ParserImpl::ParseBlockStatement() auto statements = ParseStatementList(); auto *blockNode = AllocNode(Allocator(), std::move(statements)); + ES2PANDA_ASSERT(blockNode); blockNode->SetRange({startLoc, lexer_->GetToken().End()}); ExpectToken(lexer::TokenType::PUNCTUATOR_RIGHT_BRACE); @@ -490,6 +500,7 @@ ir::Statement *ParserImpl::ParseBreakStatement() } auto *breakStatement = AllocNode(); + ES2PANDA_ASSERT(breakStatement); breakStatement->SetRange({startLoc, lexer_->GetToken().End()}); if (lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_SEMI_COLON) { @@ -565,6 +576,7 @@ ir::Statement *ParserImpl::ParseContinueStatement() identNode->SetRange(lexer_->GetToken().Loc()); auto *continueStatement = AllocNode(identNode); + ES2PANDA_ASSERT(continueStatement); continueStatement->SetRange({startLoc, lexer_->GetToken().End()}); lexer_->NextToken(); @@ -613,6 +625,7 @@ ir::Statement *ParserImpl::ParseDoWhileStatement() ExpectToken(lexer::TokenType::PUNCTUATOR_RIGHT_PARENTHESIS); auto *doWhileStatement = AllocNode(body, condition); + ES2PANDA_ASSERT(doWhileStatement); doWhileStatement->SetRange({startLoc, endLoc}); if (lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_SEMI_COLON) { @@ -659,6 +672,7 @@ ir::FunctionDeclaration *ParserImpl::ParseFunctionDeclaration(bool canBeAnonymou newStatus |= ParserStatus::FUNCTION_DECLARATION; ir::ScriptFunction *func = ParseFunction(newStatus | ParserStatus::NEED_RETURN_TYPE); + ES2PANDA_ASSERT(func); func->SetIdent(identNode); func->SetStart(startLoc); @@ -715,6 +729,7 @@ ir::Statement *ParserImpl::ParseExpressionStatement(StatementParsingFlags flags) lexer::SourcePosition endPos = exprNode->End(); auto *exprStatementNode = AllocNode(exprNode); + ES2PANDA_ASSERT(exprStatementNode); exprStatementNode->SetRange({startPos.GetToken().Start(), endPos}); ConsumeSemicolon(exprStatementNode); @@ -845,6 +860,7 @@ std::tuple ir::AstNode *initNode = lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_COMMA ? ParseSequenceExpression(expr) : expr; + ES2PANDA_ASSERT(initNode); if (initNode->IsConditionalExpression()) { ir::ConditionalExpression *condExpr = initNode->AsConditionalExpression(); @@ -997,6 +1013,7 @@ ir::Statement *ParserImpl::CreateForStatement(ForStatementNodes &&nodes, ForStat } } + ES2PANDA_ASSERT(forStatement); forStatement->SetRange({startLoc, nodes.body->End()}); return forStatement; @@ -1074,6 +1091,7 @@ ir::Statement *ParserImpl::ParseIfStatement() } auto *ifStatement = AllocNode(test, consequent, alternate); + ES2PANDA_ASSERT(ifStatement); ifStatement->SetRange({startLoc, endLoc}); return ifStatement; } @@ -1104,6 +1122,7 @@ ir::Statement *ParserImpl::ParseLabelledStatement(const lexer::LexerPosition &po ir::Statement *body = ParseStatement(StatementParsingFlags::LABELLED); auto *labeledStatement = AllocNode(identNode, body); + ES2PANDA_ASSERT(labeledStatement); labeledStatement->SetRange({pos.GetToken().Start(), body->End()}); return labeledStatement; @@ -1143,6 +1162,7 @@ ir::Statement *ParserImpl::ParseReturnStatement() returnStatement = AllocNode(); } + ES2PANDA_ASSERT(returnStatement); returnStatement->SetRange({startLoc, endLoc}); ConsumeSemicolon(returnStatement); @@ -1198,6 +1218,7 @@ ir::SwitchCaseStatement *ParserImpl::ParseSwitchCaseStatement(bool *seenDefault) } auto *caseNode = AllocNode(testExpr, std::move(consequents)); + ES2PANDA_ASSERT(caseNode); caseNode->SetRange({caseStartLoc, caseEndLoc}); return caseNode; } @@ -1229,6 +1250,7 @@ ir::Statement *ParserImpl::ParseSwitchStatement() ExpectToken(lexer::TokenType::PUNCTUATOR_RIGHT_BRACE); auto *switchStatement = AllocNode(discriminant, std::move(cases)); + ES2PANDA_ASSERT(switchStatement); switchStatement->SetRange({startLoc, endLoc}); return switchStatement; } @@ -1253,6 +1275,7 @@ ir::Statement *ParserImpl::ParseThrowStatement() lexer::SourcePosition endLoc = expression->End(); auto *throwStatement = AllocNode(expression); + ES2PANDA_ASSERT(throwStatement); throwStatement->SetRange({startLoc, endLoc}); ConsumeSemicolon(throwStatement); @@ -1307,6 +1330,7 @@ ir::CatchClause *ParserImpl::ParseCatchClause() lexer::SourcePosition endLoc = catchBlock->End(); auto *catchClause = AllocNode(param, catchBlock); + ES2PANDA_ASSERT(catchClause); catchClause->SetRange({catchStartLoc, endLoc}); return catchClause; @@ -1351,6 +1375,7 @@ ir::Statement *ParserImpl::ParseTryStatement() lexer_->NextToken(); // eat 'finally' keyword finallyClause = ParseBlockStatement(); + ES2PANDA_ASSERT(finallyClause); endLoc = finallyClause->End(); } @@ -1521,6 +1546,7 @@ ir::Statement *ParserImpl::ParseVariableDeclaration(VariableParsingFlags flags) lexer::SourcePosition endLoc = declarators.back()->End(); auto *declaration = AllocNode(varKind, Allocator(), std::move(declarators)); + ES2PANDA_ASSERT(declaration); declaration->SetRange({startLoc, endLoc}); return declaration; @@ -1548,6 +1574,7 @@ ir::Statement *ParserImpl::ParseWhileStatement() lexer::SourcePosition endLoc = body->End(); auto *whileStatement = AllocNode(condition, body); + ES2PANDA_ASSERT(whileStatement); whileStatement->SetRange({startLoc, endLoc}); return whileStatement; @@ -1598,6 +1625,7 @@ ir::ExportDefaultDeclaration *ParserImpl::ParseExportDefaultDeclaration(const le ES2PANDA_ASSERT(declNode != nullptr); lexer::SourcePosition endLoc = declNode->End(); auto *exportDeclaration = AllocNode(declNode, isExportEquals); + ES2PANDA_ASSERT(exportDeclaration); exportDeclaration->SetRange({startLoc, endLoc}); if (eatSemicolon) { @@ -1621,6 +1649,7 @@ ir::Identifier *ParserImpl::ParseNamedExport(lexer::Token *exportedToken) const util::StringView &exportedString = exportedToken->Ident(); auto *exported = AllocNode(exportedString, Allocator()); + ES2PANDA_ASSERT(exported); exported->SetRange(exportedToken->Loc()); return exported; @@ -1638,9 +1667,11 @@ ir::ExportAllDeclaration *ParserImpl::ParseExportAllDeclaration(const lexer::Sou lexer_->NextToken(); // eat exported name } ir::StringLiteral *source = ParseFromClause(); + ES2PANDA_ASSERT(source); lexer::SourcePosition endLoc = source->End(); auto *exportDeclaration = AllocNode(source, exported); + ES2PANDA_ASSERT(exportDeclaration); exportDeclaration->SetRange({startLoc, endLoc}); ConsumeSemicolon(exportDeclaration); @@ -1695,6 +1726,7 @@ ir::ExportNamedDeclaration *ParserImpl::ParseExportNamedSpecifiers(const lexer:: } auto *exportDeclaration = AllocNode(Allocator(), source, std::move(specifiers)); + ES2PANDA_ASSERT(exportDeclaration); exportDeclaration->SetRange({startLoc, endPos}); ConsumeSemicolon(exportDeclaration); @@ -1749,6 +1781,7 @@ ir::Statement *ParserImpl::ParseNamedExportDeclaration(const lexer::SourcePositi lexer::SourcePosition endLoc = decl->End(); ArenaVector specifiers(Allocator()->Adapter()); auto *exportDeclaration = AllocNode(Allocator(), decl, std::move(specifiers)); + ES2PANDA_ASSERT(exportDeclaration); exportDeclaration->SetRange({startLoc, endLoc}); return exportDeclaration; @@ -1797,6 +1830,7 @@ void ParserImpl::ParseNameSpaceImport(ArenaVector *specifiers) ir::Identifier *local = ParseNamedImport(&lexer_->GetToken()); auto *specifier = AllocNode(local); + ES2PANDA_ASSERT(specifier); specifier->SetRange({namespaceStart, lexer_->GetToken().End()}); specifiers->push_back(specifier); @@ -1814,6 +1848,7 @@ ir::Identifier *ParserImpl::ParseNamedImport(lexer::Token *importedToken) CheckRestrictedBinding(importedToken->KeywordType()); auto *local = AllocNode(importedToken->Ident(), Allocator()); + ES2PANDA_ASSERT(local); local->SetRange(importedToken->Loc()); return local; @@ -1860,6 +1895,7 @@ ir::AstNode *ParserImpl::ParseImportDefaultSpecifier(ArenaVector lexer_->NextToken(); // eat local name auto *specifier = AllocNode(local); + ES2PANDA_ASSERT(specifier); specifier->SetRange(specifier->Local()->Range()); specifiers->push_back(specifier); @@ -1892,6 +1928,7 @@ ir::StringLiteral *ParserImpl::ParseFromClause(bool requireFrom) } auto *source = AllocNode(lexer_->GetToken().String()); + ES2PANDA_ASSERT(source); source->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -1950,6 +1987,7 @@ ir::Statement *ParserImpl::ParseImportDeclaration(StatementParsingFlags flags) lexer::SourcePosition endLoc = source->End(); auto *importDeclaration = AllocNode(source, std::move(specifiers)); + ES2PANDA_ASSERT(importDeclaration); importDeclaration->SetRange({startLoc, endLoc}); ConsumeSemicolon(importDeclaration); @@ -1965,6 +2003,7 @@ ir::Statement *ParserImpl::AllocBrokenStatement(const lexer::SourcePosition &pos ir::Statement *ParserImpl::AllocBrokenStatement(const lexer::SourceRange &range) { auto *broken = AllocNode(true); + ES2PANDA_ASSERT(broken); broken->SetRange(range); return broken; } @@ -1980,6 +2019,7 @@ bool ParserImpl::IsBrokenStatement(ir::Statement *st) ir::Statement *ParserImpl::AllocEmptyStatement() { auto *empty = AllocNode(); + ES2PANDA_ASSERT(empty); empty->SetRange(lexer_->GetToken().Loc()); return empty; } diff --git a/ets2panda/parser/statementTSParser.cpp b/ets2panda/parser/statementTSParser.cpp index 34dce05dc1..2a4840d461 100644 --- a/ets2panda/parser/statementTSParser.cpp +++ b/ets2panda/parser/statementTSParser.cpp @@ -131,6 +131,7 @@ ir::TSImportEqualsDeclaration *TSParser::ParseTsImportEqualsDeclaration(const le } auto *id = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(id); id->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); // eat id name @@ -190,6 +191,7 @@ ir::ExportDefaultDeclaration *TSParser::ParseExportDefaultDeclaration(const lexe lexer::SourcePosition endLoc = declNode->End(); auto *exportDeclaration = AllocNode(declNode, isExportEquals); + ES2PANDA_ASSERT(exportDeclaration); exportDeclaration->SetRange({startLoc, endLoc}); if (eatSemicolon) { @@ -265,6 +267,7 @@ ir::Statement *TSParser::ParseNamedExportDeclaration(const lexer::SourcePosition lexer::SourcePosition endLoc = decl->End(); ArenaVector specifiers(Allocator()->Adapter()); auto *exportDeclaration = AllocNode(Allocator(), decl, std::move(specifiers)); + ES2PANDA_ASSERT(exportDeclaration); exportDeclaration->SetRange({startLoc, endLoc}); return exportDeclaration; @@ -293,6 +296,7 @@ ir::Statement *TSParser::ParseExportDeclaration(StatementParsingFlags flags) } default: { auto ret = ParseNamedExportDeclaration(startLoc); + ES2PANDA_ASSERT(ret); if (ret->IsBrokenStatement()) { return ret; } @@ -322,6 +326,7 @@ ir::Statement *TSParser::ParseConstStatement(StatementParsingFlags flags) } auto *variableDecl = ParseVariableDeclaration(VariableParsingFlags::CONST | VariableParsingFlags::NO_SKIP_VAR_KIND); + ES2PANDA_ASSERT(variableDecl); variableDecl->SetStart(constVarStar); ConsumeSemicolon(variableDecl); @@ -364,6 +369,7 @@ ir::Statement *TSParser::ParseImportDeclaration([[maybe_unused]] StatementParsin source = ParseFromClause(false); } + ES2PANDA_ASSERT(source); lexer::SourcePosition endLoc = source->End(); auto *importDeclaration = AllocNode(source, std::move(specifiers)); importDeclaration->SetRange({startLoc, endLoc}); -- Gitee From 7a58e7875f2a008e6fc61c562be06ee7c7cc0f47 Mon Sep 17 00:00:00 2001 From: anjiaqi Date: Sat, 5 Jul 2025 20:48:28 +0800 Subject: [PATCH 081/145] Update Codecheck ignore for frontend-0603 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICK8L6 Reason: Update Codecheck ignore for frontend-0603 Description: Update Codecheck ignore for frontend-0603 Test: pass Signed-off-by: anjiaqi --- codecheck_ignore.json | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/codecheck_ignore.json b/codecheck_ignore.json index 775d3e8774..a30bb19d2b 100755 --- a/codecheck_ignore.json +++ b/codecheck_ignore.json @@ -8,9 +8,18 @@ "test_ecma_bcopt": "*", "legacy_bin": "*", "merge_abc": "*", + "ets2panda/bindings/src": "*", + "ets2panda/driver/build_system/src": "*", "ets2panda/public/headers_parser": "*", "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": "*", "*": ["G.CMT.03", "G.FMT.11", "G.NAM.03", "huge_headerfile", "huge_non_headerfile", "bc-30001"] } -- Gitee From e7d8a24bcb69027b7ac6e6c750024ac8ebbb7073 Mon Sep 17 00:00:00 2001 From: oh-rgx Date: Sat, 5 Jul 2025 21:24:22 +0800 Subject: [PATCH 082/145] Fix bigInt operators Issue: #ICK8OO Signed-off-by: oh-rgx --- ets2panda/checker/ets/arithmetic.cpp | 1 + .../ets/bigInt_unsigned_right_shift.ets | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/bigInt_unsigned_right_shift.ets diff --git a/ets2panda/checker/ets/arithmetic.cpp b/ets2panda/checker/ets/arithmetic.cpp index 7f9007daec..1e109fa054 100644 --- a/ets2panda/checker/ets/arithmetic.cpp +++ b/ets2panda/checker/ets/arithmetic.cpp @@ -226,6 +226,7 @@ bool ETSChecker::CheckBinaryOperatorForBigInt(Type *left, Type *right, lexer::To case lexer::TokenType::PUNCTUATOR_STRICT_EQUAL: case lexer::TokenType::PUNCTUATOR_NOT_STRICT_EQUAL: case lexer::TokenType::KEYW_INSTANCEOF: + case lexer::TokenType::PUNCTUATOR_UNSIGNED_RIGHT_SHIFT: // This is handled in the main CheckBinaryOperator function return false; default: diff --git a/ets2panda/test/ast/compiler/ets/bigInt_unsigned_right_shift.ets b/ets2panda/test/ast/compiler/ets/bigInt_unsigned_right_shift.ets new file mode 100644 index 0000000000..0236e91282 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/bigInt_unsigned_right_shift.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. + */ + +const v0 = 1516532564n; +const v1 = 213n; + +let v2 = v0 >>> v1; + +/* @@? 19:10 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ \ No newline at end of file -- Gitee From d310cbce135de1ae53caa018e92d4bdd62169d06 Mon Sep 17 00:00:00 2001 From: daizihan Date: Mon, 26 May 2025 17:49:17 +0800 Subject: [PATCH 083/145] Add module to re-export Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICAMO0?from=project-issue Signed-off-by: daizihan Change-id: if5c1b3f4bed502a4707c9e1049c2f9e349c3b54c --- .../compiler/lowering/ets/enumLowering.cpp | 1 + .../ets/topLevelStmts/globalClassHandler.cpp | 88 +++++++++++++++++-- .../ets/topLevelStmts/globalClassHandler.h | 8 +- ets2panda/ir/base/classDefinition.h | 9 +- .../unit/lowerings/top_level_statements.cpp | 26 ++++++ 5 files changed, 123 insertions(+), 9 deletions(-) diff --git a/ets2panda/compiler/lowering/ets/enumLowering.cpp b/ets2panda/compiler/lowering/ets/enumLowering.cpp index f13666933d..494c9716b2 100644 --- a/ets2panda/compiler/lowering/ets/enumLowering.cpp +++ b/ets2panda/compiler/lowering/ets/enumLowering.cpp @@ -277,6 +277,7 @@ ir::ClassDeclaration *EnumLoweringPhase::CreateClass(ir::TSEnumDeclaration *cons if (enumDecl->IsExported()) { classDecl->AddModifier(ir::ModifierFlags::EXPORT); + program_->GlobalClass()->AddToExportedClasses(classDecl); } else if (enumDecl->IsDefaultExported()) { classDecl->AddModifier(ir::ModifierFlags::DEFAULT_EXPORT); } diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp index 13dd763e3b..df5d68e47b 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.cpp @@ -14,6 +14,7 @@ */ #include "compiler/lowering/ets/topLevelStmts/globalClassHandler.h" +#include #include "compiler/lowering/util.h" #include "ir/statements/classDeclaration.h" @@ -59,13 +60,69 @@ std::string AddToNamespaceChain(std::string chain, std::string name) return chain + "." + name; } -void GlobalClassHandler::CollectNamespaceExportedClasses(ir::ClassDefinition *classDef) +void GlobalClassHandler::CollectNamespaceExportedClasses(parser::Program *program, ir::ClassDefinition *classDef) { - CollectExportedClasses(classDef, classDef->Body()); + CollectExportedClasses(program, classDef, classDef->Body()); +} + +void GlobalClassHandler::CollectReExportedClasses(parser::Program *program, ir::ClassDefinition *classDef, + const ir::ETSReExportDeclaration *reExport) +{ + auto importDecl = reExport->GetETSImportDeclarations(); + const auto importPath = reExport->GetETSImportDeclarations()->ImportMetadata().resolvedSource; + parser::Program *extProg = nullptr; + // Search Correct external program by comparing importPath and absolutePath + for (auto &[_, progs] : program->DirectExternalSources()) { + auto it = std::find_if(progs.begin(), progs.end(), + [&](const auto *prog) { return prog->AbsoluteName() == importPath; }); + if (it != progs.end()) { + extProg = *it; + break; + } + } + if (extProg == nullptr) { + return; + } + auto &externalExportedClasses = extProg->GlobalClass()->ExportedClasses(); + const auto &specifiers = importDecl->Specifiers(); + bool needAddETSGlobal = false; + for (const auto *specifier : specifiers) { + if (specifier->IsImportNamespaceSpecifier()) { + classDef->BatchAddToExportedClasses(externalExportedClasses); + break; + } + auto found = std::find_if(externalExportedClasses.begin(), externalExportedClasses.end(), + [&specifier](const ir::ClassDeclaration *classDecl) { + return specifier->IsImportSpecifier() && + specifier->AsImportSpecifier()->Imported()->Name() == + // CC-OFFNXT(G.FMT.02-CPP) solid logic + classDecl->Definition()->Ident()->Name(); + // CC-OFFNXT(G.FMT.02-CPP) solid logic + }); + if (found == externalExportedClasses.end()) { + needAddETSGlobal = true; + continue; + } + classDef->AddToExportedClasses(*found); + } + + /* + * a.ets: b.ets: + * export let ident = 10 export {ident, A, B} from './a' + * export class A {} + * export class B {} + * Note: (`a.ets` exported classes: A, B and ETSGLOBAL) + * + * In this re-export declaration, we need manually add ETSGLOBAL to exportedClasses. + */ + if (needAddETSGlobal) { + classDef->AddToExportedClasses(extProg->GlobalClass()->Parent()->AsClassDeclaration()); + } } template -void GlobalClassHandler::CollectExportedClasses(ir::ClassDefinition *classDef, const ArenaVector &statements) +void GlobalClassHandler::CollectExportedClasses(parser::Program *program, ir::ClassDefinition *classDef, + const ArenaVector &statements) { for (const auto *statement : statements) { if (!statement->IsExported()) { @@ -73,7 +130,26 @@ void GlobalClassHandler::CollectExportedClasses(ir::ClassDefinition *classDef, c } if (statement->IsClassDeclaration()) { classDef->AddToExportedClasses(statement->AsClassDeclaration()); + continue; + } + if (statement->IsETSReExportDeclaration()) { + CollectReExportedClasses(program, classDef, statement->AsETSReExportDeclaration()); + } + } + auto globalClass = program->GlobalClass(); + bool foundExport = false; + // Add ETSGLOBAL to Module in case of export let a = 10 + std::function findExportInGlobal = [&findExportInGlobal, &foundExport](ir::AstNode *node) { + if (node->IsExported()) { + foundExport = true; + return; } + node->Iterate(findExportInGlobal); + }; + globalClass->Iterate(findExportInGlobal); + if (foundExport) { + auto globalClassDecl = globalClass->Parent()->AsClassDeclaration(); + classDef->AddToExportedClasses(globalClassDecl); } } @@ -243,7 +319,7 @@ ir::ClassDeclaration *GlobalClassHandler::TransformNamespace(ir::ETSModule *ns, for (auto *cls : globalClasses) { globalClass->Body().emplace_back(cls); cls->SetParent(globalClass); - CollectNamespaceExportedClasses(cls->Definition()); + CollectNamespaceExportedClasses(program, cls->AsClassDeclaration()->Definition()); } // Add rest statement, such as type declaration @@ -261,7 +337,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()); + CollectNamespaceExportedClasses(program, cls->Definition()); } } @@ -329,7 +405,7 @@ void GlobalClassHandler::SetupGlobalClass(const ArenaVector & CollectProgramGlobalClasses(globalProgram, namespaces); auto initializerBlockStmts = FormInitStaticBlockMethodStatements(globalProgram, moduleDependencies, std::move(initializerBlock)); - CollectExportedClasses(globalClass, globalProgram->Ast()->Statements()); + CollectExportedClasses(globalProgram, globalClass, globalProgram->Ast()->Statements()); // NOTE(vpukhov): stdlib checks are to be removed - do not extend the existing logic if (globalProgram->Kind() != parser::ScriptKind::STDLIB) { diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h index fc726e8dd6..88989919d5 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/globalClassHandler.h @@ -17,6 +17,7 @@ #define PANDA_GLOBALCLASSHANDLER_H #include "compiler/lowering/ets/topLevelStmts/globalDeclTransformer.h" +#include "ir/ets/etsReExportDeclaration.h" #include "parser/program/program.h" #include "public/public.h" #include "ir/astNode.h" @@ -56,8 +57,11 @@ private: ir::ClassDeclaration *TransformNamespace(ir::ETSModule *ns, parser::Program *program); ir::ClassDeclaration *CreateTransformedClass(ir::ETSModule *ns); template - void CollectExportedClasses(ir::ClassDefinition *classDef, const ArenaVector &statements); - void CollectNamespaceExportedClasses(ir::ClassDefinition *classDef); + void CollectExportedClasses(parser::Program *program, ir::ClassDefinition *classDef, + const ArenaVector &statements); + void CollectReExportedClasses(parser::Program *program, ir::ClassDefinition *classDef, + const ir::ETSReExportDeclaration *reExport); + void CollectNamespaceExportedClasses(parser::Program *program, ir::ClassDefinition *classDef); void SetupGlobalMethods(parser::Program *program, ArenaVector &&initStatements, ir::ClassDefinition *globalClass, bool isDeclare); void SetupInitializerBlock(parser::Program *program, ArenaVector> &&initializerBlock, diff --git a/ets2panda/ir/base/classDefinition.h b/ets2panda/ir/base/classDefinition.h index 0526e6128a..8950bd25e5 100644 --- a/ets2panda/ir/base/classDefinition.h +++ b/ets2panda/ir/base/classDefinition.h @@ -488,10 +488,17 @@ public: void AddToExportedClasses(const ir::ClassDeclaration *cls) { - ES2PANDA_ASSERT(cls->IsExported()); + ES2PANDA_ASSERT(cls->IsExported() || cls->Definition()->IsGlobal()); exportedClasses_.push_back(cls); } + void BatchAddToExportedClasses(const ArenaVector &classes) + { + for (const auto cls : classes) { + AddToExportedClasses(cls); + } + } + [[nodiscard]] const ArenaVector &ExportedClasses() const noexcept { return exportedClasses_; diff --git a/ets2panda/test/unit/lowerings/top_level_statements.cpp b/ets2panda/test/unit/lowerings/top_level_statements.cpp index 88ef617443..c7fedb4621 100644 --- a/ets2panda/test/unit/lowerings/top_level_statements.cpp +++ b/ets2panda/test/unit/lowerings/top_level_statements.cpp @@ -128,4 +128,30 @@ TEST_F(LoweringTest, TestTopLevelStmtsExportedNamespaceNested) } } +TEST_F(LoweringTest, TestTopLevelStmtsExportedEnum) +{ + char const *text = R"( + export let a = 10; + export enum Color { + Red = 1 + } + )"; + + CONTEXT(ES2PANDA_STATE_LOWERED, text) + { + const auto *const ast = GetAst(); + auto *classDef = ast->FindChild([](ir::AstNode *child) { + return child->IsClassDefinition() && child->AsClassDefinition()->IsGlobalInitialized(); + }); + 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[1]->IsExported()); + ASSERT_EQ(exportedClasses[0]->Definition()->InternalName().Mutf8(), "dummy.ETSGLOBAL"); + ASSERT_EQ(exportedClasses[1]->Definition()->InternalName().Mutf8(), "dummy.Color"); + } +} + } // namespace ark::es2panda -- Gitee From 34b3ae5134c421990bcd2654803ecec24a10be0b Mon Sep 17 00:00:00 2001 From: zmw Date: Sat, 5 Jul 2025 12:03:02 +0800 Subject: [PATCH 084/145] Fix get set type crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICK672 Description: Fix get set type crash Signed-off-by: zmw --- ets2panda/checker/ets/typeCheckingHelpers.cpp | 5 +++++ .../compiler/ets/set_init_without_param.ets | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/set_init_without_param.ets diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 7a372da58e..c3b28ada6d 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -442,6 +442,11 @@ Type *ETSChecker::GetTypeOfSetterGetter(varbinder::Variable *const var) return propType->FindGetter()->ReturnType(); } + if (propType->FindSetter()->Params().empty()) { + var->SetTsType(GlobalTypeError()); + return GlobalTypeError(); + } + return propType->FindSetter()->Params()[0]->TsType(); } diff --git a/ets2panda/test/ast/compiler/ets/set_init_without_param.ets b/ets2panda/test/ast/compiler/ets/set_init_without_param.ets new file mode 100644 index 0000000000..50710b371e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/set_init_without_param.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. + */ + +set a '1;' + +/* @@? 16:1 Error SyntaxError: Extension Setter can only have 2 parameters. */ +/* @@? 16:5 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 16:7 Error SyntaxError: Unexpected token, expected '('. */ +/* @@? 22:77 Error SyntaxError: Expected ')', got 'end of stream'. */ +/* @@? 22:77 Error SyntaxError: Extension Accessor must have a receiver. */ \ No newline at end of file -- Gitee From f40787dad720b5019870b60595f5d2131399f3fc Mon Sep 17 00:00:00 2001 From: zmw Date: Sat, 5 Jul 2025 17:36:51 +0800 Subject: [PATCH 085/145] Fix newExpr multi dot crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICK7UA Description: Fix nexExpr multi dot crash Signed-off-by: zmw --- ets2panda/parser/ETSparser.cpp | 4 ++++ .../ets/new_expr_with_succesive_multi_dot.ets | 23 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/new_expr_with_succesive_multi_dot.ets diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index d45233034c..8db516b2f1 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -987,6 +987,10 @@ ir::TypeNode *ETSParser::ParseTypeReference(TypeAnnotationParsingOptions *option while (true) { auto partPos = Lexer()->GetToken().Start(); auto [typeName, typeParams] = ParseTypeReferencePart(options); + if (typeName == nullptr) { + typeName = AllocBrokenExpression(partPos); + } + typeRefPart = AllocNode(typeName, typeParams, typeRefPart, Allocator()); typeRefPart->SetRange({partPos, Lexer()->GetToken().End()}); diff --git a/ets2panda/test/ast/compiler/ets/new_expr_with_succesive_multi_dot.ets b/ets2panda/test/ast/compiler/ets/new_expr_with_succesive_multi_dot.ets new file mode 100644 index 0000000000..30c7c5860d --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/new_expr_with_succesive_multi_dot.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. + */ + +importet lock1 = new ArkTSUt../main; + +/* @@? 16:1 Error TypeError: Unresolved reference importet */ +/* @@? 16:10 Error SyntaxError: Unexpected token 'lock1'. */ +/* @@? 16:10 Error TypeError: Unresolved reference lock1 */ +/* @@? 16:18 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ +/* @@? 16:30 Error SyntaxError: Identifier expected. */ +/* @@? 16:31 Error TypeError: Invalid type reference. */ -- Gitee From 2903890ae51ef81be6e310e903ad72f978c5738a Mon Sep 17 00:00:00 2001 From: oh-rgx Date: Sat, 5 Jul 2025 22:02:09 +0800 Subject: [PATCH 086/145] Fix check classProperty crash Issue: #ICK8SY Signed-off-by: oh-rgx --- ets2panda/checker/ets/object.cpp | 6 +++++ .../ast/compiler/ets/class_inheritance.ets | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/class_inheritance.ets diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 2b6cfeac48..c8f495de41 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -2287,6 +2287,12 @@ void ETSChecker::CheckValidInheritance(ETSObjectType *classType, ir::ClassDefini const auto &allProps = classType->GetAllProperties(); for (auto *it : allProps) { + auto *node = it->Declaration()->Node(); + if (node->IsClassProperty() && node->AsClassProperty()->TsType() != nullptr && + node->AsClassProperty()->TsType()->IsTypeError()) { + continue; + } + const auto searchFlag = PropertySearchFlags::SEARCH_ALL | PropertySearchFlags::SEARCH_IN_BASE | PropertySearchFlags::SEARCH_IN_INTERFACES | PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION; diff --git a/ets2panda/test/ast/compiler/ets/class_inheritance.ets b/ets2panda/test/ast/compiler/ets/class_inheritance.ets new file mode 100644 index 0000000000..78e049e51a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/class_inheritance.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. + */ + +class AAA { + objectProp = {name: 'Jone', age: 30}; +} + +class BBB extends AAA { + objectProp = {name: 'Jone', age: 30}; +} + +/* @@? 17:5 Error TypeError: Cannot infer type for objectProp because class composite needs an explicit target type */ +/* @@? 21:5 Error TypeError: Cannot infer type for objectProp because class composite needs an explicit target type */ \ No newline at end of file -- Gitee From b13dd718bb6e0934ae24cc9725717efbf9ca5a7e Mon Sep 17 00:00:00 2001 From: Zhelyapov Aleksey Date: Mon, 30 Jun 2025 22:17:44 +0300 Subject: [PATCH 087/145] Fixed codecheck Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIYVM Signed-off-by: Zhelyapov Aleksey --- ets2panda/compiler/core/ETSGen.cpp | 45 +++++++++++++++++-- ets2panda/compiler/core/ETSGen.h | 3 +- ets2panda/compiler/core/function.cpp | 1 + .../lowering/scopesInit/scopesInitPhase.cpp | 10 ++++- ets2panda/util/doubleLinkedList.h | 3 ++ ets2panda/util/generateBin.cpp | 1 + ets2panda/util/helpers.cpp | 1 + ets2panda/util/options.cpp | 1 + ets2panda/util/path.cpp | 8 ++-- ets2panda/util/ustring.h | 3 ++ ets2panda/varbinder/ETSBinder.cpp | 13 +++++- ets2panda/varbinder/scope.cpp | 9 ++-- 12 files changed, 82 insertions(+), 16 deletions(-) diff --git a/ets2panda/compiler/core/ETSGen.cpp b/ets2panda/compiler/core/ETSGen.cpp index 84960c75e6..bd7cb0bcbe 100644 --- a/ets2panda/compiler/core/ETSGen.cpp +++ b/ets2panda/compiler/core/ETSGen.cpp @@ -86,6 +86,7 @@ void ETSGen::CompileAndCheck(const ir::Expression *expr) return; } + ES2PANDA_ASSERT(accType != nullptr); if (accType->IsETSPrimitiveType() && ((accType->TypeFlags() ^ exprType->TypeFlags()) & ~checker::TypeFlag::CONSTANT) == 0) { return; @@ -216,6 +217,7 @@ checker::Type const *ETSGen::TypeForVar(varbinder::Variable const *var) const no void ETSGen::MoveVreg(const ir::AstNode *const node, const VReg vd, const VReg vs) { const auto *const sourceType = GetVRegType(vs); + ES2PANDA_ASSERT(sourceType != nullptr); if (sourceType->IsETSReferenceType()) { Ra().Emit(node, vd, vs); @@ -270,6 +272,8 @@ void ETSGen::LoadDynamicModuleVariable(const ir::AstNode *node, varbinder::Varia RegScope rs(this); auto *data = VarBinder()->DynamicImportDataForVar(var); + ES2PANDA_ASSERT(data != nullptr); + auto *import = data->import; LoadStaticProperty(node, var->TsType(), FormDynamicModulePropReference(var)); @@ -310,6 +314,7 @@ void ETSGen::LoadVar(const ir::Identifier *node, varbinder::Variable const *cons break; } case ReferenceKind::FIELD: { + ES2PANDA_ASSERT(GetVRegType(GetThisReg()) != nullptr); const auto fullName = FormClassPropReference(GetVRegType(GetThisReg())->AsETSObjectType(), var->Name()); LoadProperty(node, var->TsType(), GetThisReg(), fullName); break; @@ -361,6 +366,7 @@ void ETSGen::StoreVar(const ir::Identifier *node, const varbinder::ConstScopeFin util::StringView ETSGen::FormClassPropReference(const checker::ETSObjectType *classType, const util::StringView &name) { std::stringstream ss; + ES2PANDA_ASSERT(classType != nullptr); ss << classType->AssemblerName().Mutf8() << Signatures::METHOD_SEPARATOR << name; return util::StringView(*ProgElement()->Strings().emplace(ss.str()).first); } @@ -393,6 +399,7 @@ void ETSGen::StoreStaticProperty(const ir::AstNode *const node, const checker::T void ETSGen::LoadStaticProperty(const ir::AstNode *const node, const checker::Type *propType, const util::StringView &fullName) { + ES2PANDA_ASSERT(propType != nullptr); if (propType->IsETSReferenceType()) { Sa().Emit(node, fullName); } else if (IsWidePrimitiveType(propType)) { @@ -407,6 +414,7 @@ void ETSGen::LoadStaticProperty(const ir::AstNode *const node, const checker::Ty void ETSGen::StoreProperty(const ir::AstNode *const node, const checker::Type *propType, const VReg objReg, const util::StringView &name) { + ES2PANDA_ASSERT(Checker()->GetApparentType(GetVRegType(objReg)) != nullptr); auto *objType = Checker()->GetApparentType(GetVRegType(objReg))->AsETSObjectType(); const auto fullName = FormClassPropReference(objType, name); @@ -475,6 +483,7 @@ void ETSGen::LoadPropertyByName([[maybe_unused]] const ir::AstNode *const node, void ETSGen::StorePropertyDynamic(const ir::AstNode *node, const checker::Type *propType, VReg objReg, const util::StringView &propName) { + ES2PANDA_ASSERT(GetVRegType(objReg) != nullptr); auto const lang = GetVRegType(objReg)->AsETSDynamicType()->Language(); std::string_view methodName {}; if (propType->IsETSBooleanType()) { @@ -523,6 +532,7 @@ void ETSGen::StorePropertyDynamic(const ir::AstNode *node, const checker::Type * void ETSGen::LoadPropertyDynamic(const ir::AstNode *node, const checker::Type *propType, VReg objReg, std::variant property) { + ES2PANDA_ASSERT(propType != nullptr && GetVRegType(objReg) != nullptr); auto const lang = GetVRegType(objReg)->AsETSDynamicType()->Language(); auto *type = propType; std::string_view methodName {}; @@ -577,6 +587,7 @@ void ETSGen::LoadPropertyDynamic(const ir::AstNode *node, const checker::Type *p void ETSGen::StoreElementDynamic(const ir::AstNode *node, VReg objectReg, VReg index) { + ES2PANDA_ASSERT(GetVRegType(objectReg) != nullptr); auto const lang = GetVRegType(objectReg)->AsETSDynamicType()->Language(); std::string_view methodName = Signatures::Dynamic::SetElementDynamicBuiltin(lang); @@ -592,6 +603,7 @@ void ETSGen::StoreElementDynamic(const ir::AstNode *node, VReg objectReg, VReg i void ETSGen::LoadElementDynamic(const ir::AstNode *node, VReg objectReg) { + ES2PANDA_ASSERT(GetVRegType(objectReg) != nullptr); auto const lang = GetVRegType(objectReg)->AsETSDynamicType()->Language(); std::string_view methodName = Signatures::Dynamic::GetElementDynamicBuiltin(lang); @@ -682,6 +694,7 @@ void ETSGen::EmitReturnVoid(const ir::AstNode *node) void ETSGen::ReturnAcc(const ir::AstNode *node) { const auto *const accType = GetAccumulatorType(); + ES2PANDA_ASSERT(accType != nullptr); if (accType->IsETSReferenceType()) { Sa().Emit(node); @@ -694,6 +707,7 @@ void ETSGen::ReturnAcc(const ir::AstNode *node) static bool IsNullUnsafeObjectType(checker::Type const *type) { + ES2PANDA_ASSERT(type != nullptr); return type->IsETSObjectType() && type->AsETSObjectType()->IsGlobalETSObjectType(); } @@ -727,6 +741,7 @@ void ETSGen::IsInstanceDynamic(const ir::BinaryExpression *const node, const VRe // return false Label *ifFalse = AllocLabel(); Language lang = rhsType->AsETSDynamicType()->Language(); + ES2PANDA_ASSERT(Checker()->GlobalBuiltinDynamicType(lang) != nullptr); VReg dynTypeReg = MoveAccToReg(node); LoadAccumulator(node, srcReg); EmitIsInstance(node, Checker()->GlobalBuiltinDynamicType(lang)->AssemblerName()); @@ -844,7 +859,7 @@ void ETSGen::BranchIfIsInstance(const ir::AstNode *const node, const VReg srcReg void ETSGen::IsInstance(const ir::AstNode *const node, const VReg srcReg, const checker::Type *target) { target = Checker()->GetApparentType(target); - ES2PANDA_ASSERT(target->IsETSReferenceType()); + ES2PANDA_ASSERT(target->IsETSReferenceType() && GetAccumulatorType() != nullptr); if (target->IsETSAnyType()) { // should be IsSupertypeOf(target, source) LoadAccumulatorBoolean(node, true); @@ -903,6 +918,7 @@ void ETSGen::CheckedReferenceNarrowingObject(const ir::AstNode *node, const chec bool nullishCheck = false; auto *source = GetAccumulatorType(); + ES2PANDA_ASSERT(source != nullptr); if (source->PossiblyETSUndefined()) { nullishCheck = true; BranchIfUndefined(node, isNullish); @@ -1207,6 +1223,7 @@ void ETSGen::EmitUnboxedCall(const ir::AstNode *node, std::string_view signature // to cast to primitive types we probably have to cast to corresponding boxed built-in types first. auto *const checker = Checker()->AsETSChecker(); auto const *accumulatorType = GetAccumulatorType(); + ES2PANDA_ASSERT(accumulatorType != nullptr); if (accumulatorType->IsETSObjectType() && //! accumulatorType->DefinitelyNotETSNullish() && !checker->Relation()->IsIdenticalTo(const_cast(accumulatorType), const_cast(boxedType))) { @@ -1662,6 +1679,7 @@ void ETSGen::CastToReftype(const ir::AstNode *const node, const checker::Type *c ES2PANDA_ASSERT(GetAccumulatorType()->IsETSReferenceType()); const auto *const sourceType = GetAccumulatorType(); + ES2PANDA_ASSERT(sourceType != nullptr); if (sourceType->IsETSDynamicType()) { CastDynamicToObject(node, targetType); @@ -1748,6 +1766,7 @@ void ETSGen::CastDynamicToObject(const ir::AstNode *node, const checker::Type *t void ETSGen::CastToString(const ir::AstNode *const node) { const auto *const sourceType = GetAccumulatorType(); + ES2PANDA_ASSERT(sourceType != nullptr); if (sourceType->IsETSStringType()) { return; } @@ -1783,6 +1802,7 @@ void ETSGen::CastToDynamic(const ir::AstNode *node, const checker::ETSDynamicTyp case checker::TypeFlag::ETS_PARTIAL_TYPE_PARAMETER: case checker::TypeFlag::ETS_UNION: // NOTE(vpukhov): refine dynamic type cast rules case checker::TypeFlag::ETS_ANY: + ES2PANDA_ASSERT(GetAccumulatorType() != nullptr); if (GetAccumulatorType()->IsETSStringType()) { methodName = compiler::Signatures::Dynamic::NewStringBuiltin(type->Language()); break; @@ -1818,6 +1838,7 @@ void ETSGen::CastDynamicTo(const ir::AstNode *node, enum checker::TypeFlag typeF { std::string_view methodName {}; checker::Type *objectType {}; + ES2PANDA_ASSERT(GetAccumulatorType() != nullptr); auto type = GetAccumulatorType()->AsETSDynamicType(); switch (typeFlag) { case checker::TypeFlag::ETS_BOOLEAN: { @@ -2040,6 +2061,7 @@ template void ETSGen::ResolveConditionalResultFloat(const ir::AstNode *node, Label *realEndLabel) { auto type = GetAccumulatorType(); + ES2PANDA_ASSERT(type != nullptr); VReg tmpReg = AllocReg(); StoreAccumulator(node, tmpReg); if (type->IsFloatType()) { @@ -2104,6 +2126,7 @@ void ETSGen::ResolveConditionalResultReference(const ir::AstNode *node) }; auto type = GetAccumulatorType(); + ES2PANDA_ASSERT(type != nullptr); if (!type->PossiblyETSString()) { Sa().Emit(node, 1); return; @@ -2118,6 +2141,7 @@ void ETSGen::ResolveConditionalResultReference(const ir::AstNode *node) compiler::VReg objReg = AllocReg(); StoreAccumulator(node, objReg); + ES2PANDA_ASSERT(Checker()->GlobalBuiltinETSStringType() != nullptr); EmitIsInstance(node, Checker()->GlobalBuiltinETSStringType()->AssemblerName()); BranchIfTrue(node, isString); Sa().Emit(node, 1); @@ -2133,6 +2157,7 @@ template void ETSGen::ResolveConditionalResult(const ir::AstNode *node, [[maybe_unused]] Label *ifFalse) { auto type = GetAccumulatorType(); + ES2PANDA_ASSERT(type != nullptr); #ifdef PANDA_WITH_ETS if (type->IsETSReferenceType()) { VReg valReg = AllocReg(); @@ -2195,6 +2220,7 @@ template void ETSGen::BranchConditional(const ir::AstNode *node, Label *endLabel) { auto type = GetAccumulatorType(); + ES2PANDA_ASSERT(type != nullptr); if (type->IsETSReferenceType()) { VReg valReg = AllocReg(); StoreAccumulator(node, valReg); @@ -2213,6 +2239,7 @@ void ETSGen::BranchConditional(const ir::AstNode *node, Label *endLabel) void ETSGen::ConditionalFloat(const ir::AstNode *node) { auto type = GetAccumulatorType(); + ES2PANDA_ASSERT(type != nullptr); VReg tmpReg = AllocReg(); VReg isNaNReg = AllocReg(); @@ -2252,6 +2279,7 @@ void ETSGen::BranchConditionalIfTrue(const ir::AstNode *node, Label *endLabel) void ETSGen::BranchIfNullish(const ir::AstNode *node, Label *ifNullish) { auto *const type = GetAccumulatorType(); + ES2PANDA_ASSERT(type != nullptr); if (type->IsETSVoidType()) { // NOTE(): #19701 need void refactoring @@ -2294,6 +2322,7 @@ void ETSGen::BranchIfNotNullish(const ir::AstNode *node, Label *ifNotNullish) void ETSGen::AssumeNonNullish(const ir::AstNode *node, checker::Type const *targetType) { auto const *nullishType = GetAccumulatorType(); + ES2PANDA_ASSERT(nullishType != nullptr); if (nullishType->PossiblyETSNull()) { // clear 'null' dataflow EmitCheckCast(node, ToAssemblerType(targetType)); @@ -2482,6 +2511,7 @@ void ETSGen::HandleDefinitelyNullishEquality(const ir::AstNode *node, VReg lhs, } else { auto *checker = const_cast(Checker()); auto ltype = checker->GetNonConstantType(const_cast(GetVRegType(lhs))); + ES2PANDA_ASSERT(ltype != nullptr); LoadAccumulator(node, ltype->DefinitelyETSNullish() ? rhs : lhs); BranchIfNotNullish(node, ifFalse); } @@ -2518,6 +2548,7 @@ static std::optional> SelectL { auto alhs = checker->GetApparentType(checker->GetNonNullishType(lhs)); auto arhs = checker->GetApparentType(checker->GetNonNullishType(rhs)); + ES2PANDA_ASSERT(alhs != nullptr && arhs != nullptr); alhs = alhs->IsETSStringType() ? checker->GlobalBuiltinETSStringType() : alhs; arhs = arhs->IsETSStringType() ? checker->GlobalBuiltinETSStringType() : arhs; if (!alhs->IsETSObjectType() || !arhs->IsETSObjectType()) { @@ -2592,6 +2623,7 @@ void ETSGen::RefEqualityLoose(const ir::AstNode *node, VReg lhs, VReg rhs, Label auto *checker = const_cast(Checker()); auto ltype = checker->GetNonConstantType(const_cast(GetVRegType(lhs))); auto rtype = checker->GetNonConstantType(const_cast(GetVRegType(rhs))); + ES2PANDA_ASSERT(ltype != nullptr && rtype != nullptr); if (ltype->IsETSDynamicType() || rtype->IsETSDynamicType()) { RefEqualityLooseDynamic(node, lhs, rhs, ifFalse); return; @@ -2769,6 +2801,7 @@ void ETSGen::Unary(const ir::AstNode *node, lexer::TokenType op) void ETSGen::UnaryMinus(const ir::AstNode *node) { + ES2PANDA_ASSERT(GetAccumulatorType() != nullptr); if (GetAccumulatorType()->IsETSBigIntType()) { const VReg value = AllocReg(); StoreAccumulator(node, value); @@ -2804,6 +2837,7 @@ void ETSGen::UnaryMinus(const ir::AstNode *node) void ETSGen::UnaryTilde(const ir::AstNode *node) { + ES2PANDA_ASSERT(GetAccumulatorType() != nullptr); if (GetAccumulatorType()->IsETSBigIntType()) { const VReg value = AllocReg(); StoreAccumulator(node, value); @@ -2889,6 +2923,7 @@ void ETSGen::StringBuilderAppend(const ir::AstNode *node, VReg builder) signature = Signatures::BUILTIN_STRING_BUILDER_APPEND_BUILTIN_STRING; } + ES2PANDA_ASSERT(GetAccumulatorType() != nullptr); if (GetAccumulatorType()->IsETSReferenceType() && !GetAccumulatorType()->IsETSStringType()) { if (GetAccumulatorType()->PossiblyETSUndefined()) { Label *ifUndefined = AllocLabel(); @@ -3041,6 +3076,7 @@ void ETSGen::LoadResizableArrayLength(const ir::AstNode *node) void ETSGen::LoadResizableArrayElement(const ir::AstNode *node, const VReg arrObj, const VReg arrIndex) { auto *vRegType = GetVRegType(arrObj); + ES2PANDA_ASSERT(vRegType != nullptr); auto *elementType = vRegType->AsETSResizableArrayType()->ElementType(); Ra().Emit(node, Signatures::BUILTIN_ARRAY_GET_ELEMENT, arrObj, arrIndex); SetAccumulatorType(elementType); @@ -3054,6 +3090,7 @@ void ETSGen::LoadArrayLength(const ir::AstNode *node, VReg arrayReg) void ETSGen::LoadArrayElement(const ir::AstNode *node, VReg objectReg) { + ES2PANDA_ASSERT(GetVRegType(objectReg) != nullptr); auto *elementType = GetVRegType(objectReg)->AsETSArrayType()->ElementType(); if (elementType->IsETSReferenceType()) { Ra().Emit(node, objectReg); @@ -3150,7 +3187,7 @@ util::StringView ETSGen::GetTupleMemberNameForIndex(const std::size_t index) con void ETSGen::LoadTupleElement(const ir::AstNode *node, VReg objectReg, const checker::Type *elementType, std::size_t index) { - ES2PANDA_ASSERT(GetVRegType(objectReg)->IsETSTupleType()); + ES2PANDA_ASSERT(GetVRegType(objectReg) != nullptr && GetVRegType(objectReg)->IsETSTupleType()); const auto propName = FormClassPropReference(GetVRegType(objectReg)->AsETSTupleType()->GetWrapperType(), GetTupleMemberNameForIndex(index)); @@ -3162,7 +3199,7 @@ void ETSGen::LoadTupleElement(const ir::AstNode *node, VReg objectReg, const che void ETSGen::StoreTupleElement(const ir::AstNode *node, VReg objectReg, const checker::Type *elementType, std::size_t index) { - ES2PANDA_ASSERT(GetVRegType(objectReg)->IsETSTupleType()); + ES2PANDA_ASSERT(GetVRegType(objectReg) != nullptr && GetVRegType(objectReg)->IsETSTupleType()); const auto *const tupleType = GetVRegType(objectReg)->AsETSTupleType(); SetVRegType(objectReg, tupleType->GetWrapperType()); @@ -3296,7 +3333,7 @@ bool ETSGen::ExtendWithFinalizer(ir::AstNode const *node, const ir::AstNode *ori util::StringView ETSGen::ToAssemblerType(const es2panda::checker::Type *type) const { - ES2PANDA_ASSERT(type->IsETSReferenceType()); + ES2PANDA_ASSERT(type != nullptr && type->IsETSReferenceType()); std::stringstream ss; type->ToAssemblerTypeWithRank(ss); diff --git a/ets2panda/compiler/core/ETSGen.h b/ets2panda/compiler/core/ETSGen.h index 6b3400e02c..7142782c56 100644 --- a/ets2panda/compiler/core/ETSGen.h +++ b/ets2panda/compiler/core/ETSGen.h @@ -298,7 +298,7 @@ public: bool IsDevirtualizedSignature(const checker::Signature *signature) { - ES2PANDA_ASSERT(!signature->HasSignatureFlag(checker::SignatureFlags::STATIC)); + ES2PANDA_ASSERT(signature != nullptr && !signature->HasSignatureFlag(checker::SignatureFlags::STATIC)); return signature->HasSignatureFlag(checker::SignatureFlags::FINAL | checker::SignatureFlags::PRIVATE | checker::SignatureFlags::CONSTRUCTOR); } @@ -435,6 +435,7 @@ public: if (isEtsPrimitive) { // NOTE: SzD. LoadStaticProperty if ETS stdlib has static TYPE constants otherwise fallback to LdaType } else { + ES2PANDA_ASSERT(GetAccumulatorType() != nullptr); auto classRef = GetAccumulatorType()->AsETSObjectType()->AssemblerName(); Sa().Emit(node, classRef); } diff --git a/ets2panda/compiler/core/function.cpp b/ets2panda/compiler/core/function.cpp index 685ed2c89e..e5c05ca78b 100644 --- a/ets2panda/compiler/core/function.cpp +++ b/ets2panda/compiler/core/function.cpp @@ -128,6 +128,7 @@ static void CompileFunctionParameterDeclaration(PandaGen *pg, const ir::ScriptFu void Function::LoadClassContexts(const ir::AstNode *node, PandaGen *pg, VReg ctor, const util::StringView &name) { auto *classDef = util::Helpers::GetContainingClassDefinition(node); + ES2PANDA_ASSERT(classDef != nullptr); do { auto res = pg->Scope()->Find(classDef->InternalName()); diff --git a/ets2panda/compiler/lowering/scopesInit/scopesInitPhase.cpp b/ets2panda/compiler/lowering/scopesInit/scopesInitPhase.cpp index 49bec80f6e..9ddc20f714 100644 --- a/ets2panda/compiler/lowering/scopesInit/scopesInitPhase.cpp +++ b/ets2panda/compiler/lowering/scopesInit/scopesInitPhase.cpp @@ -570,6 +570,7 @@ void ScopeInitTyped::VisitTSModuleDeclaration(ir::TSModuleDeclaration *moduleDec if (!moduleDecl->IsExternalOrAmbient()) { auto name = moduleDecl->Name()->AsIdentifier()->Name(); auto *decl = AddOrGetDecl(VarBinder(), name, moduleDecl, moduleDecl->Name()->Start(), name); + ES2PANDA_ASSERT(decl != nullptr); decl->BindNode(moduleDecl); } auto localCtx = LexicalScopeCreateOrEnter(VarBinder(), moduleDecl); @@ -631,6 +632,7 @@ void ScopeInitTyped::VisitTSInterfaceDeclaration(ir::TSInterfaceDeclaration *int auto localScope = LexicalScopeCreateOrEnter(VarBinder(), interfDecl); auto *identDecl = AddOrGetDecl(VarBinder(), ident->Name(), interfDecl, ident->Start(), ident->Name()); + ES2PANDA_ASSERT(identDecl != nullptr); identDecl->BindNode(interfDecl); BindScopeNode(localScope.GetScope(), interfDecl); @@ -769,6 +771,7 @@ void InitScopesPhaseTs::CreateFuncDecl(ir::ScriptFunction *func) decl = currentDecl->AsFunctionDecl(); } + ES2PANDA_ASSERT(decl != nullptr); decl->Add(func); } @@ -952,13 +955,14 @@ void AddOverload(ir::MethodDefinition *overload, varbinder::Variable *variable) { auto *currentNode = variable->Declaration()->Node(); currentNode->AsMethodDefinition()->AddOverload(overload); + ES2PANDA_ASSERT(overload->Id() != nullptr); overload->Id()->SetVariable(variable); overload->SetParent(currentNode); } void InitScopesPhaseETS::DeclareClassMethod(ir::MethodDefinition *method) { - ES2PANDA_ASSERT(VarBinder()->GetScope()->IsClassScope()); + ES2PANDA_ASSERT(VarBinder()->GetScope()->IsClassScope() && method->AsMethodDefinition()->Function() != nullptr); if ((method->AsMethodDefinition()->Function()->Flags() & ir::ScriptFunctionFlags::OVERLOAD) != 0) { return; @@ -1014,7 +1018,8 @@ void InitScopesPhaseETS::MaybeAddOverload(ir::MethodDefinition *method, ir::Iden if (methodName->Name().Is(compiler::Signatures::MAIN) && clsScope->Parent()->IsGlobalScope()) { LogDiagnostic(diagnostic::OVERLOADED_MAIN, methodName->Start()); } - ES2PANDA_ASSERT((method->Function()->Flags() & ir::ScriptFunctionFlags::OVERLOAD) == 0U); + ES2PANDA_ASSERT(method->Function() != nullptr && + (method->Function()->Flags() & ir::ScriptFunctionFlags::OVERLOAD) == 0U); AddOverload(method, found); method->Function()->AddFlag(ir::ScriptFunctionFlags::OVERLOAD); @@ -1088,6 +1093,7 @@ void InitScopesPhaseETS::VisitTSEnumMember(ir::TSEnumMember *enumMember) void InitScopesPhaseETS::VisitMethodDefinition(ir::MethodDefinition *method) { + ES2PANDA_ASSERT(method->Function() != nullptr); if (method->Function()->Scope() != nullptr) { return; } diff --git a/ets2panda/util/doubleLinkedList.h b/ets2panda/util/doubleLinkedList.h index a4d5a5a919..f2289bc185 100644 --- a/ets2panda/util/doubleLinkedList.h +++ b/ets2panda/util/doubleLinkedList.h @@ -54,6 +54,7 @@ public: Item *Append(const T &data) { auto item = allocator_->New(); + ES2PANDA_ASSERT(item != nullptr); item->data = data; Append(item); return item; @@ -77,6 +78,7 @@ public: Item *Prepend(const T &data) { auto item = allocator_->New(); + ES2PANDA_ASSERT(item != nullptr); item->data = data; Prepend(item); return item; @@ -100,6 +102,7 @@ public: Item *Insert(Item *after, const T &data) { auto item = allocator_->New(); + ES2PANDA_ASSERT(item != nullptr); item->data = data; Insert(after, item); return item; diff --git a/ets2panda/util/generateBin.cpp b/ets2panda/util/generateBin.cpp index 33abd21586..4c9f5220ea 100644 --- a/ets2panda/util/generateBin.cpp +++ b/ets2panda/util/generateBin.cpp @@ -82,6 +82,7 @@ static int GenerateProgramImpl(ark::pandasm::Program *prog, const util::Options std::cout << "Panda file size statistic:" << std::endl; constexpr std::array INFO_STATS = {"instructions_number", "codesize"}; + ES2PANDA_ASSERT(statp != nullptr); auto &stat = *statp; for (const auto &[name, size] : stat) { if (find(INFO_STATS.begin(), INFO_STATS.end(), name) != INFO_STATS.end()) { diff --git a/ets2panda/util/helpers.cpp b/ets2panda/util/helpers.cpp index 41e971809e..11228d33fe 100644 --- a/ets2panda/util/helpers.cpp +++ b/ets2panda/util/helpers.cpp @@ -766,6 +766,7 @@ bool Helpers::IsAsyncMethod(ir::AstNode const *node) return false; } auto *method = node->AsMethodDefinition(); + ES2PANDA_ASSERT(method->Function() != nullptr); return method->Function()->IsAsyncFunc() && !method->Function()->IsProxy(); } diff --git a/ets2panda/util/options.cpp b/ets2panda/util/options.cpp index 699c636e5b..82dc27f031 100644 --- a/ets2panda/util/options.cpp +++ b/ets2panda/util/options.cpp @@ -303,6 +303,7 @@ void Options::InitializeWarnings() {"subset_aware", {ETSWarnings::SUBSET_AWARE_FIRST, ETSWarnings::SUBSET_AWARE_LAST}}, {"subset_unaware", {ETSWarnings::SUBSET_UNAWARE_FIRST, ETSWarnings::SUBSET_UNAWARE_LAST}}}; const auto setWarningRange = [&warningSet, v](size_t first, size_t last) { + ES2PANDA_ASSERT(last < ETSWarnings::COUNT); for (size_t i = first; i <= last; i++) { warningSet[i] = v; } diff --git a/ets2panda/util/path.cpp b/ets2panda/util/path.cpp index 995424b524..ad902018c6 100644 --- a/ets2panda/util/path.cpp +++ b/ets2panda/util/path.cpp @@ -75,7 +75,7 @@ void Path::InitializeFileName() } } - int extensionPosition = fileNameWithExtension_.Mutf8().find_last_of('.'); + size_t extensionPosition = fileNameWithExtension_.Mutf8().find_last_of('.'); fileName_ = fileNameWithExtension_.Substr(0, extensionPosition); } @@ -85,7 +85,7 @@ void Path::InitializeFileNameWithExtension() return; } - int position = path_.Mutf8().find_last_of(PATH_DELIMITER); + size_t position = path_.Mutf8().find_last_of(PATH_DELIMITER); fileNameWithExtension_ = path_.Substr(position + 1, path_.Length()); } @@ -114,7 +114,7 @@ void Path::InitializeAbsoluteParentFolder() return; } - int position = absolutePath_.Mutf8().find_last_of(PATH_DELIMITER); + size_t position = absolutePath_.Mutf8().find_last_of(PATH_DELIMITER); absoluteParentFolder_ = absolutePath_.Substr(0, position); } @@ -125,7 +125,7 @@ void Path::InitializeParentFolder() return; } - int position = path_.Mutf8().find_last_of(PATH_DELIMITER); + size_t position = path_.Mutf8().find_last_of(PATH_DELIMITER); parentFolder_ = path_.Substr(0, position); } diff --git a/ets2panda/util/ustring.h b/ets2panda/util/ustring.h index be6a745d60..b9106cc62b 100644 --- a/ets2panda/util/ustring.h +++ b/ets2panda/util/ustring.h @@ -202,6 +202,7 @@ public: inline void Reset(size_t offset) { + ES2PANDA_ASSERT(sv_.begin() + offset <= sv_.end()); iter_ = sv_.begin() + offset; } @@ -360,6 +361,7 @@ private: void Alloc() { str_ = allocator_->New(allocator_->Adapter()); + ES2PANDA_ASSERT(str_ != nullptr); } protected: @@ -481,6 +483,7 @@ std::string StringView::EscapeSymbol() const template void StringView::Utf8Encode(T *str, char32_t cu) { + ES2PANDA_ASSERT(str != nullptr); if (cu < Constants::UTF8_1BYTE_LIMIT) { str->push_back(static_cast(cu)); } else if (cu < Constants::UTF8_2BYTE_LIMIT) { diff --git a/ets2panda/varbinder/ETSBinder.cpp b/ets2panda/varbinder/ETSBinder.cpp index 7b44def38d..27d9d01460 100644 --- a/ets2panda/varbinder/ETSBinder.cpp +++ b/ets2panda/varbinder/ETSBinder.cpp @@ -105,6 +105,7 @@ static void CreateDummyVariable(ETSBinder *varBinder, ir::Identifier *ident) void ETSBinder::LookupTypeReference(ir::Identifier *ident, bool allowDynamicNamespaces) { + ES2PANDA_ASSERT(ident != nullptr); if (ident->Variable() != nullptr && ident->Variable()->Declaration()->Node() == ident) { return; } @@ -258,6 +259,7 @@ void ETSBinder::LookupIdentReference(ir::Identifier *ident) if (res.level != 0) { ES2PANDA_ASSERT(res.variable != nullptr); + ES2PANDA_ASSERT(GetScope()->EnclosingVariableScope() != nullptr); auto *outerFunction = GetScope()->EnclosingVariableScope()->Node(); if ((!outerFunction->IsScriptFunction() || !outerFunction->AsScriptFunction()->IsArrow()) && @@ -361,6 +363,7 @@ void ETSBinder::ResolveInterfaceDeclaration(ir::TSInterfaceDeclaration *decl) ResolveReference(stmt); + ES2PANDA_ASSERT(stmt->AsClassProperty()->Id() != nullptr); auto fieldVar = ResolvePropertyReference(stmt->AsClassProperty(), decl->Scope()->AsClassScope()) ->FindLocal(stmt->AsClassProperty()->Id()->Name(), varbinder::ResolveBindingOptions::BINDINGS); @@ -394,6 +397,7 @@ void ETSBinder::BuildMethodDefinition(ir::MethodDefinition *methodDef) methodDef->BaseOverloadMethod()->GetTopStatement() != methodDef->GetTopStatement()) { return; } + ES2PANDA_ASSERT(methodDef->Function() != nullptr); if (methodDef->Function()->TypeParams() != nullptr) { auto scopeCtx = LexicalScope::Enter(this, methodDef->Function()->TypeParams()->Scope()); ResolveReferences(methodDef->Function()->TypeParams()); @@ -451,6 +455,7 @@ void ETSBinder::ResolveMethodDefinition(ir::MethodDefinition *methodDef) } auto *thisParam = AddMandatoryParam(MANDATORY_PARAM_THIS); + ES2PANDA_ASSERT(thisParam != nullptr); thisParam->Declaration()->BindNode(thisParam_); } @@ -510,6 +515,7 @@ void ETSBinder::BuildClassDefinitionImpl(ir::ClassDefinition *classDef) auto *const prop = stmt->AsClassProperty(); auto fieldScope = ResolvePropertyReference(prop, classDef->Scope()->AsClassScope()); + ES2PANDA_ASSERT(prop->Id() != nullptr); auto fieldName = prop->Id()->Name(); if (auto fieldVar = fieldScope->FindLocal(fieldName, varbinder::ResolveBindingOptions::BINDINGS); fieldVar != nullptr) { @@ -544,6 +550,7 @@ void ETSBinder::AddFunctionThisParam(ir::ScriptFunction *func) { auto paramScopeCtx = LexicalScope::Enter(this, func->Scope()->ParamScope()); auto *thisParam = AddMandatoryParam(MANDATORY_PARAM_THIS); + ES2PANDA_ASSERT(thisParam != nullptr); thisParam->Declaration()->BindNode(thisParam_); } @@ -555,7 +562,7 @@ void ETSBinder::AddDynamicImport(ir::ETSImportDeclaration *import) void ETSBinder::BuildProxyMethod(ir::ScriptFunction *func, const util::StringView &containingClassName, bool isExternal) { - ES2PANDA_ASSERT(!containingClassName.Empty()); + ES2PANDA_ASSERT(!containingClassName.Empty() && func != nullptr); func->Scope()->BindName(containingClassName); if (!func->IsAsyncFunc() && !isExternal) { @@ -641,6 +648,7 @@ void AddOverloadFlag(ArenaAllocator *allocator, bool isStdLib, varbinder::Variab return; } + ES2PANDA_ASSERT(method->Function() != nullptr); if (!method->Overloads().empty() && !method->HasOverload(currentNode)) { method->AddOverload(currentNode); currentNode->Function()->Id()->SetVariable(importedVar); @@ -1514,6 +1522,7 @@ void ETSBinder::ValidateReexportDeclaration(ir::ETSReExportDeclaration *decl) bool ETSBinder::ImportGlobalPropertiesForNotDefaultedExports(varbinder::Variable *var, const util::StringView &name, const ir::ClassElement *classElement) { + ES2PANDA_ASSERT(var != nullptr); if (var->Declaration()->Node()->IsDefaultExported()) { return false; } @@ -1554,7 +1563,7 @@ void ETSBinder::ImportGlobalProperties(const ir::ClassDefinition *const classDef continue; } - ES2PANDA_ASSERT(classElement->IsStatic()); + ES2PANDA_ASSERT(classElement->IsStatic() && classElement->Id() != nullptr); const auto &name = classElement->Id()->Name(); auto *const var = scopeCtx.GetScope()->FindLocal(name, ResolveBindingOptions::ALL); ES2PANDA_ASSERT(var != nullptr); diff --git a/ets2panda/varbinder/scope.cpp b/ets2panda/varbinder/scope.cpp index fb13142b90..3fb54162e2 100644 --- a/ets2panda/varbinder/scope.cpp +++ b/ets2panda/varbinder/scope.cpp @@ -429,6 +429,7 @@ Variable *ParamScope::AddParameter(ArenaAllocator *allocator, Decl *newDecl, Var ES2PANDA_ASSERT(newDecl->IsParameterDecl()); auto *param = allocator->New(newDecl, flags); + ES2PANDA_ASSERT(param != nullptr); param->SetScope(this); params_.emplace_back(param); @@ -492,13 +493,12 @@ Variable *AnnotationParamScope::AddBinding([[maybe_unused]] ArenaAllocator *allo [[maybe_unused]] ScriptExtension extension) { auto *ident = newDecl->Node()->AsClassProperty()->Id(); + ES2PANDA_ASSERT(ident != nullptr); auto annoVar = allocator->New(newDecl, VariableFlags::PROPERTY); auto var = InsertBinding(ident->Name(), annoVar).first->second; if (var != nullptr) { var->SetScope(this); - if (ident != nullptr) { - ident->SetVariable(var); - } + ident->SetVariable(var); } return var; } @@ -718,6 +718,7 @@ void ModuleScope::AddImportDecl(ir::ImportDeclaration *importDecl, ImportDeclLis void ModuleScope::AddExportDecl(ir::AstNode *exportDecl, ExportDecl *decl) { + ES2PANDA_ASSERT(decl != nullptr); decl->BindNode(exportDecl); ArenaVector decls(allocator_->Adapter()); @@ -747,6 +748,7 @@ Variable *ModuleScope::AddImport(ArenaAllocator *allocator, Variable *currentVar } auto *variable = allocator->New(newDecl, VariableFlags::NONE); + ES2PANDA_ASSERT(variable != nullptr); variable->ExoticName() = newDecl->AsImportDecl()->ImportName(); InsertBinding(newDecl->Name(), variable); return variable; @@ -1007,6 +1009,7 @@ void LoopDeclarationScope::ConvertToVariableScope(ArenaAllocator *allocator) if (loopType_ == ScopeType::LOOP_DECL) { auto *parentVarScope = Parent()->EnclosingVariableScope(); + ES2PANDA_ASSERT(parentVarScope != nullptr); slotIndex_ = std::max(slotIndex_, parentVarScope->LexicalSlots()); evalBindings_ = parentVarScope->EvalBindings(); initScope_ = allocator->New(allocator, Parent()); -- Gitee From 5499636b187f68a4506f9407e036362683e648a0 Mon Sep 17 00:00:00 2001 From: lirismankarina Date: Mon, 30 Jun 2025 19:43:56 +0300 Subject: [PATCH 088/145] Fix codecheck MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: [新需求]: codecheck fix https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIYSG Description: some code style fixes for frontend Reason: clear code style needed Tests: all tests passed Signed-off-by: lirismankarina --- .../ets/constantExpressionLowering.cpp | 3 ++ .../lowering/ets/declareOverloadLowering.cpp | 2 ++ ...defaultParametersInConstructorLowering.cpp | 12 ++++++-- .../compiler/lowering/ets/enumLowering.cpp | 7 +++++ .../lowering/ets/exportAnonymousConst.cpp | 1 + .../lowering/ets/expressionLambdaLowering.cpp | 1 + .../lowering/ets/genericBridgesLowering.cpp | 6 +++- .../ets/interfaceObjectLiteralLowering.cpp | 8 ++++- .../ets/interfacePropertyDeclarations.cpp | 1 + .../compiler/lowering/ets/lambdaLowering.cpp | 29 ++++++++++++++----- .../lowering/ets/lateInitialization.cpp | 2 ++ ets2panda/ir/ets/etsClassLiteral.cpp | 1 + ets2panda/ir/ets/etsFunctionType.cpp | 1 + ets2panda/ir/ets/etsKeyofType.cpp | 2 ++ ets2panda/ir/ets/etsNeverType.cpp | 1 + .../ir/ets/etsNewArrayInstanceExpression.cpp | 1 + .../ir/ets/etsNewClassInstanceExpression.cpp | 1 + .../etsNewMultiDimArrayInstanceExpression.cpp | 1 + ets2panda/ir/ets/etsNonNullishTypeNode.cpp | 1 + ets2panda/ir/ets/etsNullishTypes.cpp | 2 ++ ets2panda/ir/ets/etsPackageDeclaration.cpp | 1 + ets2panda/ir/ets/etsParameterExpression.cpp | 1 + ets2panda/ir/ets/etsParameterExpression.h | 1 + ets2panda/ir/ets/etsPrimitiveType.cpp | 1 + ets2panda/ir/ets/etsStringLiteralType.cpp | 1 + ets2panda/ir/ets/etsTuple.cpp | 2 ++ ets2panda/ir/ets/etsTypeReferencePart.cpp | 1 + ets2panda/ir/ets/etsUnionType.cpp | 1 + ets2panda/ir/expressions/arrayExpression.cpp | 3 ++ .../expressions/arrowFunctionExpression.cpp | 3 ++ .../ir/expressions/assignmentExpression.cpp | 1 + ets2panda/ir/expressions/awaitExpression.cpp | 1 + ets2panda/ir/expressions/binaryExpression.cpp | 1 + ets2panda/ir/expressions/binaryExpression.h | 2 ++ ets2panda/ir/expressions/blockExpression.cpp | 1 + 35 files changed, 92 insertions(+), 12 deletions(-) diff --git a/ets2panda/compiler/lowering/ets/constantExpressionLowering.cpp b/ets2panda/compiler/lowering/ets/constantExpressionLowering.cpp index de86a2313a..96da74bb4b 100644 --- a/ets2panda/compiler/lowering/ets/constantExpressionLowering.cpp +++ b/ets2panda/compiler/lowering/ets/constantExpressionLowering.cpp @@ -346,6 +346,7 @@ ir::AstNode *ConstantExpressionLowering::FoldBinaryBooleanConstant(ir::BinaryExp } auto resNode = util::NodeAllocator::Alloc(context_->allocator, result); + ES2PANDA_ASSERT(resNode); resNode->SetParent(expr->Parent()); resNode->SetRange(expr->Range()); return resNode; @@ -545,6 +546,7 @@ ir::AstNode *ConstantExpressionLowering::FoldBinaryStringConstant(ir::BinaryExpr auto const rhs = expr->Right()->AsLiteral(); auto const resStr = util::UString(lhs->ToString() + rhs->ToString(), context_->allocator).View(); auto resNode = util::NodeAllocator::Alloc(context_->allocator, resStr); + ES2PANDA_ASSERT(resNode); resNode->SetParent(expr->Parent()); resNode->SetRange(expr->Range()); return resNode; @@ -758,6 +760,7 @@ ir::AstNode *ConstantExpressionLowering::FoldTSAsExpression(ir::TSAsExpression * ir::AstNode *ConstantExpressionLowering::FoldMultilineString(ir::TemplateLiteral *expr) { auto *result = util::NodeAllocator::Alloc(context_->allocator, expr->GetMultilineString()); + ES2PANDA_ASSERT(result); result->SetParent(expr->Parent()); result->SetRange(expr->Range()); return result; diff --git a/ets2panda/compiler/lowering/ets/declareOverloadLowering.cpp b/ets2panda/compiler/lowering/ets/declareOverloadLowering.cpp index b9679b253f..1d8d05f946 100644 --- a/ets2panda/compiler/lowering/ets/declareOverloadLowering.cpp +++ b/ets2panda/compiler/lowering/ets/declareOverloadLowering.cpp @@ -34,6 +34,7 @@ void GenerateOverloadHelperParams(public_lib::Context *ctx, uint32_t minArg, siz id->SetTsTypeAnnotation(typeAnnotation); typeAnnotation->SetParent(id); auto *param = ctx->AllocNode(id, false, allocator); + ES2PANDA_ASSERT(param); param->SetOptional(idx >= minArg); params.push_back(param); } @@ -84,6 +85,7 @@ void BuildOverloadHelperFunction(public_lib::Context *ctx, ir::MethodDefinition method->Modifiers(), allocator, false); method->AddOverload(helperOverload); + ES2PANDA_ASSERT(helperOverload->Function()); helperOverload->Function()->ClearFlag((ir::ScriptFunctionFlags::OVERLOAD)); helperOverload->SetParent(method); diff --git a/ets2panda/compiler/lowering/ets/defaultParametersInConstructorLowering.cpp b/ets2panda/compiler/lowering/ets/defaultParametersInConstructorLowering.cpp index d9ede70dc7..ed4192d4e8 100644 --- a/ets2panda/compiler/lowering/ets/defaultParametersInConstructorLowering.cpp +++ b/ets2panda/compiler/lowering/ets/defaultParametersInConstructorLowering.cpp @@ -63,6 +63,7 @@ static bool HasDefaultParameters(const ir::ScriptFunction *function, util::Diagn static ir::TSTypeParameterDeclaration *CreateParameterDeclaraion(ir::MethodDefinition *method, public_lib::Context *ctx) { auto const allocator = ctx->allocator; + ES2PANDA_ASSERT(method->Function()); if (method->Function()->TypeParams() == nullptr || method->Function()->TypeParams()->Params().empty()) { return nullptr; } @@ -90,6 +91,7 @@ static ir::FunctionSignature CreateFunctionSignature(ir::MethodDefinition *metho auto const allocator = ctx->allocator; ir::TSTypeParameterDeclaration *typeParamDecl = CreateParameterDeclaraion(method, ctx); + ES2PANDA_ASSERT(method->Function()); auto *returnTypeAnnotation = method->Function()->ReturnTypeAnnotation() != nullptr ? method->Function()->ReturnTypeAnnotation()->Clone(allocator, nullptr)->AsTypeNode() @@ -103,7 +105,8 @@ static ir::TSTypeParameterInstantiation *CreateTypeParameterInstantiation(ir::Me { auto const allocator = ctx->allocator; - if (method->Function()->TypeParams() == nullptr || method->Function()->TypeParams()->Params().empty()) { + if ((method->Function() != nullptr && method->Function()->TypeParams() == nullptr) || + method->Function()->TypeParams()->Params().empty()) { return nullptr; } ArenaVector selfParams(allocator->Adapter()); @@ -131,6 +134,7 @@ static ir::BlockStatement *CreateFunctionBody(ir::MethodDefinition *method, publ auto const allocator = ctx->allocator; ArenaVector funcStatements(allocator->Adapter()); + ES2PANDA_ASSERT(method->Id()); auto *const callee = util::NodeAllocator::ForceSetParent(allocator, method->Id()->Name(), allocator); @@ -163,6 +167,7 @@ static ir::FunctionExpression *CreateFunctionExpression(ir::MethodDefinition *me allocator, allocator, ir::ScriptFunction::ScriptFunctionData { body, std::move(signature), method->Function()->Flags(), {}, method->Function()->Language()}); + ES2PANDA_ASSERT(method->Function()); funcNode->AddModifier(method->Function()->Modifiers()); funcNode->SetRange({startLoc, endLoc}); @@ -184,6 +189,7 @@ static void CreateFunctionOverload(ir::MethodDefinition *method, ArenaVectorFunction()->AddFlag(ir::ScriptFunctionFlags::OVERLOAD); overloadMethod->SetRange(funcExpression->Range()); + ES2PANDA_ASSERT(overloadMethod->Function()); if (!method->IsDeclare() && method->Parent()->IsTSInterfaceBody()) { overloadMethod->Function()->Body()->AsBlockStatement()->Statements().clear(); } @@ -195,6 +201,7 @@ static void CreateFunctionOverload(ir::MethodDefinition *method, ArenaVectorallocator; for (auto p : function->Params()) { @@ -219,6 +226,7 @@ static void ClearOptionalParameters(public_lib::Context *ctx, ir::ScriptFunction if (oldParam->IsOptional()) { param = util::NodeAllocator::ForceSetParent(allocator, oldParam->Ident(), false, allocator); + ES2PANDA_ASSERT(param); param->SetParent(function); } ES2PANDA_ASSERT(!param->AsETSParameterExpression()->IsOptional()); @@ -245,7 +253,7 @@ static void ProcessGlobalFunctionDefinition(ir::MethodDefinition *method, public for (size_t i = 0; i < params.size() - paramsToCut; ++i) { auto param = params[i]->AsETSParameterExpression(); callArgs.push_back(param->Ident()->CloneReference(allocator, nullptr)->AsIdentifier()); - + ES2PANDA_ASSERT(param->Ident()->Clone(allocator, nullptr)); functionParams.push_back(allocator->New( param->Ident()->Clone(allocator, nullptr)->AsIdentifier(), false, allocator)); } diff --git a/ets2panda/compiler/lowering/ets/enumLowering.cpp b/ets2panda/compiler/lowering/ets/enumLowering.cpp index f13666933d..5212c1dc3a 100644 --- a/ets2panda/compiler/lowering/ets/enumLowering.cpp +++ b/ets2panda/compiler/lowering/ets/enumLowering.cpp @@ -39,6 +39,7 @@ namespace { [[nodiscard]] ir::Identifier *MakeParamRefIdent(public_lib::Context *ctx, ir::ETSParameterExpression *paramExpr) { auto *const refIdent = ctx->AllocNode(paramExpr->Ident()->Name(), ctx->Allocator()); + ES2PANDA_ASSERT(refIdent); refIdent->SetRange(paramExpr->Ident()->Range()); refIdent->SetVariable(paramExpr->Ident()->Variable()); return refIdent; @@ -413,13 +414,17 @@ void EnumLoweringPhase::ProcessEnumClassDeclaration(ir::TSEnumDeclaration *const auto *ident = enumClassDecl->Definition()->Ident(); if (flags.isLocal) { auto *scope = NearestScope(enumDecl->Parent()); + ES2PANDA_ASSERT(scope); auto localCtx = varbinder::LexicalScope::Enter(varbinder_, scope); + ES2PANDA_ASSERT(scope); scope->EraseBinding(ident->Name()); InitScopesPhaseETS::RunExternalNode(enumClassDecl, varbinder_); var = varbinder_->GetScope()->FindLocal(ident->Name(), varbinder::ResolveBindingOptions::ALL); } else if (flags.isTopLevel) { auto *scope = program_->GlobalClassScope(); + ES2PANDA_ASSERT(scope); auto localCtx = varbinder::LexicalScope::Enter(varbinder_, scope); + ES2PANDA_ASSERT(scope); scope->StaticDeclScope()->EraseBinding(ident->Name()); InitScopesPhaseETS::RunExternalNode(enumClassDecl, varbinder_); var = varbinder_->GetScope()->FindLocal(ident->Name(), varbinder::ResolveBindingOptions::ALL); @@ -791,11 +796,13 @@ ir::VariableDeclaration *CreateForLoopInitVariableDeclaration(public_lib::Contex { auto *const init = ctx->AllocNode("0"); auto *const decl = ctx->AllocNode(ir::VariableDeclaratorFlag::LET, loopIdentifier, init); + ES2PANDA_ASSERT(loopIdentifier); loopIdentifier->SetParent(decl); ArenaVector decls(ctx->Allocator()->Adapter()); decls.push_back(decl); auto *const declaration = ctx->AllocNode( ir::VariableDeclaration::VariableDeclarationKind::LET, ctx->Allocator(), std::move(decls)); + ES2PANDA_ASSERT(decl); decl->SetParent(declaration); return declaration; } diff --git a/ets2panda/compiler/lowering/ets/exportAnonymousConst.cpp b/ets2panda/compiler/lowering/ets/exportAnonymousConst.cpp index 3cb3fd1c24..029659c547 100644 --- a/ets2panda/compiler/lowering/ets/exportAnonymousConst.cpp +++ b/ets2panda/compiler/lowering/ets/exportAnonymousConst.cpp @@ -103,6 +103,7 @@ static void HandleExportDefaultInExportNamedDecl(public_lib::Context *const ctx, exports.emplace_back(specifier); auto *exportDefaulNamedDecl = allocator->New( allocator, static_cast(nullptr), std::move(exports)); + ES2PANDA_ASSERT(exportDefaulNamedDecl); exportDefaulNamedDecl->AddModifier(ir::ModifierFlags::DEFAULT_EXPORT); exportDefaulNamedDeclarations.push_back(exportDefaulNamedDecl); continue; diff --git a/ets2panda/compiler/lowering/ets/expressionLambdaLowering.cpp b/ets2panda/compiler/lowering/ets/expressionLambdaLowering.cpp index 7d4112c7f6..e09b2b2af2 100644 --- a/ets2panda/compiler/lowering/ets/expressionLambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/expressionLambdaLowering.cpp @@ -37,6 +37,7 @@ static ir::AstNode *ConvertExpression(public_lib::Context *ctx, ir::ArrowFunctio auto *const block = ctx->AllocNode(allocator, std::move(statements)); + ES2PANDA_ASSERT(block); block->SetScope(scope); block->SetParent(function); diff --git a/ets2panda/compiler/lowering/ets/genericBridgesLowering.cpp b/ets2panda/compiler/lowering/ets/genericBridgesLowering.cpp index 36ce44662c..0805641419 100644 --- a/ets2panda/compiler/lowering/ets/genericBridgesLowering.cpp +++ b/ets2panda/compiler/lowering/ets/genericBridgesLowering.cpp @@ -86,6 +86,7 @@ void GenericBridgesPhase::AddGenericBridge(ir::ClassDefinition const *const clas auto *const bridgeMethod = parser->CreateFormattedClassMethodDefinition(sourceCode, typeNodes)->AsMethodDefinition(); + ES2PANDA_ASSERT(bridgeMethod); bridgeMethod->AddModifier(methodDefinition->Modifiers()); bridgeMethod->ClearModifier(ir::ModifierFlags::NATIVE | ir::ModifierFlags::ABSTRACT); bridgeMethod->AddAstNodeFlags(methodDefinition->GetAstNodeFlags()); @@ -143,6 +144,7 @@ void GenericBridgesPhase::ProcessScriptFunction(ir::ClassDefinition const *const // We are not interested in functions that either don't have type parameters at all // or have type parameters that are not modified in the derived class + ES2PANDA_ASSERT(baseFunction); auto const *baseSignature1 = baseFunction->Signature()->Substitute(relation, substitutions.baseConstraints); if (baseSignature1 == baseFunction->Signature()) { return; @@ -214,6 +216,7 @@ void GenericBridgesPhase::CreateGenericBridges(ir::ClassDefinition const *const if (item->IsMethodDefinition()) { // Skip `static`, `final` and special methods... auto *const method = item->AsMethodDefinition(); + ES2PANDA_ASSERT(method->Id()); if (method->Kind() != ir::MethodDefinitionKind::METHOD || method->IsStatic() || method->IsFinal() || method->Id()->Name().Utf8().find("lambda$invoke$") != std::string_view::npos) { continue; @@ -272,7 +275,7 @@ void GenericBridgesPhase::ProcessInterfaces(ir::ClassDefinition *const classDefi !typeParameters.empty()) { if (Substitutions substitutions = GetSubstitutions(interfaceType, typeParameters); // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) - !substitutions.derivedSubstitutions->empty()) { + (substitutions.derivedSubstitutions != nullptr) && !substitutions.derivedSubstitutions->empty()) { ES2PANDA_ASSERT(interfaceType->GetDeclNode()->IsTSInterfaceDeclaration()); auto const &interfaceBody = interfaceType->GetDeclNode()->AsTSInterfaceDeclaration()->Body()->Body(); CreateGenericBridges(classDefinition, substitutions, interfaceBody); @@ -303,6 +306,7 @@ ir::ClassDefinition *GenericBridgesPhase::ProcessClassDefinition(ir::ClassDefini // Check if the class derived from base generic class has either explicit class type substitutions // or type parameters with narrowing constraints. if (Substitutions substitutions = GetSubstitutions(superType, typeParameters); + (substitutions.derivedSubstitutions != nullptr) && // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) !substitutions.derivedSubstitutions->empty()) { // If it has, then probably the generic bridges should be created. diff --git a/ets2panda/compiler/lowering/ets/interfaceObjectLiteralLowering.cpp b/ets2panda/compiler/lowering/ets/interfaceObjectLiteralLowering.cpp index 7b00e071ae..a709cf3eb3 100644 --- a/ets2panda/compiler/lowering/ets/interfaceObjectLiteralLowering.cpp +++ b/ets2panda/compiler/lowering/ets/interfaceObjectLiteralLowering.cpp @@ -72,6 +72,7 @@ static ir::ClassProperty *CreateAnonClassField(public_lib::Context *ctx, ir::Met { auto *const parser = ctx->parser->AsETSParser(); // Field type annotation + ES2PANDA_ASSERT(ifaceMethod->Function()); auto *fieldType = ifaceMethod->Function()->Signature()->ReturnType(); std::stringstream sourceCode; @@ -105,7 +106,7 @@ static ir::MethodDefinition *CreateAnonClassFieldGetterSetter(public_lib::Contex sourceCode << "public set @@I1 (anonParam:@@T2){" << std::endl; sourceCode << "this.@@I3 = anonParam" << std::endl; sourceCode << "}" << std::endl; - + ES2PANDA_ASSERT(ifaceMethod->Id()); return parser ->CreateFormattedClassMethodDefinition(sourceCode.str(), ifaceMethod->Id()->Name(), fieldType, anonClassFieldName) @@ -131,6 +132,7 @@ static void FillClassBody(public_lib::Context *ctx, ArenaVector * ES2PANDA_ASSERT(it->IsMethodDefinition()); auto *ifaceMethod = it->AsMethodDefinition(); + ES2PANDA_ASSERT(ifaceMethod->Function()); if (!ifaceMethod->Function()->IsGetter()) { continue; } @@ -201,6 +203,7 @@ static void AnnotateGeneratedAnonClass(checker::ETSChecker *checker, ir::ClassDe checker->ProgramAllocNode(Signatures::INTERFACE_OBJ_LITERAL, checker->ProgramAllocator()); annoId->SetAnnotationUsage(); auto *annoUsage = checker->ProgramAllocNode(annoId, checker->ProgramAllocator()); + ES2PANDA_ASSERT(annoUsage); annoUsage->AddModifier(ir::ModifierFlags::ANNOTATION_USAGE); annoUsage->SetParent(classDef); annoId->SetParent(annoUsage); @@ -254,6 +257,7 @@ static void GenerateAnonClassTypeFromInterface(public_lib::Context *ctx, ir::TSI // Class implements auto *classImplements = ctx->AllocNode( ctx->AllocNode(ifaceNode->TsType(), ctx->Allocator())); + ES2PANDA_ASSERT(classImplements); classImplements->SetParent(classDef); classDef->Implements().emplace_back(classImplements); classType->RemoveObjectFlag(checker::ETSObjectFlags::RESOLVED_INTERFACES); @@ -331,6 +335,7 @@ static checker::Type *ProcessDeclNode(checker::ETSChecker *checker, checker::ETS continue; } + ES2PANDA_ASSERT(it->AsMethodDefinition()->Id()); checker->LogError(diagnostic::ABSTRACT_METH_IN_ABSTRACT_CLASS, {it->AsMethodDefinition()->Id()->Name()}, objExpr->Start()); return checker->GlobalTypeError(); @@ -379,6 +384,7 @@ static bool CheckInterfaceShouldGenerateAnonClass(ir::TSInterfaceDeclaration *in for (auto it : interfaceDecl->Body()->Body()) { ES2PANDA_ASSERT(it->IsMethodDefinition()); auto methodDef = it->AsMethodDefinition(); + ES2PANDA_ASSERT(methodDef->Function()); if (!methodDef->Function()->IsGetter() && !methodDef->Function()->IsSetter()) { return false; } diff --git a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp index c997421bf4..f9832dc3c3 100644 --- a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp +++ b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp @@ -191,6 +191,7 @@ static void AddOverload(ir::MethodDefinition *method, ir::MethodDefinition *over { method->AddOverload(overload); overload->SetParent(method); + ES2PANDA_ASSERT(overload->Function()); overload->Function()->AddFlag(ir::ScriptFunctionFlags::OVERLOAD); overload->Function()->Id()->SetVariable(variable); } diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index 7584547082..5cc23e4d04 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -113,6 +113,7 @@ static std::pair Clon auto *newTypeParamNode = util::NodeAllocator::ForceSetParent(allocator, newTypeParamId, nullptr, nullptr, allocator); auto *newTypeParam = allocator->New(); + ES2PANDA_ASSERT(newTypeParam); newTypeParam->SetDeclNode(newTypeParamNode); auto *newTypeParamDecl = allocator->New(newTypeParamId->Name()); @@ -187,6 +188,7 @@ ParamsAndVarMap CreateLambdaCalleeParameters(public_lib::Context *ctx, ir::Arrow auto *oldParamType = oldParam->AsETSParameterExpression()->Ident()->TsType(); auto *newParamType = oldParamType->Substitute(checker->Relation(), substitution); auto *newParam = oldParam->AsETSParameterExpression()->Clone(allocator, nullptr); + ES2PANDA_ASSERT(newParam); if (newParam->IsOptional()) { newParam->SetOptional(false); newParamType = checker->CreateETSUnionType({newParamType, checker->GlobalETSUndefinedType()}); @@ -288,6 +290,7 @@ static ir::MethodDefinition *SetUpCalleeMethod(public_lib::Context *ctx, LambdaI var->AddFlag(varbinder::VariableFlags::METHOD); var->SetScope(scopeForMethod); func->Id()->SetVariable(var); + ES2PANDA_ASSERT(method->Id()); method->Id()->SetVariable(var); if (info->callReceiver != nullptr) { auto paramScopeCtx = varbinder::LexicalScope::Enter(varBinder, paramScope); @@ -333,10 +336,8 @@ static ir::MethodDefinition *CreateCalleeMethod(public_lib::Context *ctx, ir::Ar auto [params, vMap] = CreateLambdaCalleeParameters(ctx, lambda, *info->capturedVars, paramScope, substitution); auto varMap = std::move(vMap); - auto *returnType = - cmInfo->forcedReturnType != nullptr - ? cmInfo->forcedReturnType - : lambda->Function()->Signature()->ReturnType()->Substitute(checker->Relation(), substitution); + auto *alternative = lambda->Function()->Signature()->ReturnType()->Substitute(checker->Relation(), substitution); + auto *returnType = cmInfo->forcedReturnType != nullptr ? cmInfo->forcedReturnType : alternative; auto returnTypeAnnotation = allocator->New(returnType, allocator); auto funcFlags = ir::ScriptFunctionFlags::METHOD | cmInfo->auxFunctionFlags; @@ -352,6 +353,7 @@ static ir::MethodDefinition *CreateCalleeMethod(public_lib::Context *ctx, ir::Ar funcFlags, modifierFlags}); auto *funcScope = cmInfo->body == nullptr ? allocator->New(allocator, paramScope) : cmInfo->body->Scope()->AsFunctionScope(); + ES2PANDA_ASSERT(funcScope); funcScope->BindName(info->calleeClass->Definition()->TsType()->AsETSObjectType()->AssemblerName()); func->SetScope(funcScope); ProcessCalleeMethodBody(cmInfo->body, checker, paramScope, substitution, varMap); @@ -371,9 +373,8 @@ static ir::MethodDefinition *CreateCalleeMethod(public_lib::Context *ctx, ir::Ar */ for (auto [ov, nv] : varMap) { ES2PANDA_ASSERT(ov->Name() == nv->Name()); - auto name = ov->Name(); - funcScope->EraseBinding(name); - funcScope->InsertBinding(name, nv); + funcScope->EraseBinding(ov->Name()); + funcScope->InsertBinding(ov->Name(), nv); } return SetUpCalleeMethod(ctx, info, cmInfo, func, scopeForMethod); @@ -491,6 +492,7 @@ static void CreateLambdaClassConstructor(public_lib::Context *ctx, ir::ClassDefi ir::ScriptFunction::ScriptFunctionData {body, ir::FunctionSignature(nullptr, std::move(params), nullptr), ir::ScriptFunctionFlags::CONSTRUCTOR | ir::ScriptFunctionFlags::IMPLICIT_SUPER_CALL_NEEDED}); + ES2PANDA_ASSERT(func); func->SetIdent(constructorId); auto *funcExpr = util::NodeAllocator::ForceSetParent(allocator, func); @@ -565,7 +567,7 @@ static ArenaVector CreateRestArgumentsArrayReall lciInfo->restParameterIdentifier, lciInfo->restArgumentIdentifier, restParameterIndex, spreadArrIterator, checker->MaybeBoxType(elementType), restParameterIndex, restParameterIndex); } - + ES2PANDA_ASSERT(args); return ArenaVector(std::move(args->AsBlockStatement()->Statements())); } @@ -576,6 +578,7 @@ static void CreateInvokeMethodRestParameter(public_lib::Context *ctx, LambdaClas auto *checker = ctx->checker->AsETSChecker(); auto *restIdent = Gensym(allocator); + ES2PANDA_ASSERT(restIdent); lciInfo->restParameterIdentifier = restIdent->Name(); lciInfo->restArgumentIdentifier = GenName(allocator).View(); auto *spread = allocator->New(ir::AstNodeType::REST_ELEMENT, allocator, restIdent); @@ -753,6 +756,7 @@ static checker::ETSObjectType *FunctionTypeToLambdaProviderType(checker::ETSChec checker::Signature *signature) { if (signature->RestVar() != nullptr) { + ES2PANDA_ASSERT(checker->GlobalBuiltinLambdaType(signature->ArgCount(), true)); return checker->GlobalBuiltinLambdaType(signature->ArgCount(), true)->AsETSObjectType(); } // Note: FunctionN is not supported yet @@ -817,6 +821,7 @@ static ir::ClassDeclaration *CreateEmptyLambdaClassDeclaration(public_lib::Conte lambdaClassName.Append(objectName).Append("$").Append(info->name); + ES2PANDA_ASSERT(lambdaProviderClass); auto *providerTypeReference = checker->AllocNode( checker->AllocNode( checker->AllocNode(lambdaProviderClass->AsETSObjectType()->Name(), checker->Allocator()), @@ -867,6 +872,7 @@ static ir::ClassDeclaration *CreateLambdaClass(public_lib::Context *ctx, checker CreateEmptyLambdaClassDeclaration(ctx, info, newTypeParams, fnInterface, lambdaProviderClass); auto classDefinition = classDeclaration->Definition(); if (info->isFunctionReference) { + ES2PANDA_ASSERT(callee->Function()); classDefinition->SetFunctionalReferenceReferencedMethod(callee); classDefinition->SetModifiers(classDefinition->Modifiers() | ir::ClassDefinitionModifiers::FUNCTIONAL_REFERENCE); @@ -926,8 +932,10 @@ static ir::ETSNewClassInstanceExpression *CreateConstructorCall(public_lib::Cont auto *newExpr = util::NodeAllocator::ForceSetParent( allocator, allocator->New(constructedType, allocator), std::move(args)); auto *lambdaOrFuncRefParent = lambdaOrFuncRef->Parent(); + ES2PANDA_ASSERT(newExpr); newExpr->SetParent(lambdaOrFuncRefParent); // NOTE(dslynko, #19869): Required for correct debug-info generation + ES2PANDA_ASSERT(newExpr); newExpr->SetRange(lambdaOrFuncRefParent != nullptr ? lambdaOrFuncRefParent->Range() : lambdaOrFuncRef->Range()); auto *nearestScope = NearestScope(lambdaOrFuncRef); @@ -1014,6 +1022,7 @@ static ir::ScriptFunction *GetWrappingLambdaParentFunction(public_lib::Context * } bodyStmts.push_back(stmt); func->SetBody(util::NodeAllocator::ForceSetParent(allocator, allocator, std::move(bodyStmts))); + ES2PANDA_ASSERT(func->Body()); func->Body()->SetParent(func); return func; } @@ -1029,6 +1038,7 @@ static ir::ArrowFunctionExpression *CreateWrappingLambda(public_lib::Context *ct auto *func = GetWrappingLambdaParentFunction(ctx, funcRef, signature); auto *lambda = util::NodeAllocator::ForceSetParent(allocator, func, allocator); + ES2PANDA_ASSERT(lambda); lambda->SetParent(parent); auto *nearestScope = NearestScope(lambda); @@ -1113,6 +1123,7 @@ static ir::AstNode *ConvertFunctionReference(public_lib::Context *ctx, ir::Expre ES2PANDA_ASSERT(funcRef->TsType()->IsETSArrowType()); auto *lambdaClass = CreateLambdaClass(ctx, funcRef->TsType()->AsETSFunctionType(), method, &info); auto *constructorCall = CreateConstructorCall(ctx, funcRef, lambdaClass, &info); + ES2PANDA_ASSERT(constructorCall); constructorCall->TsType()->AsETSObjectType()->AddObjectFlag(checker::ETSObjectFlags::FUNCTIONAL_REFERENCE); return constructorCall; @@ -1134,6 +1145,7 @@ static bool IsFunctionOrMethodCall(checker::ETSChecker *checker, ir::CallExpress // Not skip if invoke pattern Union.() where field is of ETSArrowType if (callee->IsMemberExpression()) { auto me = callee->AsMemberExpression(); + ES2PANDA_ASSERT(me->TsType()); if (me->Object()->TsType() != nullptr && checker->GetApparentType(me->Object()->TsType())->IsETSUnionType() && me->TsType()->IsETSMethodType()) { return true; @@ -1174,6 +1186,7 @@ static ir::AstNode *InsertInvokeCall(public_lib::Context *ctx, ir::CallExpressio checker::PropertySearchFlags::SEARCH_IN_INTERFACES); ES2PANDA_ASSERT(prop != nullptr); auto *invoke0Id = allocator->New(invokeMethodName, allocator); + ES2PANDA_ASSERT(invoke0Id); invoke0Id->SetTsType(prop->TsType()); invoke0Id->SetVariable(prop); diff --git a/ets2panda/compiler/lowering/ets/lateInitialization.cpp b/ets2panda/compiler/lowering/ets/lateInitialization.cpp index a6e6b95098..ec9d7ee9b3 100644 --- a/ets2panda/compiler/lowering/ets/lateInitialization.cpp +++ b/ets2panda/compiler/lowering/ets/lateInitialization.cpp @@ -36,6 +36,7 @@ ir::ClassProperty *TransformerClassProperty(public_lib::Context *ctx, ir::ClassP auto annotationType = checker->CreateETSUnionType({property->TsType(), checker->GlobalETSUndefinedType()}); auto typeAnnotation = allocator->New(annotationType, allocator); + ES2PANDA_ASSERT(typeAnnotation); typeAnnotation->SetParent(property); typeAnnotation->SetTsType(annotationType); property->SetTypeAnnotation(typeAnnotation); @@ -75,6 +76,7 @@ static ir::AstNode *TransformerMemberExpression(ir::MemberExpression *memberExpr blockStatements.push_back(parser->CreateFormattedStatement(ss.str(), name)); blockStatements.push_back(parser->CreateFormattedStatement("@@I1 as @@T2", name, typeNode)); auto *res = util::NodeAllocator::ForceSetParent(allocator, std::move(blockStatements)); + ES2PANDA_ASSERT(res); res->SetParent(parent); Recheck(ctx->phaseManager, varbinder, checker, res); diff --git a/ets2panda/ir/ets/etsClassLiteral.cpp b/ets2panda/ir/ets/etsClassLiteral.cpp index fa65001a99..ba0830fb30 100644 --- a/ets2panda/ir/ets/etsClassLiteral.cpp +++ b/ets2panda/ir/ets/etsClassLiteral.cpp @@ -72,6 +72,7 @@ ETSClassLiteral *ETSClassLiteral::Clone(ArenaAllocator *const allocator, AstNode expr->SetParent(clone); } if (parent != nullptr) { + ES2PANDA_ASSERT(clone); clone->SetParent(parent); } diff --git a/ets2panda/ir/ets/etsFunctionType.cpp b/ets2panda/ir/ets/etsFunctionType.cpp index da4e93b20c..5171fe1338 100644 --- a/ets2panda/ir/ets/etsFunctionType.cpp +++ b/ets2panda/ir/ets/etsFunctionType.cpp @@ -155,6 +155,7 @@ ETSFunctionType *ETSFunctionType::Clone(ArenaAllocator *const allocator, AstNode if (!Annotations().empty()) { ArenaVector annotationUsages {allocator->Adapter()}; for (auto *annotationUsage : Annotations()) { + ES2PANDA_ASSERT(annotationUsage->Clone(allocator, clone)); annotationUsages.push_back(annotationUsage->Clone(allocator, clone)->AsAnnotationUsage()); } clone->SetAnnotations(std::move(annotationUsages)); diff --git a/ets2panda/ir/ets/etsKeyofType.cpp b/ets2panda/ir/ets/etsKeyofType.cpp index 2ef1666092..66f076e6fd 100644 --- a/ets2panda/ir/ets/etsKeyofType.cpp +++ b/ets2panda/ir/ets/etsKeyofType.cpp @@ -64,6 +64,7 @@ checker::Type *ETSKeyofType::GetType(checker::ETSChecker *checker) } auto *typeReference = type_->GetType(checker); + ES2PANDA_ASSERT(typeReference); if (typeReference->IsETSPrimitiveType()) { typeReference = checker->MaybeBoxType(typeReference); @@ -88,6 +89,7 @@ ETSKeyofType *ETSKeyofType::Clone(ArenaAllocator *const allocator, AstNode *cons { TypeNode *type = type_->Clone(allocator, nullptr); ETSKeyofType *clone = allocator->New(type, allocator); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/ets/etsNeverType.cpp b/ets2panda/ir/ets/etsNeverType.cpp index 79284dd1f7..5139f9c4fe 100644 --- a/ets2panda/ir/ets/etsNeverType.cpp +++ b/ets2panda/ir/ets/etsNeverType.cpp @@ -73,6 +73,7 @@ checker::Type *ETSNeverType::GetType([[maybe_unused]] checker::ETSChecker *check ETSNeverType *ETSNeverType::Clone(ArenaAllocator *allocator, AstNode *parent) { auto *const clone = allocator->New(allocator); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); diff --git a/ets2panda/ir/ets/etsNewArrayInstanceExpression.cpp b/ets2panda/ir/ets/etsNewArrayInstanceExpression.cpp index a3356c3c10..3df900701a 100644 --- a/ets2panda/ir/ets/etsNewArrayInstanceExpression.cpp +++ b/ets2panda/ir/ets/etsNewArrayInstanceExpression.cpp @@ -84,6 +84,7 @@ ETSNewArrayInstanceExpression *ETSNewArrayInstanceExpression::Clone(ArenaAllocat auto *const typeRef = typeReference_ != nullptr ? typeReference_->Clone(allocator, nullptr) : nullptr; auto *const dimension = dimension_ != nullptr ? dimension_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(typeRef, dimension); + ES2PANDA_ASSERT(clone); if (typeRef != nullptr) { typeRef->SetParent(clone); diff --git a/ets2panda/ir/ets/etsNewClassInstanceExpression.cpp b/ets2panda/ir/ets/etsNewClassInstanceExpression.cpp index 4a32953e5d..7c0b525c0e 100644 --- a/ets2panda/ir/ets/etsNewClassInstanceExpression.cpp +++ b/ets2panda/ir/ets/etsNewClassInstanceExpression.cpp @@ -109,6 +109,7 @@ ETSNewClassInstanceExpression *ETSNewClassInstanceExpression::Clone(ArenaAllocat AstNode *const parent) { auto *const clone = allocator->New(*this, allocator); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.cpp b/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.cpp index a79d71241b..78ea464ef9 100644 --- a/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.cpp +++ b/ets2panda/ir/ets/etsNewMultiDimArrayInstanceExpression.cpp @@ -107,6 +107,7 @@ ETSNewMultiDimArrayInstanceExpression *ETSNewMultiDimArrayInstanceExpression::Cl AstNode *const parent) { auto *const clone = allocator->New(*this, allocator); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/ets/etsNonNullishTypeNode.cpp b/ets2panda/ir/ets/etsNonNullishTypeNode.cpp index 14226f3c0f..00d68dbfce 100644 --- a/ets2panda/ir/ets/etsNonNullishTypeNode.cpp +++ b/ets2panda/ir/ets/etsNonNullishTypeNode.cpp @@ -69,6 +69,7 @@ ETSNonNullishTypeNode *ETSNonNullishTypeNode::Clone(ArenaAllocator *allocator, A { TypeNode *typeNode = typeNode_->Clone(allocator, nullptr); ETSNonNullishTypeNode *clone = allocator->New(typeNode, allocator); + ES2PANDA_ASSERT(clone); clone->SetParent(parent); clone->typeNode_->SetParent(clone); return clone; diff --git a/ets2panda/ir/ets/etsNullishTypes.cpp b/ets2panda/ir/ets/etsNullishTypes.cpp index e3e9e79836..602945adc4 100644 --- a/ets2panda/ir/ets/etsNullishTypes.cpp +++ b/ets2panda/ir/ets/etsNullishTypes.cpp @@ -73,6 +73,7 @@ checker::Type *ETSUndefinedType::GetType([[maybe_unused]] checker::ETSChecker *c ETSUndefinedType *ETSUndefinedType::Clone(ArenaAllocator *allocator, AstNode *parent) { auto *const clone = allocator->New(allocator); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); @@ -151,6 +152,7 @@ ETSNullType *ETSNullType::Clone(ArenaAllocator *allocator, AstNode *parent) if (!Annotations().empty()) { ArenaVector annotationUsages {allocator->Adapter()}; for (auto *annotationUsage : Annotations()) { + ES2PANDA_ASSERT(annotationUsage->Clone(allocator, clone)); annotationUsages.push_back(annotationUsage->Clone(allocator, clone)->AsAnnotationUsage()); } clone->SetAnnotations(std::move(annotationUsages)); diff --git a/ets2panda/ir/ets/etsPackageDeclaration.cpp b/ets2panda/ir/ets/etsPackageDeclaration.cpp index 277abfc2d3..e6de02bf1e 100644 --- a/ets2panda/ir/ets/etsPackageDeclaration.cpp +++ b/ets2panda/ir/ets/etsPackageDeclaration.cpp @@ -69,6 +69,7 @@ ETSPackageDeclaration *ETSPackageDeclaration::Clone(ArenaAllocator *const alloca { auto const name = name_ != nullptr ? name_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(name); + ES2PANDA_ASSERT(clone); if (name != nullptr) { name->SetParent(clone); diff --git a/ets2panda/ir/ets/etsParameterExpression.cpp b/ets2panda/ir/ets/etsParameterExpression.cpp index 382a8a6f11..4f1f375369 100644 --- a/ets2panda/ir/ets/etsParameterExpression.cpp +++ b/ets2panda/ir/ets/etsParameterExpression.cpp @@ -247,6 +247,7 @@ ETSParameterExpression *ETSParameterExpression::Clone(ArenaAllocator *const allo initializer->SetParent(clone); } + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/ets/etsParameterExpression.h b/ets2panda/ir/ets/etsParameterExpression.h index a38f760c79..91013b3372 100644 --- a/ets2panda/ir/ets/etsParameterExpression.h +++ b/ets2panda/ir/ets/etsParameterExpression.h @@ -49,6 +49,7 @@ public: void SetIdent(Identifier *ident) noexcept { ident_ = ident; + ES2PANDA_ASSERT(ident_); ident_->SetParent(this); } diff --git a/ets2panda/ir/ets/etsPrimitiveType.cpp b/ets2panda/ir/ets/etsPrimitiveType.cpp index c18f743502..58f800f0ab 100644 --- a/ets2panda/ir/ets/etsPrimitiveType.cpp +++ b/ets2panda/ir/ets/etsPrimitiveType.cpp @@ -167,6 +167,7 @@ ETSPrimitiveType *ETSPrimitiveType::Clone(ArenaAllocator *const allocator, AstNo if (!Annotations().empty()) { ArenaVector annotationUsages {allocator->Adapter()}; for (auto *annotationUsage : Annotations()) { + ES2PANDA_ASSERT(annotationUsage->Clone(allocator, clone)); annotationUsages.push_back(annotationUsage->Clone(allocator, clone)->AsAnnotationUsage()); } clone->SetAnnotations(std::move(annotationUsages)); diff --git a/ets2panda/ir/ets/etsStringLiteralType.cpp b/ets2panda/ir/ets/etsStringLiteralType.cpp index d6227f2673..83a867e97d 100644 --- a/ets2panda/ir/ets/etsStringLiteralType.cpp +++ b/ets2panda/ir/ets/etsStringLiteralType.cpp @@ -82,6 +82,7 @@ ETSStringLiteralType *ETSStringLiteralType::Clone(ArenaAllocator *allocator, Ast if (!Annotations().empty()) { ArenaVector annotationUsages {allocator->Adapter()}; for (auto *annotationUsage : Annotations()) { + ES2PANDA_ASSERT(annotationUsage->Clone(allocator, clone)); annotationUsages.push_back(annotationUsage->Clone(allocator, clone)->AsAnnotationUsage()); } clone->SetAnnotations(std::move(annotationUsages)); diff --git a/ets2panda/ir/ets/etsTuple.cpp b/ets2panda/ir/ets/etsTuple.cpp index b79654c62e..8de5db97f1 100644 --- a/ets2panda/ir/ets/etsTuple.cpp +++ b/ets2panda/ir/ets/etsTuple.cpp @@ -127,6 +127,7 @@ checker::Type *ETSTuple::GetType(checker::ETSChecker *const checker) auto *tupleType = checker->ProgramAllocator()->New(checker, typeList); if (IsReadonlyType()) { + ES2PANDA_ASSERT(checker->GetReadonlyType(tupleType)); tupleType = checker->GetReadonlyType(tupleType)->AsETSTupleType(); } @@ -137,6 +138,7 @@ checker::Type *ETSTuple::GetType(checker::ETSChecker *const checker) ETSTuple *ETSTuple::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(allocator, size_); + ES2PANDA_ASSERT(clone); clone->AddModifier(flags_); diff --git a/ets2panda/ir/ets/etsTypeReferencePart.cpp b/ets2panda/ir/ets/etsTypeReferencePart.cpp index 5c951356de..17fdfb9667 100644 --- a/ets2panda/ir/ets/etsTypeReferencePart.cpp +++ b/ets2panda/ir/ets/etsTypeReferencePart.cpp @@ -263,6 +263,7 @@ ETSTypeReferencePart *ETSTypeReferencePart::Clone(ArenaAllocator *const allocato prevClone->SetParent(clone); } + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/ets/etsUnionType.cpp b/ets2panda/ir/ets/etsUnionType.cpp index 39860832e4..b454c1bf79 100644 --- a/ets2panda/ir/ets/etsUnionType.cpp +++ b/ets2panda/ir/ets/etsUnionType.cpp @@ -127,6 +127,7 @@ ETSUnionType *ETSUnionType::Clone(ArenaAllocator *const allocator, AstNode *cons if (!Annotations().empty()) { ArenaVector annotationUsages {allocator->Adapter()}; for (auto *annotationUsage : Annotations()) { + ES2PANDA_ASSERT(annotationUsage->Clone(allocator, clone)); annotationUsages.push_back(annotationUsage->Clone(allocator, clone)->AsAnnotationUsage()); } clone->SetAnnotations(std::move(annotationUsages)); diff --git a/ets2panda/ir/expressions/arrayExpression.cpp b/ets2panda/ir/expressions/arrayExpression.cpp index cc9ec65885..a8d90d7e86 100644 --- a/ets2panda/ir/expressions/arrayExpression.cpp +++ b/ets2panda/ir/expressions/arrayExpression.cpp @@ -48,6 +48,7 @@ ArrayExpression::ArrayExpression([[maybe_unused]] Tag const tag, ArrayExpression ArrayExpression *ArrayExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); } @@ -345,6 +346,7 @@ checker::Type *ArrayExpression::CheckPattern(checker::TSChecker *checker) index--; } + ES2PANDA_ASSERT(desc); const checker::TupleTypeInfo tupleTypeInfo = {combinedFlags, minLength, static_cast(desc->properties.size()), false}; return checker->CreateTupleType(desc, std::move(elementFlags), tupleTypeInfo); @@ -413,6 +415,7 @@ checker::VerifiedType ArrayExpression::Check(checker::ETSChecker *checker) std::optional ArrayExpression::ExtractPossiblePreferredType(checker::Type *type) { + ES2PANDA_ASSERT(type); if (type->IsETSArrayType() || type->IsETSTupleType() || type->IsETSResizableArrayType()) { return std::make_optional(type); } diff --git a/ets2panda/ir/expressions/arrowFunctionExpression.cpp b/ets2panda/ir/expressions/arrowFunctionExpression.cpp index c4941954ec..dde0cd72a6 100644 --- a/ets2panda/ir/expressions/arrowFunctionExpression.cpp +++ b/ets2panda/ir/expressions/arrowFunctionExpression.cpp @@ -88,12 +88,14 @@ checker::VerifiedType ArrowFunctionExpression::Check(checker::ETSChecker *checke ArrowFunctionExpression::ArrowFunctionExpression(ArrowFunctionExpression const &other, ArenaAllocator *const allocator) : JsDocAllowed>(static_cast(other), allocator) { + ES2PANDA_ASSERT(other.func_->Clone(allocator, this)); func_ = other.func_->Clone(allocator, this)->AsScriptFunction(); } ArrowFunctionExpression *ArrowFunctionExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(*this, allocator); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); @@ -120,6 +122,7 @@ ir::TypeNode *ArrowFunctionExpression::CreateReturnNodeFromType(checker::ETSChec auto *ident = checker->AllocNode(util::StringView(""), checker->Allocator()); auto *const part = checker->AllocNode(ident, checker->Allocator()); auto *returnNode = checker->AllocNode(part, checker->Allocator()); + ES2PANDA_ASSERT(returnNode); returnNode->SetTsType(returnType); return returnNode; } diff --git a/ets2panda/ir/expressions/assignmentExpression.cpp b/ets2panda/ir/expressions/assignmentExpression.cpp index d6ff928480..2505910c5f 100644 --- a/ets2panda/ir/expressions/assignmentExpression.cpp +++ b/ets2panda/ir/expressions/assignmentExpression.cpp @@ -169,6 +169,7 @@ AssignmentExpression *AssignmentExpression::Clone(ArenaAllocator *const allocato auto *const left = left_ != nullptr ? left_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const right = right_ != nullptr ? right_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(Tag {}, *this, left, right); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); diff --git a/ets2panda/ir/expressions/awaitExpression.cpp b/ets2panda/ir/expressions/awaitExpression.cpp index 6071bd4155..d9e6b54668 100644 --- a/ets2panda/ir/expressions/awaitExpression.cpp +++ b/ets2panda/ir/expressions/awaitExpression.cpp @@ -74,6 +74,7 @@ AwaitExpression *AwaitExpression::Clone(ArenaAllocator *const allocator, AstNode { auto *const argument = argument_ != nullptr ? argument_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(argument); + ES2PANDA_ASSERT(clone); if (argument != nullptr) { argument->SetParent(clone); diff --git a/ets2panda/ir/expressions/binaryExpression.cpp b/ets2panda/ir/expressions/binaryExpression.cpp index 21babd5626..ddfd3f3a06 100644 --- a/ets2panda/ir/expressions/binaryExpression.cpp +++ b/ets2panda/ir/expressions/binaryExpression.cpp @@ -99,6 +99,7 @@ BinaryExpression *BinaryExpression::Clone(ArenaAllocator *const allocator, AstNo auto *const left = left_ != nullptr ? left_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const right = right_ != nullptr ? right_->Clone(allocator, nullptr)->AsExpression() : nullptr; auto *const clone = allocator->New(left, right, operator_); + ES2PANDA_ASSERT(clone); if (operationType_ != nullptr) { clone->SetOperationType(operationType_); diff --git a/ets2panda/ir/expressions/binaryExpression.h b/ets2panda/ir/expressions/binaryExpression.h index e7accbe3b4..7c5d8fa200 100644 --- a/ets2panda/ir/expressions/binaryExpression.h +++ b/ets2panda/ir/expressions/binaryExpression.h @@ -113,6 +113,7 @@ public: void SetLeft(Expression *expr) noexcept { left_ = expr; + ES2PANDA_ASSERT(left_); left_->SetParent(this); SetStart(left_->Start()); } @@ -120,6 +121,7 @@ public: void SetRight(Expression *expr) noexcept { right_ = expr; + ES2PANDA_ASSERT(right_); right_->SetParent(this); SetEnd(right_->End()); } diff --git a/ets2panda/ir/expressions/blockExpression.cpp b/ets2panda/ir/expressions/blockExpression.cpp index c38cb57710..853f4973fc 100644 --- a/ets2panda/ir/expressions/blockExpression.cpp +++ b/ets2panda/ir/expressions/blockExpression.cpp @@ -40,6 +40,7 @@ BlockExpression::BlockExpression([[maybe_unused]] Tag const tag, BlockExpression BlockExpression *BlockExpression::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(Tag {}, *this, allocator); + ES2PANDA_ASSERT(clone); if (parent != nullptr) { clone->SetParent(parent); } -- Gitee From b4bfce88edbd1569f629fd119ba7c90afd89367d Mon Sep 17 00:00:00 2001 From: pengbiao Date: Sat, 5 Jul 2025 14:37:00 +0800 Subject: [PATCH 089/145] Fix es2panda check variance crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICK6TY Signed-off-by: pengbiao --- ets2panda/checker/types/ets/etsObjectType.cpp | 25 +++++++++++++++++-- .../ast/compiler/ets/check_variance_crash.ets | 20 +++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/check_variance_crash.ets diff --git a/ets2panda/checker/types/ets/etsObjectType.cpp b/ets2panda/checker/types/ets/etsObjectType.cpp index 733f658a53..e06913625c 100644 --- a/ets2panda/checker/types/ets/etsObjectType.cpp +++ b/ets2panda/checker/types/ets/etsObjectType.cpp @@ -1336,8 +1336,29 @@ void ETSObjectType::CheckVarianceRecursively(TypeRelation *relation, VarianceFla return; } - auto *params = GetDeclNode()->IsClassDefinition() ? GetDeclNode()->AsClassDefinition()->TypeParams() - : GetDeclNode()->AsTSInterfaceDeclaration()->TypeParams(); + // according to the spec(GENERICS chapter), only class/interface/function/ + // method/lambda and type alias can have type parameters. since + // 1. the type of function and method is ETSFunctionType + // 2. lambda has been checked above + // here we just need check + // 1. class + // 2. interface + // 3. type alias(which will be redirected to its real type) + // And all of them should have declarations + if (declNode_ == nullptr) { + // If the type is not declared, then we do not need to check variance. + return; + } + ir::TSTypeParameterDeclaration *params; + if (GetDeclNode()->IsClassDefinition()) { + params = GetDeclNode()->AsClassDefinition()->TypeParams(); + } else if (GetDeclNode()->IsTSInterfaceDeclaration()) { + params = GetDeclNode()->AsTSInterfaceDeclaration()->TypeParams(); + } else { + // If the type is not a class or interface or type alias, then we do not need to check variance. + return; + } + if (params == nullptr) { return; } diff --git a/ets2panda/test/ast/compiler/ets/check_variance_crash.ets b/ets2panda/test/ast/compiler/ets/check_variance_crash.ets new file mode 100644 index 0000000000..f5bfa6f468 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/check_variance_crash.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. + */ + +type BreakpointType = 'xs' | 'sm' +class BreakPointState { + public update(type: BreakpointType):void { + } +} -- Gitee From 6e0307ef56b919e9ae7644c1dd2311ee4dc5c46a Mon Sep 17 00:00:00 2001 From: a00917162 Date: Sun, 6 Jul 2025 17:25:49 +0300 Subject: [PATCH 090/145] Fix nullptr in async function expression Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKB2I Testing: all CI tests passed. Results are availible in gg watcher. Signed-off-by: Akmaev Aleksey --- ets2panda/parser/ETSparserExpressions.cpp | 10 +++ ...w_function_call_as_record_property_key.ets | 29 +------- .../ets/async-function-expression1.ets | 54 +++++++++++++++ .../ets/async-function-expression2.ets | 66 +++++++++++++++++++ .../compiler/ets/invalid_two_functions.ets | 5 +- .../ets/empty_array_map_inference_fail.ets | 5 +- ets2panda/util/diagnostic/syntax.yaml | 6 +- ets2panda/varbinder/ETSBinder.cpp | 2 +- 8 files changed, 145 insertions(+), 32 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/async-function-expression1.ets create mode 100644 ets2panda/test/ast/compiler/ets/async-function-expression2.ets diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index f8425e7790..7790230f0d 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -364,6 +364,11 @@ ir::Expression *ETSParser::ParsePrimaryExpression(ExpressionParseFlags flags) ParseTypeAliasDeclaration(); // Try to parse type alias and drop the result. return AllocBrokenExpression(rangeToken); } + case lexer::TokenType::KEYW_FUNCTION: { + LogError(diagnostic::FUNC_EXPR); + ParseFunctionDeclaration(true, ir::ModifierFlags::NONE); + return AllocBrokenExpression(Lexer()->GetToken().Loc()); + } case lexer::TokenType::PUNCTUATOR_FORMAT: { return ParseExpressionFormatPlaceholder(); } @@ -685,6 +690,11 @@ ir::Expression *ETSParser::ParseNewExpression() ir::Expression *ETSParser::ParseAsyncExpression() { Lexer()->NextToken(); // eat 'async' + if (Lexer()->GetToken().Type() == lexer::TokenType::KEYW_FUNCTION) { + LogError(diagnostic::FUNC_EXPR); + ParseFunctionDeclaration(true, ir::ModifierFlags::NONE); + return AllocBrokenExpression(Lexer()->GetToken().Loc()); + } if (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS || !IsArrowFunctionExpressionStart()) { LogExpectedToken(lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS); diff --git a/ets2panda/test/ast/compiler/ets/arrow_function_call_as_record_property_key.ets b/ets2panda/test/ast/compiler/ets/arrow_function_call_as_record_property_key.ets index 041edd9bf5..b989234f62 100644 --- a/ets2panda/test/ast/compiler/ets/arrow_function_call_as_record_property_key.ets +++ b/ets2panda/test/ast/compiler/ets/arrow_function_call_as_record_property_key.ets @@ -24,29 +24,6 @@ const b: Record number> = { [(():number => +("bar"))()]: (y: string):number => y.length }; -/* @@? 21:21 Error TypeError: Bad operand type, the type of the operand must be numeric type. */ -/* @@? 21:34 Error SyntaxError: Unexpected token 'function'. */ -/* @@? 21:45 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 21:45 Error SyntaxError: Unexpected token. */ -/* @@? 21:47 Error TypeError: Type 'String' is not compatible with type 'Double' at index 1 */ -/* @@? 21:47 Error TypeError: Type name 'string' used in the wrong context */ -/* @@? 21:53 Error SyntaxError: Unexpected token, expected ':'. */ -/* @@? 21:54 Error SyntaxError: Unexpected token ':'. */ -/* @@? 21:56 Error SyntaxError: Unexpected token. */ -/* @@? 22:9 Error SyntaxError: return keyword should be used in function body. */ -/* @@? 22:16 Error TypeError: All return statements in the function should be empty or have a value. */ -/* @@? 22:16 Error TypeError: Unresolved reference y */ -/* @@? 23:5 Error SyntaxError: Unexpected token '}'. */ -/* @@? 23:6 Error SyntaxError: Unexpected token ','. */ -/* @@? 23:6 Error TypeError: Indexed access is not supported for such expression type. */ -/* @@? 24:32 Error SyntaxError: Unexpected token ':'. */ -/* @@? 24:36 Error SyntaxError: Unexpected token ':'. */ -/* @@? 24:36 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -/* @@? 24:36 Error SyntaxError: Unexpected token ':'. */ -/* @@? 24:38 Error SyntaxError: Unexpected token 'string'. */ -/* @@? 24:38 Error TypeError: Type name 'string' used in the wrong context */ -/* @@? 24:44 Error SyntaxError: Unexpected token ')'. */ -/* @@? 24:45 Error SyntaxError: Unexpected token ':'. */ -/* @@? 24:46 Error SyntaxError: Unexpected token 'number'. */ -/* @@? 24:46 Error TypeError: The type of parameter 'number' cannot be inferred */ -/* @@? 25:1 Error SyntaxError: Unexpected token '}'. */ +/* @@? 21:21 Error TypeError: Bad operand type, the type of the operand must be numeric type. */ +/* @@? 21:34 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 24:21 Error TypeError: Bad operand type, the type of the operand must be numeric type. */ diff --git a/ets2panda/test/ast/compiler/ets/async-function-expression1.ets b/ets2panda/test/ast/compiler/ets/async-function-expression1.ets new file mode 100644 index 0000000000..de02a74245 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/async-function-expression1.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. + */ + +function relationalStoreCustomDirTest() { + it(async function () {}) + + it(async function () { + let storestore = null; + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { + "name": "", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await storestore.insert("test", valueBucket); + }) + + it(async function () { + const STORE_CONFIG = { + name: "", + securityLevel: data_Rdb.SecurityLevel.S1, + customDir: "" + } + let storestore = await data_Rdb.getRdbStore(context, STORE_CONFIG); + await storestore.executeSql(CREATE_TABLE_TEST, null); + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { + "name": "", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await storestore.insert("test", valueBucket); + }) +} +/* @@? 17:5 Error TypeError: Unresolved reference it */ +/* @@? 17:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 19:5 Error TypeError: This expression is not callable. */ +/* @@? 19:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 31:5 Error TypeError: This expression is not callable. */ +/* @@? 31:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ diff --git a/ets2panda/test/ast/compiler/ets/async-function-expression2.ets b/ets2panda/test/ast/compiler/ets/async-function-expression2.ets new file mode 100644 index 0000000000..c4fef79dcf --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/async-function-expression2.ets @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 relationalStoreCustomDirTest() { + it(async function function() {}) + + it(async function function() { + let storestore = null; + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { + "name": "", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await storestore.insert("test", valueBucket); + }) + + it(async function function() { + const STORE_CONFIG = { + name: "", + securityLevel: data_Rdb.SecurityLevel.S1, + customDir: "" + } + let storestore = await data_Rdb.getRdbStore(context, STORE_CONFIG); + await storestore.executeSql(CREATE_TABLE_TEST, null); + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { + "name": "", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await storestore.insert("test", valueBucket); + }) +} +/* @@? 17:5 Error TypeError: Unresolved reference it */ +/* @@? 17:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 17:23 Error SyntaxError: Unexpected token, expected '('. */ +/* @@? 17:31 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 17:31 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 17:31 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 19:5 Error TypeError: This expression is not callable. */ +/* @@? 19:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 19:23 Error SyntaxError: Unexpected token, expected '('. */ +/* @@? 19:31 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 19:31 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 19:31 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 31:5 Error TypeError: This expression is not callable. */ +/* @@? 31:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 31:23 Error SyntaxError: Unexpected token, expected '('. */ +/* @@? 31:31 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 31:31 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 31:31 Error SyntaxError: Unexpected token, expected ',' or ')'. */ diff --git a/ets2panda/test/ast/compiler/ets/invalid_two_functions.ets b/ets2panda/test/ast/compiler/ets/invalid_two_functions.ets index 62d52f75f5..f4850751e5 100644 --- a/ets2panda/test/ast/compiler/ets/invalid_two_functions.ets +++ b/ets2panda/test/ast/compiler/ets/invalid_two_functions.ets @@ -20,5 +20,6 @@ const b = a.map(function (e) { return e * 2; }); -/* @@? 16:2 Error SyntaxError: Unexpected token 'function'. */ -/* @@? 19:17 Error SyntaxError: Unexpected token 'function'. */ +/* @@? 16:2 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 19:17 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 19:28 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ 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 index 0d648f4ea7..e085a3efaf 100644 --- a/ets2panda/test/ast/parser/ets/empty_array_map_inference_fail.ets +++ b/ets2panda/test/ast/parser/ets/empty_array_map_inference_fail.ets @@ -21,6 +21,7 @@ return x+1; }); -/* @@? 16:2 Error SyntaxError: Unexpected token 'function'. */ +/* @@? 16:2 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ /* @@? 20:1 Error TypeError: Can't resolve array type */ -/* @@? 20:8 Error SyntaxError: Unexpected token 'function'. */ +/* @@? 20:8 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 20:18 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ diff --git a/ets2panda/util/diagnostic/syntax.yaml b/ets2panda/util/diagnostic/syntax.yaml index a412c35ab5..015b0a355c 100644 --- a/ets2panda/util/diagnostic/syntax.yaml +++ b/ets2panda/util/diagnostic/syntax.yaml @@ -1230,4 +1230,8 @@ syntax: - name: DEEP_NESTING id: 305 - message: "Maximum allowed nesting level exceeded." \ No newline at end of file + message: "Maximum allowed nesting level exceeded." + +- name: FUNC_EXPR + id: 306 + message: "Function expressions are not supported, use arrow functions instead" \ No newline at end of file diff --git a/ets2panda/varbinder/ETSBinder.cpp b/ets2panda/varbinder/ETSBinder.cpp index d9253e6b53..35b894e041 100644 --- a/ets2panda/varbinder/ETSBinder.cpp +++ b/ets2panda/varbinder/ETSBinder.cpp @@ -878,7 +878,7 @@ static ir::AstNode *GetSpecifier(const util::StringView &importedLocal, ir::ETSI return decl->Specifiers()[0]; } ES2PANDA_UNREACHABLE(); -}; +} std::pair ETSBinder::FindImportDeclInReExports( const ir::ETSImportDeclaration *const import, const util::StringView &imported, -- Gitee From 4c05c26d330ac5f907d351a618ab912171eca131 Mon Sep 17 00:00:00 2001 From: tengtengh Date: Thu, 3 Jul 2025 22:17:15 +0800 Subject: [PATCH 091/145] Fix interface generic method as value Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKA29 Signed-off-by: tengtengh --- .../compiler/lowering/ets/lambdaLowering.cpp | 20 +++++++++--- .../ets/interface_method_as_value_1.ets | 26 ++++++++++++++++ .../ets/interface_method_as_value_3.ets | 31 +++++++++++++++++++ 3 files changed, 72 insertions(+), 5 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/interface_method_as_value_1.ets create mode 100644 ets2panda/test/runtime/ets/interface_method_as_value_3.ets diff --git a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp index c0f74de4d1..ef4a95baf7 100644 --- a/ets2panda/compiler/lowering/ets/lambdaLowering.cpp +++ b/ets2panda/compiler/lowering/ets/lambdaLowering.cpp @@ -32,6 +32,7 @@ struct LambdaInfo { ArenaSet *capturedVars = nullptr; ir::Expression *callReceiver = nullptr; bool isFunctionReference = false; + checker::ETSObjectType *objType = nullptr; }; struct CalleeMethodInfo { @@ -430,8 +431,10 @@ static void CreateLambdaClassFields(public_lib::Context *ctx, ir::ClassDefinitio auto *checker = ctx->checker->AsETSChecker(); auto props = ArenaVector(allocator->Adapter()); - checker::Type *objectType = - info->calleeClass != nullptr ? info->calleeClass->Definition()->TsType() : info->calleeInterface->TsType(); + checker::Type *objectType = info->objType != nullptr + ? info->objType + : (info->calleeClass != nullptr ? info->calleeClass->Definition()->TsType() + : info->calleeInterface->TsType()); if (info->callReceiver != nullptr) { auto *outerThisDeclaration = parser->CreateFormattedClassFieldDefinition( @@ -465,8 +468,10 @@ static void CreateLambdaClassConstructor(public_lib::Context *ctx, ir::ClassDefi params.push_back(param); }; - checker::Type *objectType = - info->calleeClass != nullptr ? info->calleeClass->Definition()->TsType() : info->calleeInterface->TsType(); + checker::Type *objectType = info->objType != nullptr + ? info->objType + : (info->calleeClass != nullptr ? info->calleeClass->Definition()->TsType() + : info->calleeInterface->TsType()); if (info->callReceiver != nullptr) { makeParam("$this", objectType); @@ -1083,6 +1088,9 @@ static LambdaInfo GenerateLambdaInfoForFunctionReference(public_lib::Context *ct ES2PANDA_ASSERT(funcRef->IsMemberExpression()); info.callReceiver = funcRef->AsMemberExpression()->Object(); } + if (funcRef->IsMemberExpression()) { + info.objType = funcRef->AsMemberExpression()->ObjType(); + } return info; } @@ -1128,7 +1136,9 @@ static ir::AstNode *ConvertFunctionReference(public_lib::Context *ctx, ir::Expre auto *lambdaClass = CreateLambdaClass(ctx, funcRef->TsType()->AsETSFunctionType(), method, &info); auto *constructorCall = CreateConstructorCall(ctx, funcRef, lambdaClass, &info); ES2PANDA_ASSERT(constructorCall); - constructorCall->TsType()->AsETSObjectType()->AddObjectFlag(checker::ETSObjectFlags::FUNCTIONAL_REFERENCE); + if (constructorCall->TsType()->IsETSObjectType()) { + constructorCall->TsType()->AsETSObjectType()->AddObjectFlag(checker::ETSObjectFlags::FUNCTIONAL_REFERENCE); + } return constructorCall; } diff --git a/ets2panda/test/ast/compiler/ets/interface_method_as_value_1.ets b/ets2panda/test/ast/compiler/ets/interface_method_as_value_1.ets new file mode 100644 index 0000000000..3e1f2336bc --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/interface_method_as_value_1.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. + */ + +declare function g(a: string): void; +let gg: (a: string)=>void = g; + +interface Obj { + method(value: T): void; +} + +declare const o1: Obj; + +gg = o1.method; + diff --git a/ets2panda/test/runtime/ets/interface_method_as_value_3.ets b/ets2panda/test/runtime/ets/interface_method_as_value_3.ets new file mode 100644 index 0000000000..65fed84965 --- /dev/null +++ b/ets2panda/test/runtime/ets/interface_method_as_value_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. + */ + + +let gg: (a: string)=>void; + +class Obj { + method2 = (value:T):void => {} + method(value: T): void {}; +} + +class Obj2 { + method(): void {} +} + +function foo(o: Obj, o2: Obj2) { + gg = o2.method; + gg = o.method; +} -- Gitee From 889530d91546a164a6bbc16105cc89e994e3608b Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Sat, 5 Jul 2025 16:08:30 +0800 Subject: [PATCH 092/145] Fix crash when create ETSObjectType Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICK7C3?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ets/object.cpp | 5 +++- .../test/ast/compiler/ets/invalid_object.ets | 28 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/invalid_object.ets diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index e2d4232f15..97eb2f20a1 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -437,8 +437,11 @@ Type *ETSChecker::BuildBasicInterfaceProperties(ir::TSInterfaceDeclaration *inte interfaceType = CreateETSObjectTypeOrBuiltin(interfaceDecl, checker::ETSObjectFlags::INTERFACE); interfaceType->SetVariable(var); var->SetTsType(interfaceType); - } else { + } else if (var->TsType()->IsETSObjectType()) { interfaceType = var->TsType()->AsETSObjectType(); + } else { + ES2PANDA_ASSERT(IsAnyError()); + return GlobalTypeError(); } // Save before we mess with savedContext. diff --git a/ets2panda/test/ast/compiler/ets/invalid_object.ets b/ets2panda/test/ast/compiler/ets/invalid_object.ets new file mode 100644 index 0000000000..6d2e5fb2a1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/invalid_object.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. + */ + +interface Obj {} +const object1: Obj = {}; + +console.log(Objˆct.keys(object1)); + +/* @@? 19:13 Error TypeError: Class name can't be the argument of function or method. */ +/* @@? 19:13 Error TypeError: Class or interface 'Obj' cannot be used as object */ +/* @@? 19:16 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 19:16 Error SyntaxError: Unexpected token 'ˆct'. */ +/* @@? 19:16 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 19:16 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 19:16 Error TypeError: Unresolved reference ˆct */ +/* @@? 19:33 Error SyntaxError: Unexpected token ')'. */ \ No newline at end of file -- Gitee From 7e640e4c84e8a55f21f52f9cedaafb867e695a2b Mon Sep 17 00:00:00 2001 From: huyunhui Date: Mon, 7 Jul 2025 14:52:43 +0800 Subject: [PATCH 093/145] Fix bug of annotation Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKIB8 Signed-off-by: huyunhui --- ets2panda/checker/ets/typeCheckingHelpers.cpp | 2 +- .../annotation_usage_wrong_ref.ets | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/parser/ets/annotations_tests/annotation_usage_wrong_ref.ets diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 322967f18e..198dd2702c 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -1108,7 +1108,7 @@ void ETSChecker::HandleAnnotationRetention(ir::AnnotationUsage *anno, ir::Annota void ETSChecker::CheckStandardAnnotation(ir::AnnotationUsage *anno) { - if (anno->GetBaseName()->Variable() == nullptr) { + if (anno->GetBaseName()->Variable() == nullptr || IsTypeError(anno->GetBaseName()->TsType())) { return; } ES2PANDA_ASSERT(anno->GetBaseName()->Variable()->Declaration()->Node()->AsAnnotationDeclaration() != nullptr); diff --git a/ets2panda/test/ast/parser/ets/annotations_tests/annotation_usage_wrong_ref.ets b/ets2panda/test/ast/parser/ets/annotations_tests/annotation_usage_wrong_ref.ets new file mode 100644 index 0000000000..6aa297c618 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/annotations_tests/annotation_usage_wrong_ref.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. + */ + +function foo() {} + +@/* @@ label */foo +@interface anno {} + +/* @@@ label Error TypeError: Cannot find type 'foo'. */ \ No newline at end of file -- Gitee From f10b792d1f8e8765f200032ed0b4958d63d7188c Mon Sep 17 00:00:00 2001 From: Boglarka Haag Date: Mon, 30 Jun 2025 13:34:50 +0200 Subject: [PATCH 094/145] Fix crash on callbacks Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICIXCV Reason: Fixed crash when generic callback function was called with less params then expected Description: Modified EnchanceSignatureSubstitution Fixes internal issue: #26930 Signed-off-by: Haag Boglarka --- .../checker/types/ets/etsFunctionType.cpp | 2 +- .../ast/compiler/ets/generic_callback.ets | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/generic_callback.ets diff --git a/ets2panda/checker/types/ets/etsFunctionType.cpp b/ets2panda/checker/types/ets/etsFunctionType.cpp index 7c757922b8..23a5f92808 100644 --- a/ets2panda/checker/types/ets/etsFunctionType.cpp +++ b/ets2panda/checker/types/ets/etsFunctionType.cpp @@ -168,7 +168,7 @@ static Signature *EnhanceSignatureSubstitution(TypeRelation *relation, Signature auto const enhance = [checker, sub, substitution](Type *param, Type *arg) { return checker->EnhanceSubstitutionForType(sub->GetSignatureInfo()->typeParams, param, arg, substitution); }; - for (size_t ix = 0; ix < super->MinArgCount(); ix++) { + for (size_t ix = 0; ix < sub->ArgCount(); ix++) { if (!enhance(sub->GetSignatureInfo()->params[ix]->TsType(), super->GetSignatureInfo()->params[ix]->TsType())) { return nullptr; } diff --git a/ets2panda/test/ast/compiler/ets/generic_callback.ets b/ets2panda/test/ast/compiler/ets/generic_callback.ets new file mode 100644 index 0000000000..92c4b7ad7e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/generic_callback.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 identity(a: A): A { + return a; +} +let x = [1, 2, 3].map(identity)[0]; + +/* @@? 19:9 Error TypeError: No matching call signature for map((a: A) => A) */ +/* @@? 19:9 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 19:9 Error TypeError: No matching call signature for map((a: A) => A) */ +/* @@? 19:9 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 19:23 Error TypeError: Type '(a: A) => A' is not compatible with type '(value: Int, index: Double, array: Array) => A' at index 1 */ +/* @@? 19:23 Error TypeError: Type '(a: A) => A' is not compatible with type '(value: Int, index: Double, array: ReadonlyArray) => A' at index 1 */ +/* @@? 19:23 Error TypeError: Type '(a: A) => A' is not compatible with type '(value: Int, index: Double, array: Array) => A' at index 1 */ +/* @@? 19:23 Error TypeError: Type '(a: A) => A' is not compatible with type '(value: Int, index: Double, array: ReadonlyArray) => A' at index 1 */ -- Gitee From 1096476497b885f8e848a81c64b8fbe92d26adc5 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Thu, 3 Jul 2025 20:54:07 +0800 Subject: [PATCH 095/145] fix smart cast bug Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJU9E?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ETSAnalyzer.cpp | 2 +- .../ets/defaultParametersLowering.cpp | 3 + .../test/ast/compiler/ets/smart_cast.ets | 28 +++ .../ets/default_parameter5-expected.txt | 72 +++--- .../ets/default_parameter7-expected.txt | 72 +++--- .../ets/default_parameter8-expected.txt | 216 +++++++++--------- ..._implicitly_typed_return_void-expected.txt | 144 ++++++------ .../ets/proxyVoidGeneration-expected.txt | 96 ++++---- .../parser/ets/rest_parameter_02-expected.txt | 72 +++--- 9 files changed, 368 insertions(+), 337 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/smart_cast.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 3003844b28..c6c0633648 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -1634,7 +1634,7 @@ checker::Type *ETSAnalyzer::Check(ir::ConditionalExpression *expr) const checker->Context().CombineSmartCasts(consequentSmartCasts); if (checker->IsTypeIdenticalTo(consequentType, alternateType)) { - expr->SetTsType(checker->GetNonConstantType(consequentType)); + expr->SetTsType(consequentType); } else { // If possible and required update number literal type to the proper value (identical to left-side type) if (alternate->IsNumberLiteral() && diff --git a/ets2panda/compiler/lowering/ets/defaultParametersLowering.cpp b/ets2panda/compiler/lowering/ets/defaultParametersLowering.cpp index d87fc777fd..d11ee47066 100644 --- a/ets2panda/compiler/lowering/ets/defaultParametersLowering.cpp +++ b/ets2panda/compiler/lowering/ets/defaultParametersLowering.cpp @@ -75,6 +75,9 @@ static void TransformFunction(public_lib::Context *ctx, ir::ScriptFunction *func auto const param = defaultParams.at(dfltIdx); auto stmt = TransformInitializer(allocator, parser, param); body->Statements()[dfltIdx] = stmt; + // From a developer's perspective, this locational information is more intuitive. + stmt->SetParent(param); + RefineSourceRanges(stmt); stmt->SetParent(body); } } diff --git a/ets2panda/test/ast/compiler/ets/smart_cast.ets b/ets2panda/test/ast/compiler/ets/smart_cast.ets new file mode 100644 index 0000000000..226a7a068e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/smart_cast.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(p: "Object" | "String" | "Number" = "Object") { // should be ok +} + +function bar(p: "Object") { + let s: "Object" = p != undefined ? p : "Object"// should be ok +} + +function baz(p: "Double") { + let s: "Object" = p != undefined ? p : "Double"// should be cte +} + +/* @@? 24:23 Error TypeError: Type '"Double"' cannot be assigned to type '"Object"' */ + diff --git a/ets2panda/test/parser/ets/default_parameter5-expected.txt b/ets2panda/test/parser/ets/default_parameter5-expected.txt index 3fa19f2329..413e391c60 100644 --- a/ets2panda/test/parser/ets/default_parameter5-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter5-expected.txt @@ -591,14 +591,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 35, + "program": "default_parameter5.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 55, + "program": "default_parameter5.ets" } } }, @@ -607,26 +607,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 35, "program": "default_parameter5.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 55, "program": "default_parameter5.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 35, "program": "default_parameter5.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 55, "program": "default_parameter5.ets" } } @@ -637,14 +637,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 35, + "program": "default_parameter5.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 55, + "program": "default_parameter5.ets" } } }, @@ -734,39 +734,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 35, "program": "default_parameter5.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 55, "program": "default_parameter5.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 35, "program": "default_parameter5.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 55, "program": "default_parameter5.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 35, "program": "default_parameter5.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 55, "program": "default_parameter5.ets" } } @@ -775,13 +775,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 21, + "column": 35, "program": "default_parameter5.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 55, "program": "default_parameter5.ets" } } diff --git a/ets2panda/test/parser/ets/default_parameter7-expected.txt b/ets2panda/test/parser/ets/default_parameter7-expected.txt index 1e2089524a..81392ca079 100644 --- a/ets2panda/test/parser/ets/default_parameter7-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter7-expected.txt @@ -983,14 +983,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 36, + "program": "default_parameter7.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 48, + "program": "default_parameter7.ets" } } }, @@ -999,26 +999,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 36, "program": "default_parameter7.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 48, "program": "default_parameter7.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 36, "program": "default_parameter7.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 48, "program": "default_parameter7.ets" } } @@ -1029,14 +1029,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 36, + "program": "default_parameter7.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 48, + "program": "default_parameter7.ets" } } }, @@ -1107,39 +1107,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 36, "program": "default_parameter7.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 48, "program": "default_parameter7.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 36, "program": "default_parameter7.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 48, "program": "default_parameter7.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 36, "program": "default_parameter7.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 48, "program": "default_parameter7.ets" } } @@ -1148,13 +1148,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 21, + "column": 36, "program": "default_parameter7.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 48, "program": "default_parameter7.ets" } } diff --git a/ets2panda/test/parser/ets/default_parameter8-expected.txt b/ets2panda/test/parser/ets/default_parameter8-expected.txt index 4e675b381d..46c9e1e7bd 100644 --- a/ets2panda/test/parser/ets/default_parameter8-expected.txt +++ b/ets2panda/test/parser/ets/default_parameter8-expected.txt @@ -651,14 +651,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 17, + "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 32, + "program": "default_parameter8.ets" } } }, @@ -667,26 +667,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 17, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 32, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 17, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 32, "program": "default_parameter8.ets" } } @@ -697,14 +697,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 17, + "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 21, + "column": 32, + "program": "default_parameter8.ets" } } }, @@ -743,39 +743,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 17, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 32, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 17, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 32, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 21, + "column": 17, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 32, "program": "default_parameter8.ets" } } @@ -784,13 +784,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 21, + "column": 17, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 21, + "column": 32, "program": "default_parameter8.ets" } } @@ -1555,14 +1555,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 30, + "column": 18, + "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 30, + "column": 35, + "program": "default_parameter8.ets" } } }, @@ -1571,26 +1571,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 30, + "column": 18, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 30, + "column": 35, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 30, + "column": 18, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 30, + "column": 35, "program": "default_parameter8.ets" } } @@ -1601,14 +1601,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 30, + "column": 18, + "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 30, + "column": 35, + "program": "default_parameter8.ets" } } }, @@ -1680,39 +1680,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 30, + "column": 18, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 30, + "column": 35, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 30, + "column": 18, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 30, + "column": 35, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 30, + "column": 18, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 30, + "column": 35, "program": "default_parameter8.ets" } } @@ -1721,13 +1721,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 30, + "column": 18, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 30, + "column": 35, "program": "default_parameter8.ets" } } @@ -2385,14 +2385,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 36, + "column": 16, + "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 36, + "column": 31, + "program": "default_parameter8.ets" } } }, @@ -2401,26 +2401,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 36, + "column": 16, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 36, + "column": 31, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 36, + "column": 16, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 36, + "column": 31, "program": "default_parameter8.ets" } } @@ -2431,14 +2431,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 36, + "column": 16, + "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 36, + "column": 31, + "program": "default_parameter8.ets" } } }, @@ -2512,39 +2512,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 36, + "column": 16, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 36, + "column": 31, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 36, + "column": 16, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 36, + "column": 31, "program": "default_parameter8.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 36, + "column": 16, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 36, + "column": 31, "program": "default_parameter8.ets" } } @@ -2553,13 +2553,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 36, + "column": 16, "program": "default_parameter8.ets" }, "end": { - "line": 1, - "column": 3, + "line": 36, + "column": 31, "program": "default_parameter8.ets" } } 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 b8edf0fab3..979f618866 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 @@ -500,14 +500,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 16, + "column": 25, + "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 16, + "column": 47, + "program": "default_parameter_implicitly_typed_return_void.ets" } } }, @@ -516,26 +516,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 25, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 47, "program": "default_parameter_implicitly_typed_return_void.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 25, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 47, "program": "default_parameter_implicitly_typed_return_void.ets" } } @@ -546,14 +546,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 16, + "column": 25, + "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 16, + "column": 47, + "program": "default_parameter_implicitly_typed_return_void.ets" } } }, @@ -624,39 +624,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 25, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 47, "program": "default_parameter_implicitly_typed_return_void.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 25, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 47, "program": "default_parameter_implicitly_typed_return_void.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 25, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 47, "program": "default_parameter_implicitly_typed_return_void.ets" } } @@ -665,13 +665,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 16, + "column": 25, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 47, "program": "default_parameter_implicitly_typed_return_void.ets" } } @@ -756,14 +756,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 16, + "column": 49, + "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 16, + "column": 70, + "program": "default_parameter_implicitly_typed_return_void.ets" } } }, @@ -772,26 +772,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 49, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 70, "program": "default_parameter_implicitly_typed_return_void.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 49, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 70, "program": "default_parameter_implicitly_typed_return_void.ets" } } @@ -802,14 +802,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 16, + "column": 49, + "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 16, + "column": 70, + "program": "default_parameter_implicitly_typed_return_void.ets" } } }, @@ -880,39 +880,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 49, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 70, "program": "default_parameter_implicitly_typed_return_void.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 49, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 70, "program": "default_parameter_implicitly_typed_return_void.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 16, + "column": 49, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 70, "program": "default_parameter_implicitly_typed_return_void.ets" } } @@ -921,13 +921,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 16, + "column": 49, "program": "default_parameter_implicitly_typed_return_void.ets" }, "end": { - "line": 1, - "column": 3, + "line": 16, + "column": 70, "program": "default_parameter_implicitly_typed_return_void.ets" } } diff --git a/ets2panda/test/parser/ets/proxyVoidGeneration-expected.txt b/ets2panda/test/parser/ets/proxyVoidGeneration-expected.txt index f6c9b7b863..bb2573f571 100644 --- a/ets2panda/test/parser/ets/proxyVoidGeneration-expected.txt +++ b/ets2panda/test/parser/ets/proxyVoidGeneration-expected.txt @@ -265,14 +265,14 @@ "type": "ETSNullType", "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 17, + "column": 16, + "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 17, + "column": 28, + "program": "proxyVoidGeneration.ets" } } } @@ -315,14 +315,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 17, + "column": 10, + "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 17, + "column": 35, + "program": "proxyVoidGeneration.ets" } } }, @@ -331,26 +331,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 17, + "column": 10, "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 3, + "line": 17, + "column": 35, "program": "proxyVoidGeneration.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 17, + "column": 10, "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 3, + "line": 17, + "column": 35, "program": "proxyVoidGeneration.ets" } } @@ -361,14 +361,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 17, + "column": 10, + "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 17, + "column": 35, + "program": "proxyVoidGeneration.ets" } } }, @@ -444,14 +444,14 @@ "type": "ETSNullType", "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 17, + "column": 16, + "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 17, + "column": 28, + "program": "proxyVoidGeneration.ets" } } } @@ -471,39 +471,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 17, + "column": 10, "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 3, + "line": 17, + "column": 35, "program": "proxyVoidGeneration.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 17, + "column": 10, "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 3, + "line": 17, + "column": 35, "program": "proxyVoidGeneration.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 17, + "column": 10, "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 3, + "line": 17, + "column": 35, "program": "proxyVoidGeneration.ets" } } @@ -512,13 +512,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 17, + "column": 10, "program": "proxyVoidGeneration.ets" }, "end": { - "line": 1, - "column": 3, + "line": 17, + "column": 35, "program": "proxyVoidGeneration.ets" } } diff --git a/ets2panda/test/parser/ets/rest_parameter_02-expected.txt b/ets2panda/test/parser/ets/rest_parameter_02-expected.txt index ee060d72bb..1da8e5673f 100644 --- a/ets2panda/test/parser/ets/rest_parameter_02-expected.txt +++ b/ets2panda/test/parser/ets/rest_parameter_02-expected.txt @@ -806,14 +806,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 20, + "column": 31, + "program": "rest_parameter_02.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 20, + "column": 41, + "program": "rest_parameter_02.ets" } } }, @@ -822,26 +822,26 @@ "value": "undefined", "loc": { "start": { - "line": 1, - "column": 3, + "line": 20, + "column": 31, "program": "rest_parameter_02.ets" }, "end": { - "line": 1, - "column": 3, + "line": 20, + "column": 41, "program": "rest_parameter_02.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 20, + "column": 31, "program": "rest_parameter_02.ets" }, "end": { - "line": 1, - "column": 3, + "line": 20, + "column": 41, "program": "rest_parameter_02.ets" } } @@ -852,14 +852,14 @@ "decorators": [], "loc": { "start": { - "line": 1, - "column": 1, - "program": null + "line": 20, + "column": 31, + "program": "rest_parameter_02.ets" }, "end": { - "line": 1, - "column": 1, - "program": null + "line": 20, + "column": 41, + "program": "rest_parameter_02.ets" } } }, @@ -898,39 +898,39 @@ }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 20, + "column": 31, "program": "rest_parameter_02.ets" }, "end": { - "line": 1, - "column": 3, + "line": 20, + "column": 41, "program": "rest_parameter_02.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 20, + "column": 31, "program": "rest_parameter_02.ets" }, "end": { - "line": 1, - "column": 3, + "line": 20, + "column": 41, "program": "rest_parameter_02.ets" } } }, "loc": { "start": { - "line": 1, - "column": 3, + "line": 20, + "column": 31, "program": "rest_parameter_02.ets" }, "end": { - "line": 1, - "column": 3, + "line": 20, + "column": 41, "program": "rest_parameter_02.ets" } } @@ -939,13 +939,13 @@ "kind": "let", "loc": { "start": { - "line": 1, - "column": 1, + "line": 20, + "column": 31, "program": "rest_parameter_02.ets" }, "end": { - "line": 1, - "column": 3, + "line": 20, + "column": 41, "program": "rest_parameter_02.ets" } } -- Gitee From 1474eaf16a4e549809f55957e47eaf9049179633 Mon Sep 17 00:00:00 2001 From: lijunru Date: Thu, 26 Jun 2025 19:15:16 +0800 Subject: [PATCH 096/145] Fix the timeout issue of the use case Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICHVLY Signed-off-by: lijunru --- ets2panda/test/unit/lsp/CMakeLists.txt | 19 +- ets2panda/test/unit/lsp/get_completions.cpp | 333 --------------- ets2panda/test/unit/lsp/get_completions_1.cpp | 392 ++++++++++++++++++ ets2panda/test/unit/lsp/navigate_to_test.cpp | 242 ----------- .../test/unit/lsp/navigate_to_test_1.cpp | 251 +++++++++++ ets2panda/test/unit/lsp/quick_info_test.cpp | 335 +-------------- ets2panda/test/unit/lsp/quick_info_test_1.cpp | 357 ++++++++++++++++ .../unit/lsp/suggestion_diagnostics_test.cpp | 149 +------ .../lsp/suggestion_diagnostics_test_1.cpp | 171 ++++++++ 9 files changed, 1193 insertions(+), 1056 deletions(-) create mode 100644 ets2panda/test/unit/lsp/get_completions_1.cpp create mode 100644 ets2panda/test/unit/lsp/navigate_to_test_1.cpp create mode 100644 ets2panda/test/unit/lsp/quick_info_test_1.cpp create mode 100644 ets2panda/test/unit/lsp/suggestion_diagnostics_test_1.cpp diff --git a/ets2panda/test/unit/lsp/CMakeLists.txt b/ets2panda/test/unit/lsp/CMakeLists.txt index 7c300f8dc0..0ddf32b095 100644 --- a/ets2panda/test/unit/lsp/CMakeLists.txt +++ b/ets2panda/test/unit/lsp/CMakeLists.txt @@ -87,6 +87,10 @@ ets2panda_add_gtest(lsp_quick_info_api_test CPP_SOURCES quick_info_test.cpp ) +ets2panda_add_gtest(lsp_quick_info_api_test_1 CPP_SOURCES + quick_info_test_1.cpp +) + ets2panda_add_gtest(lsp_api_completions_entry_details_test CPP_SOURCES get_completions_entry_details.cpp ) @@ -148,6 +152,10 @@ ets2panda_add_gtest(lsp_api_test_suggestion_diagnostics CPP_SOURCES suggestion_diagnostics_test.cpp ) +ets2panda_add_gtest(lsp_api_test_suggestion_diagnostics_1 CPP_SOURCES + suggestion_diagnostics_test_1.cpp +) + ets2panda_add_gtest(lsp_api_test_get_class_property_info CPP_SOURCES get_class_property_info_test.cpp ) @@ -164,6 +172,10 @@ ets2panda_add_gtest(lsp_api_ui_suggest_test CPP_SOURCES code_fix/ui_plugin_suggest.cpp ) +ets2panda_add_gtest(lsp_api_completions_test_1 CPP_SOURCES + get_completions_1.cpp +) + ets2panda_add_gtest(lsp_api_test_get_class_hierarchy_info CPP_SOURCES class_hierarchy_info_test.cpp ) @@ -231,10 +243,15 @@ ets2panda_add_gtest(lsp_api_test_todo_comments CPP_SOURCES ets2panda_add_gtest(lsp_api_test_navigate_to CPP_SOURCES navigate_to_test.cpp ) + +ets2panda_add_gtest(lsp_api_test_navigate_to_1 CPP_SOURCES + navigate_to_test_1.cpp +) + ets2panda_add_gtest(lsp_api_test_code_fix_registration CPP_SOURCES code_fix_registration_test.cpp ) ets2panda_add_gtest(lsp_api_test_get_name_or_dotted_name_span CPP_SOURCES get_name_or_dotted_name_span_test.cpp -) \ No newline at end of file +) diff --git a/ets2panda/test/unit/lsp/get_completions.cpp b/ets2panda/test/unit/lsp/get_completions.cpp index 7b5d5a22ef..a25265efd8 100644 --- a/ets2panda/test/unit/lsp/get_completions.cpp +++ b/ets2panda/test/unit/lsp/get_completions.cpp @@ -409,337 +409,4 @@ let myColor: Color = Color._WILDCARD)delimiter"}; initializer.DestroyContext(ctx); } -TEST_F(LSPCompletionsTests, MemberCompletionsForClassTest9) -{ - std::vector files = {"getCompletionsAtPosition12.ets"}; - std::vector texts = {R"delimiter( -namespace space { - export class classInSpace { - public c: number = 2; - } -} -let numOfSpace: space._WILDCARD)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - const size_t offset = 113; - auto res = lspApi->getCompletionsAtPosition(ctx, offset); - auto entries = res.GetEntries(); - std::string propertyName1 = "classInSpace"; - ASSERT_TRUE(entries.size() == 1); - CompletionEntry entry1 = - CompletionEntry(propertyName1, CompletionEntryKind::CLASS, - std::string(ark::es2panda::lsp::sort_text::MEMBER_DECLARED_BY_SPREAD_ASSIGNMENT)); - initializer.DestroyContext(ctx); - ASSERT_EQ(entry1, entries[0]); -} - -TEST_F(LSPCompletionsTests, getCompletionsAtPosition6) -{ - std::vector files = {"getCompletionsAtPosition9.ets"}; - std::vector texts = {R"delimiter( -let a: num -)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - - LSPAPI const *lspApi = GetImpl(); - size_t const offset = 11; // after 'n' in 'let a = n' - 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("number", ark::es2panda::lsp::CompletionEntryKind::KEYWORD, std::string(GLOBALS_OR_KEYWORDS))}; - AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); - initializer.DestroyContext(ctx); -} - -TEST_F(LSPCompletionsTests, getCompletionsAtPosition5) -{ - std::vector files = {"getCompletionsAtPosition8.ets"}; - std::vector texts = {R"delimiter( -class -)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - - LSPAPI const *lspApi = GetImpl(); - 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); - auto expectedEntries = std::vector {}; - AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); - initializer.DestroyContext(ctx); -} - -TEST_F(LSPCompletionsTests, getCompletionsAtPosition0) -{ - std::vector files = {"getCompletionsAtPosition7.ets"}; - std::vector texts = {R"delimiter( -function num1() { - return 1; -} - -function num2() { - return 2; -} - -console.log(1); - -let a = n -)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - - LSPAPI const *lspApi = GetImpl(); - size_t const offset = 97; // after 'n' in 'let a = n' - 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("num1", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("num2", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), - }; - AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); - initializer.DestroyContext(ctx); -} - -TEST_F(LSPCompletionsTests, getCompletionsAtPosition1) -{ - std::vector files = {"getCompletionsAtPosition1.ets"}; - std::vector texts = {R"delimiter( -function num1() { - return 1; -} - -function num2() { - return 2; -} - -let a = n -)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - size_t const offset = 80; // after 'n' in 'let a = n' - auto res = lspApi->getCompletionsAtPosition(ctx, offset); - auto expectedEntries = std::vector { - CompletionEntry("num1", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("num2", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), - }; - initializer.DestroyContext(ctx); - AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); -} - -TEST_F(LSPCompletionsTests, getCompletionsAtPosition2) -{ - std::vector files = {"getCompletionsAtPosition2.ets"}; - std::vector texts = {R"delimiter( -let aaa = 123; -const abb = 333; - -function axx() { - return 444; -} - -function foo() { - let bbb = 222; - let ccc = bbb + a - return bbb + ccc; -} -)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - size_t const offset = 127; // after 'a' in 'let ccc = bbb + a' - auto res = lspApi->getCompletionsAtPosition(ctx, offset); - auto expectedEntries = std::vector { - CompletionEntry("aaa", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("abb", ark::es2panda::lsp::CompletionEntryKind::CONSTANT, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("axx", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), - }; - initializer.DestroyContext(ctx); - AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); -} - -TEST_F(LSPCompletionsTests, getCompletionsAtPosition3) -{ - std::vector files = {"getCompletionsAtPosition3.ets"}; - std::vector texts = {R"delimiter( -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 -} -)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - size_t const offset = 181; // after 'b' in 'let axx = b' - auto res = lspApi->getCompletionsAtPosition(ctx, offset); - auto expectedEntries = std::vector { - CompletionEntry("baa", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("bbb", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("bcc", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("bxx", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), - }; - auto unexpectedEntries = std::vector { - CompletionEntry("bar", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), - }; - initializer.DestroyContext(ctx); - AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, unexpectedEntries); -} - -TEST_F(LSPCompletionsTests, getCompletionsAtPosition4) -{ - std::vector files = {"getCompletionsAtPosition4.ets"}; - std::vector texts = {R"delimiter( -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 -)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - size_t const offset = 159; // after 'b' in 'let axx = b' - auto res = lspApi->getCompletionsAtPosition(ctx, offset); - auto expectedEntries = std::vector { - CompletionEntry("baa", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("bbb", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("bxx", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), - }; - auto unexpectedEntries = std::vector { - CompletionEntry("bar", ark::es2panda::lsp::CompletionEntryKind::PROPERTY, std::string(GLOBALS_OR_KEYWORDS)), - CompletionEntry("bcc", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), - }; - initializer.DestroyContext(ctx); - AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, unexpectedEntries); -} - -TEST_F(LSPCompletionsTests, MemberCompletionsForClassTest1) -{ - std::vector files = {"getCompletionsAtPosition5.ets"}; - std::vector texts = {R"delimiter( -class MyClass1 { - public myProp: number = 0; - public prop: number = 1; -} -let obj1 = new MyClass1() -let prop = obj1.yp)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - const size_t offset = 120; - auto res = lspApi->getCompletionsAtPosition(ctx, offset); - auto entries = res.GetEntries(); - ASSERT_TRUE(entries.size() == 1); - - std::string propertyName1 = "myProp"; - CompletionEntry entry1 = CompletionEntry(propertyName1, CompletionEntryKind::PROPERTY, - std::string(ark::es2panda::lsp::sort_text::SUGGESTED_CLASS_MEMBERS)); - initializer.DestroyContext(ctx); - ASSERT_EQ(entry1, entries[0]); -} - -TEST_F(LSPCompletionsTests, MemberCompletionsForClassTest2) -{ - std::vector files = {"getCompletionsAtPosition6.ets"}; - std::vector texts = {R"delimiter( -namespace space { - export class classInSpace { - public c: number = 2; - } -} -let numOfSpace: space.classi)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - const size_t offset = 110; - auto res = lspApi->getCompletionsAtPosition(ctx, offset); - auto entries = res.GetEntries(); - std::string propertyName1 = "classInSpace"; - ASSERT_TRUE(entries.size() == 1); - CompletionEntry entry1 = - CompletionEntry(propertyName1, CompletionEntryKind::CLASS, - std::string(ark::es2panda::lsp::sort_text::MEMBER_DECLARED_BY_SPREAD_ASSIGNMENT)); - initializer.DestroyContext(ctx); - ASSERT_EQ(entry1, entries[0]); -} - -TEST_F(LSPCompletionsTests, MemberCompletionsForClassTest4) -{ - std::vector files = {"getCompletionsAtPosition6.ets"}; - std::vector texts = {R"delimiter( -enum Color { - Red = "red", - Blue = "blue" -} -let myColor: Color = Color.R)delimiter"}; - auto filePaths = CreateTempFile(files, texts); - int const expectedFileCount = 1; - ASSERT_EQ(filePaths.size(), expectedFileCount); - Initializer initializer = Initializer(); - auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); - LSPAPI const *lspApi = GetImpl(); - const size_t offset = 75; - auto res = lspApi->getCompletionsAtPosition(ctx, offset); - auto entries = res.GetEntries(); - ASSERT_TRUE(entries.size() == 1); - - std::string propertyName1 = "Red"; - CompletionEntry entry1 = - CompletionEntry(propertyName1, CompletionEntryKind::ENUM_MEMBER, - std::string(ark::es2panda::lsp::sort_text::MEMBER_DECLARED_BY_SPREAD_ASSIGNMENT)); - initializer.DestroyContext(ctx); - ASSERT_EQ(entry1, entries[0]); -} - } // namespace diff --git a/ets2panda/test/unit/lsp/get_completions_1.cpp b/ets2panda/test/unit/lsp/get_completions_1.cpp new file mode 100644 index 0000000000..c61d9bba00 --- /dev/null +++ b/ets2panda/test/unit/lsp/get_completions_1.cpp @@ -0,0 +1,392 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "lsp_api_test.h" +#include "lsp/include/completions.h" +#include "lsp/include/internal_api.h" + +class LSPCompletionsTests : public LSPAPITests {}; + +using ark::es2panda::lsp::CompletionEntry; +using ark::es2panda::lsp::CompletionEntryKind; +using ark::es2panda::lsp::Initializer; +using ark::es2panda::lsp::sort_text::GLOBALS_OR_KEYWORDS; + +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(); + + for (const auto &expectedEntry : expectedEntries) { + bool found = false; + for (const auto &entry : entries) { + if (entry.GetName() == expectedEntry.GetName() && + entry.GetCompletionKind() == expectedEntry.GetCompletionKind()) { + found = true; + break; + } + } + ASSERT_TRUE(found) << "Expected completion '" << expectedEntry.GetName() << "' not found"; + } + + for (const auto &unexpectedEntry : unexpectedEntries) { + bool found = false; + for (const auto &entry : entries) { + if (entry.GetName() == unexpectedEntry.GetName() && + entry.GetCompletionKind() == unexpectedEntry.GetCompletionKind()) { + found = true; + break; + } + } + ASSERT_FALSE(found) << "Unexpected completion '" << unexpectedEntry.GetName() << "' found"; + } +} + +namespace { +TEST_F(LSPCompletionsTests, MemberCompletionsForClassTest9) +{ + std::vector files = {"getCompletionsAtPosition12.ets"}; + std::vector texts = {R"delimiter( +namespace space { + export class classInSpace { + public c: number = 2; + } +} +let numOfSpace: space._WILDCARD)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + const size_t offset = 113; + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto entries = res.GetEntries(); + std::string propertyName1 = "classInSpace"; + ASSERT_TRUE(entries.size() == 1); + CompletionEntry entry1 = + CompletionEntry(propertyName1, CompletionEntryKind::CLASS, + std::string(ark::es2panda::lsp::sort_text::MEMBER_DECLARED_BY_SPREAD_ASSIGNMENT)); + initializer.DestroyContext(ctx); + ASSERT_EQ(entry1, entries[0]); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition6) +{ + std::vector files = {"getCompletionsAtPosition9.ets"}; + std::vector texts = {R"delimiter( +let a: num +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 11; // after 'n' in 'let a = n' + 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("number", ark::es2panda::lsp::CompletionEntryKind::KEYWORD, std::string(GLOBALS_OR_KEYWORDS))}; + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition5) +{ + std::vector files = {"getCompletionsAtPosition8.ets"}; + std::vector texts = {R"delimiter( +class +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + LSPAPI const *lspApi = GetImpl(); + 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); + auto expectedEntries = std::vector {}; + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition0) +{ + std::vector files = {"getCompletionsAtPosition7.ets"}; + std::vector texts = {R"delimiter( +function num1() { + return 1; +} + +function num2() { + return 2; +} + +console.log(1); + +let a = n +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 97; // after 'n' in 'let a = n' + 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("num1", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("num2", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), + }; + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); + initializer.DestroyContext(ctx); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition1) +{ + std::vector files = {"getCompletionsAtPosition1.ets"}; + std::vector texts = {R"delimiter( +function num1() { + return 1; +} + +function num2() { + return 2; +} + +let a = n +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 80; // after 'n' in 'let a = n' + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto expectedEntries = std::vector { + CompletionEntry("num1", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("num2", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), + }; + initializer.DestroyContext(ctx); + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition2) +{ + std::vector files = {"getCompletionsAtPosition2.ets"}; + std::vector texts = {R"delimiter( +let aaa = 123; +const abb = 333; + +function axx() { + return 444; +} + +function foo() { + let bbb = 222; + let ccc = bbb + a + return bbb + ccc; +} +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 127; // after 'a' in 'let ccc = bbb + a' + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto expectedEntries = std::vector { + CompletionEntry("aaa", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("abb", ark::es2panda::lsp::CompletionEntryKind::CONSTANT, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("axx", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), + }; + initializer.DestroyContext(ctx); + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, {}); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition3) +{ + std::vector files = {"getCompletionsAtPosition3.ets"}; + std::vector texts = {R"delimiter( +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 +} +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 181; // after 'b' in 'let axx = b' + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto expectedEntries = std::vector { + CompletionEntry("baa", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("bbb", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("bcc", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("bxx", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), + }; + auto unexpectedEntries = std::vector { + CompletionEntry("bar", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), + }; + initializer.DestroyContext(ctx); + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, unexpectedEntries); +} + +TEST_F(LSPCompletionsTests, getCompletionsAtPosition4) +{ + std::vector files = {"getCompletionsAtPosition4.ets"}; + std::vector texts = {R"delimiter( +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 +)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + size_t const offset = 159; // after 'b' in 'let axx = b' + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto expectedEntries = std::vector { + CompletionEntry("baa", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("bbb", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("bxx", ark::es2panda::lsp::CompletionEntryKind::FUNCTION, std::string(GLOBALS_OR_KEYWORDS)), + }; + auto unexpectedEntries = std::vector { + CompletionEntry("bar", ark::es2panda::lsp::CompletionEntryKind::PROPERTY, std::string(GLOBALS_OR_KEYWORDS)), + CompletionEntry("bcc", ark::es2panda::lsp::CompletionEntryKind::VARIABLE, std::string(GLOBALS_OR_KEYWORDS)), + }; + initializer.DestroyContext(ctx); + AssertCompletionsContainAndNotContainEntries(res.GetEntries(), expectedEntries, unexpectedEntries); +} + +TEST_F(LSPCompletionsTests, MemberCompletionsForClassTest1) +{ + std::vector files = {"getCompletionsAtPosition5.ets"}; + std::vector texts = {R"delimiter( +class MyClass1 { + public myProp: number = 0; + public prop: number = 1; +} +let obj1 = new MyClass1() +let prop = obj1.yp)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + const size_t offset = 120; + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto entries = res.GetEntries(); + ASSERT_TRUE(entries.size() == 1); + + std::string propertyName1 = "myProp"; + CompletionEntry entry1 = CompletionEntry(propertyName1, CompletionEntryKind::PROPERTY, + std::string(ark::es2panda::lsp::sort_text::SUGGESTED_CLASS_MEMBERS)); + initializer.DestroyContext(ctx); + ASSERT_EQ(entry1, entries[0]); +} + +TEST_F(LSPCompletionsTests, MemberCompletionsForClassTest2) +{ + std::vector files = {"getCompletionsAtPosition6.ets"}; + std::vector texts = {R"delimiter( +namespace space { + export class classInSpace { + public c: number = 2; + } +} +let numOfSpace: space.classi)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + const size_t offset = 110; + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto entries = res.GetEntries(); + std::string propertyName1 = "classInSpace"; + ASSERT_TRUE(entries.size() == 1); + CompletionEntry entry1 = + CompletionEntry(propertyName1, CompletionEntryKind::CLASS, + std::string(ark::es2panda::lsp::sort_text::MEMBER_DECLARED_BY_SPREAD_ASSIGNMENT)); + initializer.DestroyContext(ctx); + ASSERT_EQ(entry1, entries[0]); +} + +TEST_F(LSPCompletionsTests, MemberCompletionsForClassTest4) +{ + std::vector files = {"getCompletionsAtPosition6.ets"}; + std::vector texts = {R"delimiter( +enum Color { + Red = "red", + Blue = "blue" +} +let myColor: Color = Color.R)delimiter"}; + auto filePaths = CreateTempFile(files, texts); + int const expectedFileCount = 1; + ASSERT_EQ(filePaths.size(), expectedFileCount); + Initializer initializer = Initializer(); + auto ctx = initializer.CreateContext(filePaths[0].c_str(), ES2PANDA_STATE_CHECKED); + LSPAPI const *lspApi = GetImpl(); + const size_t offset = 75; + auto res = lspApi->getCompletionsAtPosition(ctx, offset); + auto entries = res.GetEntries(); + ASSERT_TRUE(entries.size() == 1); + + std::string propertyName1 = "Red"; + CompletionEntry entry1 = + CompletionEntry(propertyName1, CompletionEntryKind::ENUM_MEMBER, + std::string(ark::es2panda::lsp::sort_text::MEMBER_DECLARED_BY_SPREAD_ASSIGNMENT)); + initializer.DestroyContext(ctx); + ASSERT_EQ(entry1, entries[0]); +} +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/navigate_to_test.cpp b/ets2panda/test/unit/lsp/navigate_to_test.cpp index 46a69f87a7..dc47ec46e8 100644 --- a/ets2panda/test/unit/lsp/navigate_to_test.cpp +++ b/ets2panda/test/unit/lsp/navigate_to_test.cpp @@ -27,27 +27,6 @@ using std::vector; class NavigateToTest : public LSPAPITests {}; -TEST_F(NavigateToTest, EmptySourceFiles) -{ - std::vector srcFiles; - Initializer initializer; - std::vector allResults; - const int maxResultCount = 10; - std::string searchTerm = "foo"; - - for (const auto &file : srcFiles) { - std::string sourceStr(file.source); - es2panda_Context *ctx = - initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); - ASSERT_NE(ctx, nullptr); - - std::vector singleFile = {{file.filePath, sourceStr}}; - auto results = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); - allResults.insert(allResults.end(), results.begin(), results.end()); - } - ASSERT_TRUE(allResults.empty()); -} - TEST_F(NavigateToTest, ExactMatchFromSingleFile) { std::vector files = {{"exatchMatch.sts", R"( @@ -254,225 +233,4 @@ TEST_F(NavigateToTest, NoMatchFound) ASSERT_TRUE(allResults.empty()); } -TEST_F(NavigateToTest, MatchLimitRespected) -{ - std::vector files = {{"matchLimitRespected1.sts", R"( - function foo() { - let a = 1; - return a; - } - )"}, - {"matchLimitRespected2.sts", R"( - function foobar() { - let b = 2; - return b; - } - )"}, - {"matchLimitRespected3.sts", R"( - function my_foo() { - let c = 3; - return c; - } - )"}}; - const int maxResultCountTwo = 2; - const int expectedResultSize = 2; - std::string searchTerm = "foo"; - - Initializer initializer; - std::vector allResults; - - for (const auto &file : files) { - std::string sourceStr(file.source); - es2panda_Context *ctx = - initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); - ASSERT_NE(ctx, nullptr); - - std::vector singleFile = {{file.filePath, sourceStr}}; - auto matches = GetNavigateToItems(ctx, singleFile, maxResultCountTwo, searchTerm, false); - allResults.insert(allResults.end(), matches.begin(), matches.end()); - - initializer.DestroyContext(ctx); - } - - ASSERT_LE(allResults.size(), expectedResultSize); -} - -TEST_F(NavigateToTest, MultiFileSubstringMatch) -{ - std::vector files = {{"multiFileSubstringMatch1.sts", R"( - function foo() { - let a = 1; - return a; - } - )"}, - {"multiFileSubstringMatch2.sts", R"( - function foobar() { - let b = 2; - return b; - } - )"}, - {"multiFileSubstringMatch3.sts", R"( - function my_foo() { - let c = 3; - return c; - } - )"}}; - Initializer initializer; - const int maxResultCount = 10; - size_t totalMatches = 0; - std::string searchTerm = "_foo"; - const int expectedResultSize = 1; - - for (const auto &file : files) { - std::string sourceStr(file.source); - es2panda_Context *ctx = - initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); - ASSERT_NE(ctx, nullptr); - - std::vector singleFile = {{file.filePath, sourceStr}}; - auto matches = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); - totalMatches += matches.size(); - - initializer.DestroyContext(ctx); - } - - ASSERT_EQ(totalMatches, expectedResultSize); -} - -TEST_F(NavigateToTest, PrefixMatchOnly) -{ - std::vector files = {{"prefixMatchOnly1.sts", R"( - function foo() { - let a = 1; - return a; - } - )"}, - {"prefixMatchOnly2.sts", R"( - function foobar() { - let b = 2; - return b; - } - )"}, - {"prefixMatchOnly3.sts", R"( - function my_foo() { - let c = 3; - return c; - } - )"}}; - Initializer initializer; - const int maxResultCount = 10; - size_t prefixCount = 0; - const int expectedResultSize = 1; - std::string searchTerm = "foo"; - - for (const auto &file : files) { - std::string sourceStr(file.source); - es2panda_Context *ctx = - initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); - ASSERT_NE(ctx, nullptr); - - std::vector singleFile = {{file.filePath, sourceStr}}; - auto matches = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); - for (const auto &match : matches) { - if (match.matchKind == ark::es2panda::lsp::MatchKind::PREFIX) { - ++prefixCount; - } - } - - initializer.DestroyContext(ctx); - } - - ASSERT_EQ(prefixCount, expectedResultSize); // Only "foobar" is a PREFIX of "foo" -} - -TEST_F(NavigateToTest, MatchFromSecondFile) -{ - std::vector files = {{"matchFromSecondFile1.sts", R"( - function foo() { - let a = 1; - return a; - } - )"}, - {"matchFromSecondFile2.sts", R"( - function foobar() { - let b = 2; - return b; - } - )"}, - {"matchFromSecondFile3.sts", R"( - function my_foo() { - let c = 3; - return c; - } - )"}}; - Initializer initializer; - const int maxResultCount = 10; - const int expectedResultSize = 1; - std::string searchTerm = "foobar"; - std::vector matches; - - for (const auto &file : files) { - std::string sourceStr(file.source); - es2panda_Context *ctx = - initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); - ASSERT_NE(ctx, nullptr); - - std::vector singleFile = {{file.filePath, sourceStr}}; - auto results = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); - matches.insert(matches.end(), results.begin(), results.end()); - - initializer.DestroyContext(ctx); - } - ASSERT_EQ(matches.size(), expectedResultSize); - ASSERT_EQ(matches[0].name, searchTerm); -} - -TEST_F(NavigateToTest, MatchOnClassMember) -{ - std::vector files = {{"matchOnClassMember1.sts", R"( - class Test { - yeke: number = 2; - method() { - let b = 3; - return b; - } - } - )"}, - {"matchOnClassMember2.sts", R"( - function foobar() { - let b = 2; - return b; - } - )"}, - {"matchOnClassMember3.sts", R"( - function my_foo() { - let c = 3; - return c; - } - )"}}; - Initializer initializer; - const int maxResultCount = 10; - const int expectedResultSize = 1; - std::string searchTerm = "yeke"; - std::string containerName = "Test"; - std::vector results; - - for (const auto &file : files) { - std::string sourceStr(file.source); - es2panda_Context *ctx = - initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); - ASSERT_NE(ctx, nullptr); - - std::vector singleFile = {{file.filePath, sourceStr}}; - auto items = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); - results.insert(results.end(), items.begin(), items.end()); - - initializer.DestroyContext(ctx); - } - - ASSERT_EQ(results.size(), expectedResultSize); - ASSERT_EQ(results[0].name, searchTerm); - ASSERT_EQ(results[0].containerName, containerName); -} - } // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/navigate_to_test_1.cpp b/ets2panda/test/unit/lsp/navigate_to_test_1.cpp new file mode 100644 index 0000000000..1456028435 --- /dev/null +++ b/ets2panda/test/unit/lsp/navigate_to_test_1.cpp @@ -0,0 +1,251 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "lsp_api_test.h" +#include "lsp/include/navigate_to.h" + +namespace { + +using ark::es2panda::SourceFile; +using ark::es2panda::lsp::GetNavigateToItems; +using ark::es2panda::lsp::Initializer; +using std::string; +using std::vector; + +class NavigateToTest : public LSPAPITests {}; + +TEST_F(NavigateToTest, MatchLimitRespected) +{ + std::vector files = {{"matchLimitRespected1.sts", R"( + function foo() { + let a = 1; + return a; + } + )"}, + {"matchLimitRespected2.sts", R"( + function foobar() { + let b = 2; + return b; + } + )"}, + {"matchLimitRespected3.sts", R"( + function my_foo() { + let c = 3; + return c; + } + )"}}; + const int maxResultCountTwo = 2; + const int expectedResultSize = 2; + std::string searchTerm = "foo"; + + Initializer initializer; + std::vector allResults; + + for (const auto &file : files) { + std::string sourceStr(file.source); + es2panda_Context *ctx = + initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); + ASSERT_NE(ctx, nullptr); + + std::vector singleFile = {{file.filePath, sourceStr}}; + auto matches = GetNavigateToItems(ctx, singleFile, maxResultCountTwo, searchTerm, false); + allResults.insert(allResults.end(), matches.begin(), matches.end()); + + initializer.DestroyContext(ctx); + } + + ASSERT_LE(allResults.size(), expectedResultSize); +} + +TEST_F(NavigateToTest, MultiFileSubstringMatch) +{ + std::vector files = {{"multiFileSubstringMatch1.sts", R"( + function foo() { + let a = 1; + return a; + } + )"}, + {"multiFileSubstringMatch2.sts", R"( + function foobar() { + let b = 2; + return b; + } + )"}, + {"multiFileSubstringMatch3.sts", R"( + function my_foo() { + let c = 3; + return c; + } + )"}}; + Initializer initializer; + const int maxResultCount = 10; + size_t totalMatches = 0; + std::string searchTerm = "_foo"; + const int expectedResultSize = 1; + + for (const auto &file : files) { + std::string sourceStr(file.source); + es2panda_Context *ctx = + initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); + ASSERT_NE(ctx, nullptr); + + std::vector singleFile = {{file.filePath, sourceStr}}; + auto matches = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); + totalMatches += matches.size(); + + initializer.DestroyContext(ctx); + } + + ASSERT_EQ(totalMatches, expectedResultSize); +} + +TEST_F(NavigateToTest, PrefixMatchOnly) +{ + std::vector files = {{"prefixMatchOnly1.sts", R"( + function foo() { + let a = 1; + return a; + } + )"}, + {"prefixMatchOnly2.sts", R"( + function foobar() { + let b = 2; + return b; + } + )"}, + {"prefixMatchOnly3.sts", R"( + function my_foo() { + let c = 3; + return c; + } + )"}}; + Initializer initializer; + const int maxResultCount = 10; + size_t prefixCount = 0; + const int expectedResultSize = 1; + std::string searchTerm = "foo"; + + for (const auto &file : files) { + std::string sourceStr(file.source); + es2panda_Context *ctx = + initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); + ASSERT_NE(ctx, nullptr); + + std::vector singleFile = {{file.filePath, sourceStr}}; + auto matches = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); + for (const auto &match : matches) { + if (match.matchKind == ark::es2panda::lsp::MatchKind::PREFIX) { + ++prefixCount; + } + } + + initializer.DestroyContext(ctx); + } + + ASSERT_EQ(prefixCount, expectedResultSize); // Only "foobar" is a PREFIX of "foo" +} + +TEST_F(NavigateToTest, MatchFromSecondFile) +{ + std::vector files = {{"matchFromSecondFile1.sts", R"( + function foo() { + let a = 1; + return a; + } + )"}, + {"matchFromSecondFile2.sts", R"( + function foobar() { + let b = 2; + return b; + } + )"}, + {"matchFromSecondFile3.sts", R"( + function my_foo() { + let c = 3; + return c; + } + )"}}; + Initializer initializer; + const int maxResultCount = 10; + const int expectedResultSize = 1; + std::string searchTerm = "foobar"; + std::vector matches; + + for (const auto &file : files) { + std::string sourceStr(file.source); + es2panda_Context *ctx = + initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); + ASSERT_NE(ctx, nullptr); + + std::vector singleFile = {{file.filePath, sourceStr}}; + auto results = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); + matches.insert(matches.end(), results.begin(), results.end()); + + initializer.DestroyContext(ctx); + } + ASSERT_EQ(matches.size(), expectedResultSize); + ASSERT_EQ(matches[0].name, searchTerm); +} + +TEST_F(NavigateToTest, MatchOnClassMember) +{ + std::vector files = {{"matchOnClassMember1.sts", R"( + class Test { + yeke: number = 2; + method() { + let b = 3; + return b; + } + } + )"}, + {"matchOnClassMember2.sts", R"( + function foobar() { + let b = 2; + return b; + } + )"}, + {"matchOnClassMember3.sts", R"( + function my_foo() { + let c = 3; + return c; + } + )"}}; + Initializer initializer; + const int maxResultCount = 10; + const int expectedResultSize = 1; + std::string searchTerm = "yeke"; + std::string containerName = "Test"; + std::vector results; + + for (const auto &file : files) { + std::string sourceStr(file.source); + es2panda_Context *ctx = + initializer.CreateContext(file.filePath.data(), ES2PANDA_STATE_CHECKED, sourceStr.c_str()); + ASSERT_NE(ctx, nullptr); + + std::vector singleFile = {{file.filePath, sourceStr}}; + auto items = GetNavigateToItems(ctx, singleFile, maxResultCount, searchTerm, false); + results.insert(results.end(), items.begin(), items.end()); + + initializer.DestroyContext(ctx); + } + + ASSERT_EQ(results.size(), expectedResultSize); + ASSERT_EQ(results[0].name, searchTerm); + ASSERT_EQ(results[0].containerName, containerName); +} + +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/quick_info_test.cpp b/ets2panda/test/unit/lsp/quick_info_test.cpp index f0da63dba8..e03728e33a 100644 --- a/ets2panda/test/unit/lsp/quick_info_test.cpp +++ b/ets2panda/test/unit/lsp/quick_info_test.cpp @@ -18,6 +18,7 @@ #include "lsp/include/internal_api.h" #include +namespace { using ark::es2panda::lsp::Initializer; class LspQuickInfoTests : public LSPAPITests {}; @@ -336,336 +337,4 @@ TEST_F(LspQuickInfoTests, CreateDisplayForEnumMemberWithStringLiteral) ASSERT_EQ(expected, display); initializer.DestroyContext(ctx); } - -TEST_F(LspQuickInfoTests, CreateDisplayForEnum) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = - initializer.CreateContext("enum-test.ets", ES2PANDA_STATE_CHECKED, "enum MyEnum { A, B, C }"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::CLASS_DEFINITION && - node->AsClassDefinition()->Ident()->Name() == "MyEnum"; - }; - auto found = ast->FindChild(checkFunc); - auto enumDecl = found->AsClassDefinition()->OrigEnumDecl()->AsTSEnumDeclaration(); - std::vector display = ark::es2panda::lsp::CreateDisplayForEnum(enumDecl); - std::vector expected; - expected.emplace_back("enum", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("MyEnum", "enumName"); - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForClass1) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = - initializer.CreateContext("quick-info-test.ets", ES2PANDA_STATE_CHECKED, - "class Test {\n private _a: number = 1;\n public get a(): number {\n " - "return this._a;\n }\n public static ccc:number = 1\n\n constructor(a : " - "number) {\n }\n}\n\nlet a = 1\nlet test: Test = new Test(a)\nlet t_a = test.a"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::CLASS_DECLARATION && - node->AsClassDeclaration()->Definition()->InternalName() != "quick-info-test.ETSGLOBAL"; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForClass(found); - std::vector expected; - auto keyword1 = SymbolDisplayPart("class", "keyword"); - auto keyword2 = SymbolDisplayPart(" ", "space"); - auto keyword3 = SymbolDisplayPart("Test", "className"); - expected.push_back(keyword1); - expected.push_back(keyword2); - expected.push_back(keyword3); - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForUnionTypeAlias) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("union-type-alias-test.ets", ES2PANDA_STATE_CHECKED, - "type TestUnion = string | number;"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_ALIAS_DECLARATION; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForTypeAlias(found); - std::vector expected; - expected.emplace_back("type", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("TestUnion", "className"); - expected.emplace_back(" ", "space"); - expected.emplace_back("=", "operator"); - expected.emplace_back(" ", "space"); - expected.emplace_back("string|number", "typeName"); - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForTypeAlias) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = - initializer.CreateContext("type-alias-test.ets", ES2PANDA_STATE_CHECKED, "type TestType = string;"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_ALIAS_DECLARATION; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForTypeAlias(found); - std::vector expected; - expected.emplace_back("type", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("TestType", "className"); - expected.emplace_back(" ", "space"); - expected.emplace_back("=", "operator"); - expected.emplace_back(" ", "space"); - expected.emplace_back("string", "typeName"); - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForInterface) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext( - "quick-info-test.ets", ES2PANDA_STATE_CHECKED, - "interface Inner { key : string; }\ninterface Outer { inner : Inner; keyValue : number; }"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::TS_INTERFACE_DECLARATION; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForInterface(found); - std::vector expected; - auto keyword1 = SymbolDisplayPart("interface", "keyword"); - auto keyword2 = SymbolDisplayPart(" ", "space"); - auto keyword3 = SymbolDisplayPart("Inner", "className"); - expected.push_back(keyword1); - expected.push_back(keyword2); - expected.push_back(keyword3); - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForTypeAliasTypeParameter) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = - initializer.CreateContext("type-alias-type-param-test.ets", ES2PANDA_STATE_CHECKED, "type list = T[]"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_PARAMETER; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForTypeParameter(found); - std::vector expected; - expected.emplace_back("T", "typeParameter"); - expected.emplace_back(" ", "space"); - expected.emplace_back("in", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("type", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("list", "typeName"); - expected.emplace_back("<", "punctuation"); - expected.emplace_back("T", "typeParameter"); - expected.emplace_back(">", "punctuation"); - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForClassDeclarationTypeParameter) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("class-type-param-test.ets", ES2PANDA_STATE_CHECKED, - "class Queue { private items: T[] = []; }"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_PARAMETER; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForTypeParameter(found); - std::vector expected; - expected.emplace_back("T", "typeParameter"); - expected.emplace_back(" ", "space"); - expected.emplace_back("in", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("Queue", "className"); - expected.emplace_back("<", "punctuation"); - expected.emplace_back("T", "typeParameter"); - expected.emplace_back(">", "punctuation"); - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForMethodDefinition) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("method-definition-test.ets", ES2PANDA_STATE_CHECKED, - "function func(a: number): string { return 'function1'; }"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::METHOD_DEFINITION && - node->AsMethodDefinition()->Id()->Name() != "main" && - node->AsMethodDefinition()->Id()->Name() != "_$init$_"; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForMethodDefinition(found, ""); - std::vector expected; - - // Expected parts for the method definition - expected.emplace_back("function", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("func", "functionName"); - expected.emplace_back("(", "punctuation"); - expected.emplace_back("a", "functionParameter"); - expected.emplace_back(":", "punctuation"); - expected.emplace_back(" ", "space"); - expected.emplace_back("number", "typeParameter"); - expected.emplace_back(")", "punctuation"); - expected.emplace_back(":", "punctuation"); - expected.emplace_back(" ", "space"); - expected.emplace_back("string", "returnType"); - - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForScriptFunctionTypeParameter) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("function-type-param-test.ets", ES2PANDA_STATE_CHECKED, - "function identity(arg: T): T { return arg }"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_PARAMETER; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForTypeParameter(found); - std::vector expected; - expected.emplace_back("T", "typeParameter"); - expected.emplace_back(" ", "space"); - expected.emplace_back("in", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("identity", "functionName"); - expected.emplace_back("<", "punctuation"); - expected.emplace_back("T", "typeParameter"); - expected.emplace_back(",", "punctuation"); - expected.emplace_back(" ", "space"); - expected.emplace_back("D", "typeParameter"); - expected.emplace_back(">", "punctuation"); - expected.emplace_back("(", "punctuation"); - expected.emplace_back("arg", "functionParameter"); - expected.emplace_back(":", "punctuation"); - expected.emplace_back(" ", "space"); - expected.emplace_back("T", "typeParameter"); - expected.emplace_back(")", "punctuation"); - expected.emplace_back(":", "punctuation"); - expected.emplace_back(" ", "space"); - expected.emplace_back("T", "returnType"); - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForClassProperty1) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = - initializer.CreateContext("class-property-test.ets", ES2PANDA_STATE_CHECKED, - "class MyClass {\n public myProp: number = 0;\n}\n let obj = new MyClass();"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::CLASS_PROPERTY && - node->AsClassProperty()->Key()->AsIdentifier()->Name() != "ETSGLOBAL"; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForClassProperty(found, "const"); - std::vector expected; - - expected.emplace_back("const", "keyword"); - expected.emplace_back(" ", "space"); - expected.emplace_back("obj", "property"); - expected.emplace_back(":", "punctuation"); - expected.emplace_back(" ", "space"); - expected.emplace_back("MyClass", "typeName"); - - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForClassProperty2) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("class-property-test.ets", ES2PANDA_STATE_CHECKED, - "class MyClass {\n public myProp: number = 0;\n}"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::CLASS_PROPERTY && - node->AsClassProperty()->Key()->AsIdentifier()->Name() != "ETSGLOBAL"; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForClassProperty(found, "const"); - std::vector expected; - - expected.emplace_back("MyClass", "className"); - expected.emplace_back(".", "punctuation"); - expected.emplace_back("myProp", "property"); - expected.emplace_back(":", "punctuation"); - expected.emplace_back(" ", "space"); - expected.emplace_back("number", "typeName"); - - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} - -TEST_F(LspQuickInfoTests, CreateDisplayForParameterExpression) -{ - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("parameter-expression-test.ets", ES2PANDA_STATE_CHECKED, - "function func(param1: string, param2: number) {}"); - ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); - auto context = reinterpret_cast(ctx); - auto ast = reinterpret_cast(context->parserProgram->Ast()); - auto checkFunc = [](ark::es2panda::ir::AstNode *node) { - return node->Type() == ark::es2panda::ir::AstNodeType::ETS_PARAMETER_EXPRESSION && - node->AsETSParameterExpression()->Name() != "param2"; - }; - auto found = ast->FindChild(checkFunc); - std::vector display = ark::es2panda::lsp::CreateDisplayForETSParameterExpression(found); - std::vector expected; - - expected.emplace_back("param1", "functionParameter"); - expected.emplace_back(":", "punctuation"); - expected.emplace_back(" ", "space"); - expected.emplace_back("string", "typeName"); - - ASSERT_EQ(expected, display); - initializer.DestroyContext(ctx); -} +} // namespace diff --git a/ets2panda/test/unit/lsp/quick_info_test_1.cpp b/ets2panda/test/unit/lsp/quick_info_test_1.cpp new file mode 100644 index 0000000000..916dea9a8f --- /dev/null +++ b/ets2panda/test/unit/lsp/quick_info_test_1.cpp @@ -0,0 +1,357 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "lsp/include/quick_info.h" +#include "lsp_api_test.h" +#include "lsp/include/internal_api.h" +#include +namespace { +using ark::es2panda::lsp::Initializer; + +class LspQuickInfoTests : public LSPAPITests {}; + +TEST_F(LspQuickInfoTests, CreateDisplayForEnum) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = + initializer.CreateContext("enum-test.ets", ES2PANDA_STATE_CHECKED, "enum MyEnum { A, B, C }"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::CLASS_DEFINITION && + node->AsClassDefinition()->Ident()->Name() == "MyEnum"; + }; + auto found = ast->FindChild(checkFunc); + auto enumDecl = found->AsClassDefinition()->OrigEnumDecl()->AsTSEnumDeclaration(); + std::vector display = ark::es2panda::lsp::CreateDisplayForEnum(enumDecl); + std::vector expected; + expected.emplace_back("enum", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("MyEnum", "enumName"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForClass1) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = + initializer.CreateContext("quick-info-test.ets", ES2PANDA_STATE_CHECKED, + "class Test {\n private _a: number = 1;\n public get a(): number {\n " + "return this._a;\n }\n public static ccc:number = 1\n\n constructor(a : " + "number) {\n }\n}\n\nlet a = 1\nlet test: Test = new Test(a)\nlet t_a = test.a"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::CLASS_DECLARATION && + node->AsClassDeclaration()->Definition()->InternalName() != "quick-info-test.ETSGLOBAL"; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForClass(found); + std::vector expected; + auto keyword1 = SymbolDisplayPart("class", "keyword"); + auto keyword2 = SymbolDisplayPart(" ", "space"); + auto keyword3 = SymbolDisplayPart("Test", "className"); + expected.push_back(keyword1); + expected.push_back(keyword2); + expected.push_back(keyword3); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForUnionTypeAlias) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("union-type-alias-test.ets", ES2PANDA_STATE_CHECKED, + "type TestUnion = string | number;"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_ALIAS_DECLARATION; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeAlias(found); + std::vector expected; + expected.emplace_back("type", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("TestUnion", "className"); + expected.emplace_back(" ", "space"); + expected.emplace_back("=", "operator"); + expected.emplace_back(" ", "space"); + expected.emplace_back("string|number", "typeName"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForTypeAlias) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = + initializer.CreateContext("type-alias-test.ets", ES2PANDA_STATE_CHECKED, "type TestType = string;"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_ALIAS_DECLARATION; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeAlias(found); + std::vector expected; + expected.emplace_back("type", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("TestType", "className"); + expected.emplace_back(" ", "space"); + expected.emplace_back("=", "operator"); + expected.emplace_back(" ", "space"); + expected.emplace_back("string", "typeName"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForInterface) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext( + "quick-info-test.ets", ES2PANDA_STATE_CHECKED, + "interface Inner { key : string; }\ninterface Outer { inner : Inner; keyValue : number; }"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::TS_INTERFACE_DECLARATION; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForInterface(found); + std::vector expected; + auto keyword1 = SymbolDisplayPart("interface", "keyword"); + auto keyword2 = SymbolDisplayPart(" ", "space"); + auto keyword3 = SymbolDisplayPart("Inner", "className"); + expected.push_back(keyword1); + expected.push_back(keyword2); + expected.push_back(keyword3); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForTypeAliasTypeParameter) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = + initializer.CreateContext("type-alias-type-param-test.ets", ES2PANDA_STATE_CHECKED, "type list = T[]"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_PARAMETER; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeParameter(found); + std::vector expected; + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(" ", "space"); + expected.emplace_back("in", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("type", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("list", "typeName"); + expected.emplace_back("<", "punctuation"); + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(">", "punctuation"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForClassDeclarationTypeParameter) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("class-type-param-test.ets", ES2PANDA_STATE_CHECKED, + "class Queue { private items: T[] = []; }"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_PARAMETER; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeParameter(found); + std::vector expected; + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(" ", "space"); + expected.emplace_back("in", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("Queue", "className"); + expected.emplace_back("<", "punctuation"); + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(">", "punctuation"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForMethodDefinition) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("method-definition-test.ets", ES2PANDA_STATE_CHECKED, + "function func(a: number): string { return 'function1'; }"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::METHOD_DEFINITION && + node->AsMethodDefinition()->Id()->Name() != "main" && + node->AsMethodDefinition()->Id()->Name() != "_$init$_"; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForMethodDefinition(found, ""); + std::vector expected; + + // Expected parts for the method definition + expected.emplace_back("function", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("func", "functionName"); + expected.emplace_back("(", "punctuation"); + expected.emplace_back("a", "functionParameter"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("number", "typeParameter"); + expected.emplace_back(")", "punctuation"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("string", "returnType"); + + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForScriptFunctionTypeParameter) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("function-type-param-test.ets", ES2PANDA_STATE_CHECKED, + "function identity(arg: T): T { return arg }"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::TS_TYPE_PARAMETER; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForTypeParameter(found); + std::vector expected; + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(" ", "space"); + expected.emplace_back("in", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("identity", "functionName"); + expected.emplace_back("<", "punctuation"); + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(",", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("D", "typeParameter"); + expected.emplace_back(">", "punctuation"); + expected.emplace_back("(", "punctuation"); + expected.emplace_back("arg", "functionParameter"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("T", "typeParameter"); + expected.emplace_back(")", "punctuation"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("T", "returnType"); + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForClassProperty1) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = + initializer.CreateContext("class-property-test.ets", ES2PANDA_STATE_CHECKED, + "class MyClass {\n public myProp: number = 0;\n}\n let obj = new MyClass();"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::CLASS_PROPERTY && + node->AsClassProperty()->Key()->AsIdentifier()->Name() != "ETSGLOBAL"; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForClassProperty(found, "const"); + std::vector expected; + + expected.emplace_back("const", "keyword"); + expected.emplace_back(" ", "space"); + expected.emplace_back("obj", "property"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("MyClass", "typeName"); + + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForClassProperty2) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("class-property-test.ets", ES2PANDA_STATE_CHECKED, + "class MyClass {\n public myProp: number = 0;\n}"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::CLASS_PROPERTY && + node->AsClassProperty()->Key()->AsIdentifier()->Name() != "ETSGLOBAL"; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForClassProperty(found, "const"); + std::vector expected; + + expected.emplace_back("MyClass", "className"); + expected.emplace_back(".", "punctuation"); + expected.emplace_back("myProp", "property"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("number", "typeName"); + + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} + +TEST_F(LspQuickInfoTests, CreateDisplayForParameterExpression) +{ + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("parameter-expression-test.ets", ES2PANDA_STATE_CHECKED, + "function func(param1: string, param2: number) {}"); + ASSERT_EQ(ContextState(ctx), ES2PANDA_STATE_CHECKED); + auto context = reinterpret_cast(ctx); + auto ast = reinterpret_cast(context->parserProgram->Ast()); + auto checkFunc = [](ark::es2panda::ir::AstNode *node) { + return node->Type() == ark::es2panda::ir::AstNodeType::ETS_PARAMETER_EXPRESSION && + node->AsETSParameterExpression()->Name() != "param2"; + }; + auto found = ast->FindChild(checkFunc); + std::vector display = ark::es2panda::lsp::CreateDisplayForETSParameterExpression(found); + std::vector expected; + + expected.emplace_back("param1", "functionParameter"); + expected.emplace_back(":", "punctuation"); + expected.emplace_back(" ", "space"); + expected.emplace_back("string", "typeName"); + + ASSERT_EQ(expected, display); + initializer.DestroyContext(ctx); +} +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/suggestion_diagnostics_test.cpp b/ets2panda/test/unit/lsp/suggestion_diagnostics_test.cpp index ea02cbeb75..64ab05a210 100644 --- a/ets2panda/test/unit/lsp/suggestion_diagnostics_test.cpp +++ b/ets2panda/test/unit/lsp/suggestion_diagnostics_test.cpp @@ -19,7 +19,7 @@ #include "lsp/include/classifier.h" #include "lsp_api_test.h" #include "public/es2panda_lib.h" - +namespace { using ark::es2panda::lsp::Initializer; class LspSuggestionTests : public LSPAPITests {}; @@ -249,149 +249,4 @@ TEST_F(LspSuggestionTests, isPromiseHandler4) EXPECT_TRUE(ark::es2panda::lsp::IsPromiseHandler(callExprs.at(0))); initializer.DestroyContext(ctx); } - -TEST_F(LspSuggestionTests, isFixablePromiseHandler) -{ - const char *source = - "function fetchData():Promise{\nreturn Promise.resolve(\"Success\");\n}" - "\nfetchData().then();"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, isFixablePromiseHandler2) -{ - const char *source = - "function fetchData(name:string):Promise{\nreturn Promise.resolve(\"Success\");\n}" - "\nfetchData(\"test\").finally();"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, isFixablePromiseHandler3) -{ - const char *source = - "function fetchData():Promise{\n" - "return Promise.reject(\"Error\");\n}" - "\nfetchData().catch();"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, isFixablePromiseHandler4) -{ - const char *source = - "function fetchData(name: string,name2:string):Promise{\n" - "\nreturn Promise.resolve(\"Success\");" - "\n}\nfetchData(\"test\",\"test2\").finally();"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, isReturnStatementWithFixablePromiseHandler) -{ - const char *source = - "function fetchData(){\nreturn Promise.resolve(\"h\")\n;}\nfunction processData()" - "{\nreturn fetchData().then();\n};\nprocessData();\n"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::IsReturnStatementWithFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, isReturnStatementWithFixablePromiseHandler2) -{ - const char *source = - "function fetchData(){\nreturn Promise.resolve(\"h\")\n;}\n" - "\nfunction processData(){\nreturn fetchData().finally();\n};\nprocessData();\n"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::IsReturnStatementWithFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, isReturnStatementWithFixablePromiseHandler3) -{ - const char *source = - "function fetchData(){\nreturn Promise.reject(\"h\")\n;}\nfunction processData(){\n" - "\nreturn fetchData().catch();\n};\nprocessData();\n"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::IsReturnStatementWithFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, hasReturnStatementWithPromiseHandler) -{ - const char *source = - "function fetchData(){\nreturn Promise.reject(\"h\")\n;}\nfunction processData()" - "{\nreturn fetchData().catch();\n};\nprocessData();\n"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::HasReturnStatementWithPromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, hasReturnStatementWithPromiseHandler2) -{ - const char *source = - "function fetchData(){\nreturn Promise.resolve(\"h\")\n;}\nfunction processData(){\n" - "\nreturn fetchData().finally();\n};\nprocessData();\n"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::HasReturnStatementWithPromiseHandler(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, isConvertibleFunction) -{ - const char *source = - "function fetchData(){\nreturn Promise.resolve(\"h\")\n;}\nfunction processData()" - "{\nreturn fetchData().finally();\n};\nprocessData();\n"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - EXPECT_TRUE(ark::es2panda::lsp::IsConvertibleFunction(ast, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} - -TEST_F(LspSuggestionTests, isFixablePromiseArgument2) -{ - const char *source = "function myFun(x: string): string\n {return x;}\nconsole.log(\"add(1+2)\");"; - Initializer initializer = Initializer(); - es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); - std::unordered_map visitedNestedConvertibleFunctions; - auto ast = GetAstFromContext(ctx); - auto node = ast->FindChild([](ark::es2panda::ir::AstNode *childNode) { - return (childNode->Type() == ark::es2panda::ir::AstNodeType::FUNCTION_EXPRESSION); - }); - EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseArgument(node, visitedNestedConvertibleFunctions)); - initializer.DestroyContext(ctx); -} +} // namespace \ No newline at end of file diff --git a/ets2panda/test/unit/lsp/suggestion_diagnostics_test_1.cpp b/ets2panda/test/unit/lsp/suggestion_diagnostics_test_1.cpp new file mode 100644 index 0000000000..65ff4ea086 --- /dev/null +++ b/ets2panda/test/unit/lsp/suggestion_diagnostics_test_1.cpp @@ -0,0 +1,171 @@ +/** + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "lsp/include/suggestion_diagnostics.h" +#include +#include "lsp/include/internal_api.h" +#include "lsp_api_test.h" +#include "public/es2panda_lib.h" +namespace { +using ark::es2panda::lsp::Initializer; + +class LspSuggestionTests : public LSPAPITests {}; + +TEST_F(LspSuggestionTests, isFixablePromiseHandler) +{ + const char *source = + "function fetchData():Promise{\nreturn Promise.resolve(\"Success\");\n}" + "\nfetchData().then();"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, isFixablePromiseHandler2) +{ + const char *source = + "function fetchData(name:string):Promise{\nreturn Promise.resolve(\"Success\");\n}" + "\nfetchData(\"test\").finally();"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, isFixablePromiseHandler3) +{ + const char *source = + "function fetchData():Promise{\n" + "return Promise.reject(\"Error\");\n}" + "\nfetchData().catch();"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, isFixablePromiseHandler4) +{ + const char *source = + "function fetchData(name: string,name2:string):Promise{\n" + "\nreturn Promise.resolve(\"Success\");" + "\n}\nfetchData(\"test\",\"test2\").finally();"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, isReturnStatementWithFixablePromiseHandler) +{ + const char *source = + "function fetchData(){\nreturn Promise.resolve(\"h\")\n;}\nfunction processData()" + "{\nreturn fetchData().then();\n};\nprocessData();\n"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::IsReturnStatementWithFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, isReturnStatementWithFixablePromiseHandler2) +{ + const char *source = + "function fetchData(){\nreturn Promise.resolve(\"h\")\n;}\n" + "\nfunction processData(){\nreturn fetchData().finally();\n};\nprocessData();\n"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::IsReturnStatementWithFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, isReturnStatementWithFixablePromiseHandler3) +{ + const char *source = + "function fetchData(){\nreturn Promise.reject(\"h\")\n;}\nfunction processData(){\n" + "\nreturn fetchData().catch();\n};\nprocessData();\n"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::IsReturnStatementWithFixablePromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, hasReturnStatementWithPromiseHandler) +{ + const char *source = + "function fetchData(){\nreturn Promise.reject(\"h\")\n;}\nfunction processData()" + "{\nreturn fetchData().catch();\n};\nprocessData();\n"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::HasReturnStatementWithPromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, hasReturnStatementWithPromiseHandler2) +{ + const char *source = + "function fetchData(){\nreturn Promise.resolve(\"h\")\n;}\nfunction processData(){\n" + "\nreturn fetchData().finally();\n};\nprocessData();\n"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::HasReturnStatementWithPromiseHandler(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, isConvertibleFunction) +{ + const char *source = + "function fetchData(){\nreturn Promise.resolve(\"h\")\n;}\nfunction processData()" + "{\nreturn fetchData().finally();\n};\nprocessData();\n"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + EXPECT_TRUE(ark::es2panda::lsp::IsConvertibleFunction(ast, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} + +TEST_F(LspSuggestionTests, isFixablePromiseArgument2) +{ + const char *source = "function myFun(x: string): string\n {return x;}\nconsole.log(\"add(1+2)\");"; + Initializer initializer = Initializer(); + es2panda_Context *ctx = initializer.CreateContext("sug-diag.ets", ES2PANDA_STATE_CHECKED, source); + std::unordered_map visitedNestedConvertibleFunctions; + auto ast = GetAstFromContext(ctx); + auto node = ast->FindChild([](ark::es2panda::ir::AstNode *childNode) { + return (childNode->Type() == ark::es2panda::ir::AstNodeType::FUNCTION_EXPRESSION); + }); + EXPECT_TRUE(ark::es2panda::lsp::IsFixablePromiseArgument(node, visitedNestedConvertibleFunctions)); + initializer.DestroyContext(ctx); +} +} // namespace \ No newline at end of file -- Gitee From 69611614b2c9a809dee653bdce08a73e376cd828 Mon Sep 17 00:00:00 2001 From: daizihan Date: Fri, 4 Jul 2025 14:59:26 +0800 Subject: [PATCH 097/145] Fix fuzz crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICK0DL?from=project-issue Signed-off-by: daizihan --- ets2panda/checker/ets/helpers.cpp | 3 ++- ets2panda/parser/TypedParser.cpp | 3 --- .../test/ast/compiler/ets/fuzzingtest4.ets | 22 ++++++++++++++++++ .../test/ast/compiler/ets/fuzzingtest5.ets | 23 +++++++++++++++++++ .../ets/new_expr_with_succesive_multi_dot.ets | 1 + 5 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/fuzzingtest4.ets create mode 100644 ets2panda/test/ast/compiler/ets/fuzzingtest5.ets diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index a30b44a6fb..05b12e466d 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -39,7 +39,8 @@ std::pair ETSChecker::FindVariable return {nullptr, nullptr}; } const auto searchFlags = PropertySearchFlags::SEARCH_ALL | PropertySearchFlags::SEARCH_IN_BASE | - PropertySearchFlags::SEARCH_IN_INTERFACES; + PropertySearchFlags::SEARCH_IN_INTERFACES | + PropertySearchFlags::DISALLOW_SYNTHETIC_METHOD_CREATION; auto *resolved = classType->GetProperty(name, searchFlags); while (classType->EnclosingType() != nullptr && resolved == nullptr) { classType = classType->EnclosingType(); diff --git a/ets2panda/parser/TypedParser.cpp b/ets2panda/parser/TypedParser.cpp index cfdf144927..d39bcaae81 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -1219,9 +1219,6 @@ ir::Expression *TypedParser::ParseQualifiedName(ExpressionParseFlags flags) Lexer()->NextToken(); break; default: - if ((flags & ExpressionParseFlags::POTENTIAL_NEW_ARRAY) != 0) { - return expr; - } LogError(diagnostic::ID_EXPECTED); return AllocBrokenExpression(Lexer()->GetToken().Loc()); } diff --git a/ets2panda/test/ast/compiler/ets/fuzzingtest4.ets b/ets2panda/test/ast/compiler/ets/fuzzingtest4.ets new file mode 100644 index 0000000000..93c9fbf39d --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzzingtest4.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() { + new CC. +} + +/* @@? 17:9 Error TypeError: Cannot find type 'CC'. */ +/* @@? 18:1 Error SyntaxError: Identifier expected. */ +/* @@? 18:1 Error TypeError: Invalid type reference. */ diff --git a/ets2panda/test/ast/compiler/ets/fuzzingtest5.ets b/ets2panda/test/ast/compiler/ets/fuzzingtest5.ets new file mode 100644 index 0000000000..ad88a4d71c --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzzingtest5.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 A { + f() { + f = 300 + } +} + +/* @@? 18:9 Error TypeError: Property 'f' must be accessed through 'this' */ +/* @@? 18:13 Error TypeError: Type 'int' cannot be assigned to type '() => void' */ diff --git a/ets2panda/test/ast/compiler/ets/new_expr_with_succesive_multi_dot.ets b/ets2panda/test/ast/compiler/ets/new_expr_with_succesive_multi_dot.ets index 30c7c5860d..dc623f5b1a 100644 --- a/ets2panda/test/ast/compiler/ets/new_expr_with_succesive_multi_dot.ets +++ b/ets2panda/test/ast/compiler/ets/new_expr_with_succesive_multi_dot.ets @@ -20,4 +20,5 @@ importet lock1 = new ArkTSUt../main; /* @@? 16:10 Error TypeError: Unresolved reference lock1 */ /* @@? 16:18 Error TypeError: Bad operand type, the types of the operands must be numeric type. */ /* @@? 16:30 Error SyntaxError: Identifier expected. */ +/* @@? 16:31 Error SyntaxError: Identifier expected. */ /* @@? 16:31 Error TypeError: Invalid type reference. */ -- Gitee From 915a8e54d1c73ef22886004858f5c9d0f0af35e0 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Fri, 6 Jun 2025 23:51:36 +0800 Subject: [PATCH 098/145] Allow "use static" on files first line Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICACF5 Description: Allow use "use static" on the first line of source files and declaration files 1. In parser phase, first step is to attempt to load "use static" -> StringLiteral and add it to topstatements. 2. In TopLevelStatements phase, check topstatements. If the first statement is "use static", remove it. Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- .../ets/topLevelStmts/topLevelStmts.cpp | 21 ++++++++++++++++ ets2panda/compiler/scripts/signatures.yaml | 2 ++ ets2panda/parser/ETSparser.cpp | 19 ++++++++++++++ ets2panda/parser/ETSparser.h | 1 + .../compiler/ets/use_static_flag/export1.ets | 17 +++++++++++++ .../compiler/ets/use_static_flag/export2.ets | 17 +++++++++++++ .../use_static_flag/flag_after_copyright.ets | 18 +++++++++++++ .../use_static_flag/flag_after_importdecl.ets | 20 +++++++++++++++ .../flag_before_importdecl.ets | 18 +++++++++++++ .../use_static_flag/flag_in_first_line.ets | 17 +++++++++++++ .../use_static_flag/flag_in_first_line_2.ets | 17 +++++++++++++ .../flag_in_first_line_2_neg.ets | 19 ++++++++++++++ .../flag_in_first_line_3_neg.ets | 19 ++++++++++++++ .../flag_in_first_line_neg.ets | 19 ++++++++++++++ .../flag_middle_importdecl_neg.ets | 20 +++++++++++++++ .../package/flag_before_package.ets | 17 +++++++++++++ .../package/flag_before_package2.ets | 17 +++++++++++++ .../package_2_neg/flag_before_package.ets | 24 ++++++++++++++++++ .../package_3_neg/flag_before_package.ets | 25 +++++++++++++++++++ .../package_neg/flag_package.ets | 20 +++++++++++++++ .../package_neg/flag_package2.ets | 19 ++++++++++++++ .../srcdumper/srcdumper-ets-ignored.txt | 2 ++ 22 files changed, 368 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/export1.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/export2.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_after_copyright.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_after_importdecl.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_before_importdecl.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_2.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_2_neg.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_3_neg.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_neg.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/flag_middle_importdecl_neg.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/package/flag_before_package.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/package/flag_before_package2.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/package_2_neg/flag_before_package.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/package_3_neg/flag_before_package.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/package_neg/flag_package.ets create mode 100644 ets2panda/test/ast/compiler/ets/use_static_flag/package_neg/flag_package2.ets diff --git a/ets2panda/compiler/lowering/ets/topLevelStmts/topLevelStmts.cpp b/ets2panda/compiler/lowering/ets/topLevelStmts/topLevelStmts.cpp index 28c205ee50..bd503f088e 100644 --- a/ets2panda/compiler/lowering/ets/topLevelStmts/topLevelStmts.cpp +++ b/ets2panda/compiler/lowering/ets/topLevelStmts/topLevelStmts.cpp @@ -48,8 +48,29 @@ static bool CheckProgramSourcesConsistency(parser::Program *program) return success; } +static void CheckFileHeaderFlag(parser::Program *program) +{ + auto &statements = program->Ast()->Statements(); + if (statements.empty()) { + return; + } + + if (!statements.front()->IsExpressionStatement()) { + return; + } + + // If further processing based on "use static" is required later, such as throwing a warning or modifying the node, + // perform the operation here. + auto *expansion = statements.front()->AsExpressionStatement()->GetExpression(); + if (expansion->IsStringLiteral() && expansion->AsStringLiteral()->Str() == Signatures::STATIC_PROGRAM_FLAG) { + statements.erase(statements.begin()); + return; + } +} + bool TopLevelStatements::Perform(public_lib::Context *ctx, parser::Program *program) { + CheckFileHeaderFlag(program); auto imports = ImportExportDecls(program->VarBinder()->AsETSBinder(), ctx->parser->AsETSParser()); imports.ParseDefaultSources(); if (!CheckProgramSourcesConsistency(program)) { diff --git a/ets2panda/compiler/scripts/signatures.yaml b/ets2panda/compiler/scripts/signatures.yaml index 930c5a0408..3a4186c8b7 100644 --- a/ets2panda/compiler/scripts/signatures.yaml +++ b/ets2panda/compiler/scripts/signatures.yaml @@ -226,6 +226,8 @@ defines: ref: UNUSED_ETSGLOBAL_INIT - name: 'ETSGLOBAL.main:void;' ref: UNUSED_ETSGLOBAL_MAIN + - name: 'use static' + ref: STATIC_PROGRAM_FLAG packages: - name: 'std.core' diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 6f423f8142..f42151a120 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -121,6 +121,7 @@ void ETSParser::ParseProgram(ScriptKind kind) } ArenaVector statements(Allocator()->Adapter()); + ParseFileHeaderFlag(startLoc, &statements); auto decl = ParsePackageDeclaration(); if (decl != nullptr) { statements.emplace_back(decl); @@ -147,6 +148,23 @@ void ETSParser::ParseProgram(ScriptKind kind) GetProgram()->SetAst(script); } +void ETSParser::ParseFileHeaderFlag(lexer::SourcePosition startLoc, ArenaVector *statements) +{ + if (Lexer()->GetToken().KeywordType() != lexer::TokenType::LITERAL_STRING || + Lexer()->GetToken().String() != compiler::Signatures::STATIC_PROGRAM_FLAG) { + return; + } + + ir::Expression *fileHeaderFlag = ParseStringLiteral(); + auto *exprStatementNode = AllocNode(fileHeaderFlag); + + exprStatementNode->SetRange({startLoc, fileHeaderFlag->End()}); + ConsumeSemicolon(exprStatementNode); + if (statements != nullptr) { + statements->push_back(exprStatementNode); + } +} + ir::ETSModule *ETSParser::ParseETSGlobalScript(lexer::SourcePosition startLoc, ArenaVector &statements) { ETSNolintParser etsnolintParser(this); @@ -408,6 +426,7 @@ parser::Program *ETSParser::ParseSource(const SourceFile &sourceFile) Lexer()->NextToken(); ArenaVector statements(Allocator()->Adapter()); + ParseFileHeaderFlag(startLoc, nullptr); auto decl = ParsePackageDeclaration(); ir::ETSModule *script = nullptr; if (decl != nullptr) { diff --git a/ets2panda/parser/ETSparser.h b/ets2panda/parser/ETSparser.h index 6a2e718765..37b3d195b3 100644 --- a/ets2panda/parser/ETSparser.h +++ b/ets2panda/parser/ETSparser.h @@ -210,6 +210,7 @@ private: ArenaVector &directImportsFromMainSource); parser::Program *ParseSource(const SourceFile &sourceFile); ir::ETSModule *ParseETSGlobalScript(lexer::SourcePosition startLoc, ArenaVector &statements); + void ParseFileHeaderFlag(lexer::SourcePosition startLoc, ArenaVector *statements); ir::ETSModule *ParseImportsOnly(lexer::SourcePosition startLoc, ArenaVector &statements); ir::AstNode *ParseImportDefaultSpecifier(ArenaVector *specifiers) override; void *ApplyAnnotationsToClassElement(ir::AstNode *property, ArenaVector &&annotations, diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/export1.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/export1.ets new file mode 100644 index 0000000000..3b6361ce1a --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/export1.ets @@ -0,0 +1,17 @@ +"use static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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{} diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/export2.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/export2.ets new file mode 100644 index 0000000000..dd2d2b0a2b --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/export2.ets @@ -0,0 +1,17 @@ +"use static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 B{} diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_after_copyright.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_after_copyright.ets new file mode 100644 index 0000000000..f5862745c1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_after_copyright.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" + +class A{} diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_after_importdecl.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_after_importdecl.ets new file mode 100644 index 0000000000..7245e8367d --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_after_importdecl.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 as A } from "./export1.ets" +import { B as B } from "./export2.ets" + +"use static" +let str:String = "use static" diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_before_importdecl.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_before_importdecl.ets new file mode 100644 index 0000000000..730bab7c5d --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_before_importdecl.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" +import {A as A} from "./export1.ets" +import {B as B} from "./export2.ets" diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line.ets new file mode 100644 index 0000000000..34045c2ff1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line.ets @@ -0,0 +1,17 @@ +"use static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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{} diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_2.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_2.ets new file mode 100644 index 0000000000..c14b258b49 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_2.ets @@ -0,0 +1,17 @@ +'use static' +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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{} diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_2_neg.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_2_neg.ets new file mode 100644 index 0000000000..df09abb5e1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_2_neg.ets @@ -0,0 +1,19 @@ +'use statics' +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 as A } from "./export1.ets" + +/* @@? 17:1 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_3_neg.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_3_neg.ets new file mode 100644 index 0000000000..1b1cd257ac --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_3_neg.ets @@ -0,0 +1,19 @@ +"uses static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 as A } from "./export1.ets" + +/* @@? 17:1 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_neg.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_neg.ets new file mode 100644 index 0000000000..e0a410adc7 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_in_first_line_neg.ets @@ -0,0 +1,19 @@ +'uses static' +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 as A } from "./export1.ets" + +/* @@? 17:1 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/flag_middle_importdecl_neg.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_middle_importdecl_neg.ets new file mode 100644 index 0000000000..b048662c57 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/flag_middle_importdecl_neg.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 as A} from "./export1.ets" +"use static" +import {B as B} from "./export2.ets" + +/* @@? 18:1 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/package/flag_before_package.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/package/flag_before_package.ets new file mode 100644 index 0000000000..07508594ee --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/package/flag_before_package.ets @@ -0,0 +1,17 @@ +"use static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usestaticpackage; diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/package/flag_before_package2.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/package/flag_before_package2.ets new file mode 100644 index 0000000000..07508594ee --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/package/flag_before_package2.ets @@ -0,0 +1,17 @@ +"use static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usestaticpackage; diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/package_2_neg/flag_before_package.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/package_2_neg/flag_before_package.ets new file mode 100644 index 0000000000..ee44269d82 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/package_2_neg/flag_before_package.ets @@ -0,0 +1,24 @@ +"use static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usestaticpackage3; + +let str2:String = "use static" +import {A as A} from "../export1.ets" +import {B as B} from "../export2.ets" + +/* @@? 20:1 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ +/* @@? 21:1 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/package_3_neg/flag_before_package.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/package_3_neg/flag_before_package.ets new file mode 100644 index 0000000000..55490f06d0 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/package_3_neg/flag_before_package.ets @@ -0,0 +1,25 @@ +"use static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usestaticpackage3; + +"use static" +import {A as A} from "../export1.ets" +import {B as B} from "../export2.ets" + +/* @@? 19:1 Error SyntaxError: Invalid package toplevel statement */ +/* @@? 20:1 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ +/* @@? 21:1 Error SyntaxError: Import declarations can only be used on the top level and before any other declaration, top level statement or directive. */ diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/package_neg/flag_package.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/package_neg/flag_package.ets new file mode 100644 index 0000000000..ae374bb21f --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/package_neg/flag_package.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. + */ + +package usestaticpackage2; + +"use static" + +/* @@? 18:1 Error SyntaxError: Invalid package toplevel statement */ diff --git a/ets2panda/test/ast/compiler/ets/use_static_flag/package_neg/flag_package2.ets b/ets2panda/test/ast/compiler/ets/use_static_flag/package_neg/flag_package2.ets new file mode 100644 index 0000000000..551145bbe7 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/use_static_flag/package_neg/flag_package2.ets @@ -0,0 +1,19 @@ +"use static" +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usestaticpackage2; + +/* @@? flag_package.ets:18:1 Error SyntaxError: Invalid package toplevel statement */ diff --git a/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt b/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt index 93f5508e79..0f60c8fe11 100644 --- a/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt +++ b/ets2panda/test/test-lists/srcdumper/srcdumper-ets-ignored.txt @@ -178,6 +178,8 @@ ast/compiler/ets/namespace_tests/namespace.ets ast/compiler/ets/namespace_tests/namespace_ambient_export01.ets ast/compiler/ets/namespace_tests/namespace_ambient_export02.ets ast/compiler/ets/namespace_tests/namespace_ambient_export03.ets +ast/compiler/ets/use_static_flag/flag_after_importdecl.ets +ast/compiler/ets/use_static_flag/flag_before_importdecl.ets runtime/ets/namespace_tests/namespace_import_type_test/namespace_import.ets runtime/ets/namespace_tests/namespace_initializer.ets runtime/ets/interface_with_optional_property_cycle_import/class_file.ets -- Gitee From fb82a98a87a92d490cea157ea8de0c2ccba5f097 Mon Sep 17 00:00:00 2001 From: Maxim Bolshov Date: Wed, 2 Jul 2025 15:54:04 +0300 Subject: [PATCH 099/145] Minor utils/plugin refactoring * Add missing assert * Add missing static_cast Issue: #ICJK24 Testing: ninja ets_tests Signed-off-by: Maxim Bolshov --- ets2panda/compiler/lowering/util.cpp | 1 + ets2panda/public/es2panda_lib.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ets2panda/compiler/lowering/util.cpp b/ets2panda/compiler/lowering/util.cpp index 70277eeeac..397eb4ad56 100644 --- a/ets2panda/compiler/lowering/util.cpp +++ b/ets2panda/compiler/lowering/util.cpp @@ -57,6 +57,7 @@ util::UString GenName(ArenaAllocator *const allocator) void SetSourceRangesRecursively(ir::AstNode *node, const lexer::SourceRange &range) { + ES2PANDA_ASSERT(node != nullptr); node->SetRange(range); node->IterateRecursively([](ir::AstNode *n) { n->SetRange(n->Parent()->Range()); }); } diff --git a/ets2panda/public/es2panda_lib.cpp b/ets2panda/public/es2panda_lib.cpp index 1a0d1f9d2c..7d1405550e 100644 --- a/ets2panda/public/es2panda_lib.cpp +++ b/ets2panda/public/es2panda_lib.cpp @@ -130,7 +130,7 @@ __attribute__((unused)) es2panda_variantDoubleCharArrayBool EnumMemberResultToEs // NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic, readability-simplify-subscript-expr) es2panda_variantDoubleCharArrayBool es2panda_variant; - es2panda_variant.index = variant.index(); + es2panda_variant.index = static_cast(variant.index()); switch (es2panda_variant.index) { case es2panda_variantIndex::CAPI_DOUBLE: es2panda_variant.variant.d = std::get(variant); -- Gitee From 28cba89b19985557d2adc016bebb2075719927c4 Mon Sep 17 00:00:00 2001 From: xuxinjie4 Date: Sun, 6 Jul 2025 17:46:03 +0800 Subject: [PATCH 100/145] fix crash when redefine array Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKACL?from=project-issue Signed-off-by: xuxinjie4 --- ets2panda/checker/ets/object.cpp | 6 +++++ .../ets/redefine_class/redefine_array.ets | 26 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/redefine_class/redefine_array.ets diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index e2d4232f15..07e925f8ad 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -1203,6 +1203,12 @@ void ETSChecker::CheckClassDefinition(ir::ClassDefinition *classDef) classType->SuperType()->GetDeclNode()->Check(this); } + if (classType->GetDeclNode() != classDef) { + ES2PANDA_ASSERT(IsAnyError()); + classDef->SetTsType(GlobalTypeError()); + return; + } + auto newStatus = checker::CheckerStatus::IN_CLASS; if (Context().ContainingClass() != classType) { classType->SetEnclosingType(Context().ContainingClass()); diff --git a/ets2panda/test/ast/compiler/ets/redefine_class/redefine_array.ets b/ets2panda/test/ast/compiler/ets/redefine_class/redefine_array.ets new file mode 100644 index 0000000000..ec66c92c5e --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/redefine_class/redefine_array.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. + */ + +package escompat; + +class ArrayKeysIterator { + private a: Array +} + +export class Array { + a: T +} + +/* @@? 1:3 Error TypeError: Class 'Array' is already defined. */ \ No newline at end of file -- Gitee From f0ea44806b0e78e795c9b6f39d90934b9afff6cd Mon Sep 17 00:00:00 2001 From: Maxim Bolshov Date: Wed, 2 Jul 2025 15:54:04 +0300 Subject: [PATCH 101/145] Minor utils/plugin refactoring * Add missing assert * Add missing static_cast Issue: #ICJK24 Testing: ninja ets_tests Signed-off-by: Maxim Bolshov --- ets2panda/compiler/lowering/util.cpp | 1 + ets2panda/public/es2panda_lib.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ets2panda/compiler/lowering/util.cpp b/ets2panda/compiler/lowering/util.cpp index 70277eeeac..397eb4ad56 100644 --- a/ets2panda/compiler/lowering/util.cpp +++ b/ets2panda/compiler/lowering/util.cpp @@ -57,6 +57,7 @@ util::UString GenName(ArenaAllocator *const allocator) void SetSourceRangesRecursively(ir::AstNode *node, const lexer::SourceRange &range) { + ES2PANDA_ASSERT(node != nullptr); node->SetRange(range); node->IterateRecursively([](ir::AstNode *n) { n->SetRange(n->Parent()->Range()); }); } diff --git a/ets2panda/public/es2panda_lib.cpp b/ets2panda/public/es2panda_lib.cpp index 1a0d1f9d2c..7d1405550e 100644 --- a/ets2panda/public/es2panda_lib.cpp +++ b/ets2panda/public/es2panda_lib.cpp @@ -130,7 +130,7 @@ __attribute__((unused)) es2panda_variantDoubleCharArrayBool EnumMemberResultToEs // NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic, readability-simplify-subscript-expr) es2panda_variantDoubleCharArrayBool es2panda_variant; - es2panda_variant.index = variant.index(); + es2panda_variant.index = static_cast(variant.index()); switch (es2panda_variant.index) { case es2panda_variantIndex::CAPI_DOUBLE: es2panda_variant.variant.d = std::get(variant); -- Gitee From c3683df9f388d945ba3ca028d7ae2aec10abb236 Mon Sep 17 00:00:00 2001 From: daizihan Date: Mon, 7 Jul 2025 21:46:15 +0800 Subject: [PATCH 102/145] Fix fuzz crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKLXR?from=project-issue Signed-off-by: daizihan --- ets2panda/checker/ets/utilityTypeHandlers.cpp | 3 +++ .../test/ast/compiler/ets/fuzzingtest6.ets | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/fuzzingtest6.ets diff --git a/ets2panda/checker/ets/utilityTypeHandlers.cpp b/ets2panda/checker/ets/utilityTypeHandlers.cpp index 227461a466..a939553b74 100644 --- a/ets2panda/checker/ets/utilityTypeHandlers.cpp +++ b/ets2panda/checker/ets/utilityTypeHandlers.cpp @@ -875,6 +875,9 @@ Type *ETSChecker::CreatePartialTypeClassDef(ir::ClassDefinition *const partialCl LogError(diagnostic::CYCLIC_CLASS_SUPER_TYPE, {}, classDef->Start()); return partialType; } + if (partialSuper->IsTypeError()) { + return partialType; + } partialType->SetSuperType(partialSuper->AsETSObjectType()); } diff --git a/ets2panda/test/ast/compiler/ets/fuzzingtest6.ets b/ets2panda/test/ast/compiler/ets/fuzzingtest6.ets new file mode 100644 index 0000000000..79c7af6977 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzzingtest6.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 inter { } + +class B extends A implements inter { +} + +function foo1(b: Partial>) { +} + +/* @@? 18:20 Error TypeError: Cannot find type 'A'. */ +/* @@? 18:20 Error TypeError: The super type of 'B' class is not extensible. */ -- Gitee From 4efcc921a9aa66a93c3310faadebad37740a36d7 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Tue, 8 Jul 2025 20:09:32 +0800 Subject: [PATCH 103/145] Fix crash caused by invalid switch code Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKVRI Description: The modification method is to ensure that ParseTryStatement does not return nullptr in case of an exception, but instead returns AlloBrokenStatement. Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/parser/ETSparserStatements.cpp | 2 +- .../test/ast/parser/ets/switch_invalid.ets | 67 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/parser/ets/switch_invalid.ets diff --git a/ets2panda/parser/ETSparserStatements.cpp b/ets2panda/parser/ETSparserStatements.cpp index 065a0a5966..c6e55ee4a8 100644 --- a/ets2panda/parser/ETSparserStatements.cpp +++ b/ets2panda/parser/ETSparserStatements.cpp @@ -332,7 +332,7 @@ ir::Statement *ETSParser::ParseTryStatement() if (catchClauses.empty() && finalizer == nullptr) { LogError(diagnostic::MISSING_CATCH_OR_FINALLY_AFTER_TRY, {}, startLoc); - return nullptr; + return AllocBrokenStatement(startLoc); } lexer::SourcePosition endLoc = finalizer != nullptr ? finalizer->End() : catchClauses.back()->End(); diff --git a/ets2panda/test/ast/parser/ets/switch_invalid.ets b/ets2panda/test/ast/parser/ets/switch_invalid.ets new file mode 100644 index 0000000000..7c72bea595 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/switch_invalid.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. + */ + +switch:[11](q): [12]{: [13]case: [14]1:: [15]{: [16]q: [17] +=: [18]2;: +[38]try: [39]{: [40]s: [41] +=: [42]"cba";: [43]q: [44] +=: [45]5;: [46]throw: [98] + +/* @@? 16:7 Error SyntaxError: Unexpected token ':'. */ +/* @@? 16:7 Error SyntaxError: Expected '(', got ':'. */ +/* @@? 16:7 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 16:7 Error TypeError: Incompatible types. Found: *ERROR_TYPE*, required: char , byte , short , int, long , Char , Byte , Short , Int, Long , String or an enum type */ +/* @@? 16:15 Error SyntaxError: Expected '{', got ':'. */ +/* @@? 16:15 Error SyntaxError: Expected ')', got ':'. */ +/* @@? 16:15 Error SyntaxError: Unexpected token ':', expected 'case' or 'default'. */ +/* @@? 16:21 Error SyntaxError: Unexpected token '{'. */ +/* @@? 16:22 Error SyntaxError: Unexpected token ':'. */ +/* @@? 16:22 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 16:28 Error SyntaxError: Unexpected token 'case'. */ +/* @@? 16:32 Error SyntaxError: Unexpected token ':'. */ +/* @@? 16:32 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 16:38 Error SyntaxError: Unexpected token '1'. */ +/* @@? 16:39 Error SyntaxError: Unexpected token ':'. */ +/* @@? 16:40 Error SyntaxError: Unexpected token ':'. */ +/* @@? 16:40 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 16:46 Error SyntaxError: Unexpected token '{'. */ +/* @@? 16:47 Error SyntaxError: Unexpected token ':'. */ +/* @@? 16:47 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 16:53 Error SyntaxError: Unexpected token 'q'. */ +/* @@? 16:56 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 16:56 Error TypeError: Invalid left-hand side of assignment expression */ +/* @@? 16:61 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 16:63 Error SyntaxError: Unexpected token ':'. */ +/* @@? 16:69 Error SyntaxError: Unexpected token '2'. */ +/* @@? 16:71 Error SyntaxError: Unexpected token ':'. */ +/* @@? 16:71 Error TypeError: Indexed access is not supported for such expression type. */ +/* @@? 17:5 Error SyntaxError: Unexpected token 'try'. */ +/* @@? 17:5 Error SyntaxError: A try statement should contain either finally clause or at least one catch clause. */ +/* @@? 17:8 Error SyntaxError: Expected '{', got ':'. */ +/* @@? 17:8 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:14 Error SyntaxError: Unexpected token '{'. */ +/* @@? 17:15 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:21 Error SyntaxError: Unexpected token 's'. */ +/* @@? 17:24 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 17:29 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 17:31 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:37 Error SyntaxError: Unexpected token 'cba'. */ +/* @@? 17:43 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:49 Error SyntaxError: Unexpected token 'q'. */ +/* @@? 17:52 Error SyntaxError: Label must be followed by a loop statement. */ +/* @@? 17:57 Error SyntaxError: Invalid left-hand side in assignment expression. */ +/* @@? 17:59 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:65 Error SyntaxError: Unexpected token '5'. */ +/* @@? 17:67 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:73 Error SyntaxError: Unexpected token 'throw'. */ +/* @@? 17:78 Error SyntaxError: Unexpected token ':'. */ +/* @@? 68:1 Error SyntaxError: Expected '}', got 'end of stream'. */ -- Gitee From 1501e679091f7802d30593ba437291f5d95572a3 Mon Sep 17 00:00:00 2001 From: oh-rgx Date: Tue, 8 Jul 2025 20:50:45 +0800 Subject: [PATCH 104/145] Fix parser crash Issue: #ICKW2V Signed-off-by: oh-rgx --- ets2panda/parser/ETSFormattedParser.cpp | 2 +- .../test/ast/compiler/ets/parser_format.ets | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/parser_format.ets diff --git a/ets2panda/parser/ETSFormattedParser.cpp b/ets2panda/parser/ETSFormattedParser.cpp index 4be9f1d50c..4043796c13 100644 --- a/ets2panda/parser/ETSFormattedParser.cpp +++ b/ets2panda/parser/ETSFormattedParser.cpp @@ -161,7 +161,7 @@ ir::Statement *ETSParser::ParseStatementFormatPlaceholder() { if (insertingNodes_.empty()) { LogError(diagnostic::INSERT_NODE_ABSENT, {}, Lexer()->GetToken().Start()); - ES2PANDA_UNREACHABLE(); + return AllocBrokenStatement(Lexer()->GetToken().Start()); } ParserImpl::NodeFormatType nodeFormat = GetFormatPlaceholderType(); diff --git a/ets2panda/test/ast/compiler/ets/parser_format.ets b/ets2panda/test/ast/compiler/ets/parser_format.ets new file mode 100644 index 0000000000..a468621ea1 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/parser_format.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. + */ + +declaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaare struct MainProg2 { + @@Stave +} + +/* @@? 16:1 Error TypeError: Cannot find type 'declaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaare'. */ +/* @@? 16:1 Error TypeError: Class literal is not yet supported. */ +/* @@? 16:46 Error SyntaxError: Unexpected token 'MainProg2'. */ +/* @@? 16:46 Error TypeError: Unresolved reference MainProg2 */ +/* @@? 16:56 Error SyntaxError: Unexpected token '{'. */ +/* @@? 17:5 Error SyntaxError: There is no any node to insert at the placeholder position. */ +/* @@? 17:7 Error TypeError: Unresolved reference Stave */ -- Gitee From 867ecd7e803759a1737bf9520d08c62df0f16df5 Mon Sep 17 00:00:00 2001 From: gcw_HJ4zMsdn Date: Tue, 8 Jul 2025 12:11:12 +0800 Subject: [PATCH 105/145] 0603-fix-alert Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKQW6 Signed-off-by: yp9522 --- ets2panda/checker/ETSAnalyzerHelpers.cpp | 1 + ets2panda/checker/TSAnalyzer.cpp | 11 ++- ets2panda/checker/ets/aliveAnalyzer.cpp | 1 + ets2panda/checker/ets/assignAnalyzer.cpp | 1 + ets2panda/checker/ets/dynamic.cpp | 1 + ets2panda/checker/ets/etsWarningAnalyzer.cpp | 7 +- ets2panda/checker/ets/function.cpp | 9 +- ets2panda/checker/ets/helpers.cpp | 22 +++-- ets2panda/checker/ets/object.cpp | 20 ++-- ets2panda/checker/ets/typeCheckingHelpers.cpp | 7 +- ets2panda/checker/ets/typeCreation.cpp | 2 + ets2panda/checker/ets/typeRelationContext.h | 2 + ets2panda/checker/ets/utilityTypeHandlers.cpp | 16 ++- ets2panda/checker/ts/destructuringContext.cpp | 4 +- ets2panda/checker/ts/function.cpp | 10 +- ets2panda/checker/ts/object.cpp | 2 + .../checker/types/ets/etsFunctionType.cpp | 4 +- ets2panda/checker/types/ets/etsObjectType.cpp | 1 + ets2panda/checker/types/signature.cpp | 3 +- .../checker/types/ts/objectDescriptor.cpp | 2 +- ets2panda/parser/ASparser.cpp | 4 + ets2panda/parser/ETSparser.cpp | 5 +- ets2panda/parser/ETSparserAnnotations.cpp | 2 + ets2panda/parser/ETSparserClasses.cpp | 3 + ets2panda/parser/ETSparserExpressions.cpp | 2 + ets2panda/parser/TSparser.cpp | 3 +- ets2panda/parser/TypedParser.cpp | 4 +- .../parser/context/classPrivateContext.cpp | 4 +- ets2panda/parser/expressionParser.cpp | 97 ++++++++++--------- ets2panda/parser/expressionTSParser.cpp | 12 ++- ets2panda/parser/parserImpl.cpp | 30 +++--- ets2panda/parser/program/program.cpp | 2 +- ets2panda/parser/statementParser.cpp | 84 ++++++++-------- ets2panda/parser/statementTSParser.cpp | 12 +-- 34 files changed, 236 insertions(+), 154 deletions(-) diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index 8b864b8652..9ebb333d7b 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -676,6 +676,7 @@ void InferReturnType(ETSChecker *checker, ir::ScriptFunction *containingFunc, ch // First (or single) return statement in the function: funcReturnType = stArgument == nullptr ? checker->GlobalVoidType() : checker->GetNonConstantType(stArgument->Check(checker)); + ES2PANDA_ASSERT(funcReturnType != nullptr); if (funcReturnType->IsTypeError()) { containingFunc->Signature()->RemoveSignatureFlag(checker::SignatureFlags::NEED_RETURN_TYPE); return; diff --git a/ets2panda/checker/TSAnalyzer.cpp b/ets2panda/checker/TSAnalyzer.cpp index c353155e2c..44d5a3d824 100644 --- a/ets2panda/checker/TSAnalyzer.cpp +++ b/ets2panda/checker/TSAnalyzer.cpp @@ -74,6 +74,7 @@ checker::Type *TSAnalyzer::Check(ir::TSIndexSignature *node) const checker::ObjectDescriptor *desc = checker->Allocator()->New(checker->Allocator()); checker::ObjectType *placeholder = checker->Allocator()->New(desc); + ES2PANDA_ASSERT(placeholder != nullptr); if (node->Kind() == ir::TSIndexSignature::TSIndexSignatureKind::NUMBER) { placeholder->Desc()->numberIndexInfo = info; } else { @@ -281,12 +282,13 @@ checker::Type *TSAnalyzer::Check(ir::ArrayExpression *expr) const util::StringView memberIndex = util::Helpers::ToStringView(checker->Allocator(), index); varbinder::LocalVariable *tupleMember = varbinder::Scope::CreateVar( checker->Allocator(), memberIndex, varbinder::VariableFlags::PROPERTY, nullptr); - + ES2PANDA_ASSERT(tupleMember != nullptr); if (inConstContext) { tupleMember->AddFlag(varbinder::VariableFlags::READONLY); } tupleMember->SetTsType(*it); + ES2PANDA_ASSERT(desc != nullptr); desc->properties.push_back(tupleMember); } @@ -327,7 +329,7 @@ checker::Type *TSAnalyzer::Check(ir::ArrowFunctionExpression *expr) const if (funcVar != nullptr && funcVar->TsType() == nullptr) { funcVar->SetTsType(funcType); } - + ES2PANDA_ASSERT(signature != nullptr); signature->SetReturnType(checker->HandleFunctionReturn(expr->Function())); if (!expr->Function()->Body()->IsExpression()) { @@ -570,7 +572,7 @@ checker::Type *TSAnalyzer::Check(ir::FunctionExpression *expr) const if (funcVar != nullptr && funcVar->TsType() == nullptr) { funcVar->SetTsType(funcType); } - + ES2PANDA_ASSERT(signature != nullptr); signature->SetReturnType(checker->HandleFunctionReturn(expr->Function())); expr->Function()->Body()->Check(checker); @@ -878,6 +880,7 @@ checker::Type *TSAnalyzer::Check(ir::ObjectExpression *expr) const } checker::Type *returnType = checker->Allocator()->New(desc); + ES2PANDA_ASSERT(returnType != nullptr); returnType->AsObjectType()->AddObjectFlag(checker::ObjectFlags::RESOLVED_MEMBERS | checker::ObjectFlags::CHECK_EXCESS_PROPS); return returnType; @@ -1850,6 +1853,7 @@ checker::Type *TSAnalyzer::Check(ir::TSEnumDeclaration *st) const if (enumVar->TsType() == nullptr) { checker::ScopeContext scopeCtx(checker, st->Scope()); checker::Type *enumType = InferType(checker, st->IsConst(), st); + ES2PANDA_ASSERT(enumType != nullptr); enumType->SetVariable(enumVar); enumVar->SetTsType(enumType); } @@ -1957,6 +1961,7 @@ checker::Type *TSAnalyzer::Check(ir::TSInterfaceDeclaration *st) const checker->Allocator()->New(checker->Allocator()); resolvedType = checker->Allocator()->New(checker->Allocator(), st->Id()->Name(), desc); + ES2PANDA_ASSERT(resolvedType != nullptr); resolvedType->SetVariable(var); var->SetTsType(resolvedType); } diff --git a/ets2panda/checker/ets/aliveAnalyzer.cpp b/ets2panda/checker/ets/aliveAnalyzer.cpp index 495ee5bae3..05107c571e 100644 --- a/ets2panda/checker/ets/aliveAnalyzer.cpp +++ b/ets2panda/checker/ets/aliveAnalyzer.cpp @@ -255,6 +255,7 @@ void AliveAnalyzer::AnalyzeMethodDef(const ir::MethodDefinition *methodDef) } if (status_ == LivenessStatus::ALIVE && !isVoid && !isPromiseVoid) { + ES2PANDA_ASSERT(methodDef->Function() != nullptr); if (!methodDef->Function()->HasReturnStatement()) { if (!util::Helpers::IsAsyncMethod(methodDef)) { checker_->LogError(diagnostic::MISSING_RETURN_STMT, {}, func->Start()); diff --git a/ets2panda/checker/ets/assignAnalyzer.cpp b/ets2panda/checker/ets/assignAnalyzer.cpp index 358a10a992..1966a95bfb 100644 --- a/ets2panda/checker/ets/assignAnalyzer.cpp +++ b/ets2panda/checker/ets/assignAnalyzer.cpp @@ -532,6 +532,7 @@ static bool IsInitialConstructor(const ir::AstNode *node) } const auto methodDef = node->AsMethodDefinition(); + ES2PANDA_ASSERT(methodDef != nullptr); if (methodDef->Function()->Body() == nullptr || methodDef->Function()->IsExternal()) { return false; } diff --git a/ets2panda/checker/ets/dynamic.cpp b/ets2panda/checker/ets/dynamic.cpp index 3f907d3796..ec5e5a3dc8 100644 --- a/ets2panda/checker/ets/dynamic.cpp +++ b/ets2panda/checker/ets/dynamic.cpp @@ -65,6 +65,7 @@ void ProcessCheckerNode(ETSChecker *checker, ir::AstNode *node) // however right now checker do it when called on ClassDefinition auto method = node->AsMethodDefinition(); auto func = method->Value()->AsFunctionExpression()->Function(); + ES2PANDA_ASSERT(method->Id() != nullptr); func->Id()->SetVariable(method->Id()->Variable()); } ScopeContext checkerScope(checker, scope); diff --git a/ets2panda/checker/ets/etsWarningAnalyzer.cpp b/ets2panda/checker/ets/etsWarningAnalyzer.cpp index 239398f27f..8320d38cbc 100644 --- a/ets2panda/checker/ets/etsWarningAnalyzer.cpp +++ b/ets2panda/checker/ets/etsWarningAnalyzer.cpp @@ -103,8 +103,9 @@ void ETSWarningAnalyzer::AnalyzeClassMethodForFinalModifier(const ir::MethodDefi if (!potentialDescendant->IsDescendantOf(classAsETSObject)) { continue; } - const util::StringView bodyMethodName = - ETSChecker::GetSignatureFromMethodDefinition(bodyPart->AsMethodDefinition())->Function()->Id()->Name(); + auto signature = ETSChecker::GetSignatureFromMethodDefinition(bodyPart->AsMethodDefinition()); + ES2PANDA_ASSERT(signature != nullptr); + const util::StringView bodyMethodName = signature->Function()->Id()->Name(); const auto *func = methodDef->Function(); ES2PANDA_ASSERT(func != nullptr); if (bodyPart->IsOverride() && bodyMethodName != compiler::Signatures::CTOR && @@ -212,7 +213,7 @@ void ETSWarningAnalyzer::ETSWarningsProhibitTopLevelStatements(const ir::AstNode } for (const auto *itBody : classDef->Body()) { - if (!itBody->IsMethodDefinition() || + if (!itBody->IsMethodDefinition() || itBody->AsMethodDefinition()->Id() == nullptr || itBody->AsMethodDefinition()->Id()->Name() != compiler::Signatures::INIT_METHOD) { continue; } diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 616c098cd5..6736d65441 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -959,6 +959,7 @@ void ETSChecker::CollectSuitableSignaturesForTypeInference( for (auto *sig : signatures) { auto *sigParamType = GetNonNullishType(sig->Params().at(paramIdx)->TsType()); + ES2PANDA_ASSERT(sigParamType != nullptr); if (!sigParamType->IsETSFunctionType()) { continue; } @@ -1236,7 +1237,8 @@ static bool CollectOverload(checker::ETSChecker *checker, ir::MethodDefinition * for (ir::MethodDefinition *const currentFunc : method->Overloads()) { ldInfo.isDeclare &= currentFunc->IsDeclare(); - + ES2PANDA_ASSERT(currentFunc->Function() != nullptr); + ES2PANDA_ASSERT(currentFunc->Id() != nullptr); currentFunc->Function()->Id()->SetVariable(currentFunc->Id()->Variable()); checker->BuildFunctionSignature(currentFunc->Function(), method->IsConstructor()); if (currentFunc->Function()->Signature() == nullptr) { @@ -1284,6 +1286,7 @@ checker::Type *ETSChecker::BuildMethodSignature(ir::MethodDefinition *method) } auto *methodId = method->Id(); ES2PANDA_ASSERT(methodId != nullptr); + ES2PANDA_ASSERT(method->Function() != nullptr); method->Function()->Id()->SetVariable(methodId->Variable()); BuildFunctionSignature(method->Function(), method->IsConstructor()); if (method->Function()->Signature() == nullptr) { @@ -1794,6 +1797,7 @@ bool ETSChecker::CheckOverride(Signature *signature, ETSObjectType *site) void ETSChecker::CheckOverride(Signature *signature) { + ES2PANDA_ASSERT(signature != nullptr); auto *owner = signature->Owner(); ES2PANDA_ASSERT(owner != nullptr); bool isOverriding = false; @@ -2043,6 +2047,7 @@ ir::MethodDefinition *ETSChecker::CreateMethod(const util::StringView &name, ir: // CC-OFFNXT(G.FMT.05-CPP) project codestyle clang format off body, ir::FunctionSignature(nullptr, std::move(params), returnType), flags, modifiers}); // clang-format on + ES2PANDA_ASSERT(func != nullptr); func->SetScope(scope); func->SetIdent(nameId); if (body != nullptr && body->IsBlockStatement()) { @@ -2227,10 +2232,12 @@ ArenaVector ETSChecker::ExtendArgumentsWithFakeLamda(ir::CallE ProgramAllocator(), ir::ScriptFunction::ScriptFunctionData {body, ir::FunctionSignature(nullptr, std::move(params), nullptr), ir::ScriptFunctionFlags::ARROW}); + ES2PANDA_ASSERT(funcNode != nullptr); funcNode->SetScope(funcScope); funcScope->BindNode(funcNode); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *arrowFuncNode = ProgramAllocNode(funcNode, ProgramAllocator()); + ES2PANDA_ASSERT(arrowFuncNode != nullptr); arrowFuncNode->SetParent(callExpr); ArenaVector fakeArguments = callExpr->Arguments(); diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index 2fc82244b4..35eb70cc91 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -2039,6 +2039,7 @@ Type *ETSChecker::CheckSwitchDiscriminant(ir::Expression *discriminant) { discriminant->Check(this); auto *discriminantType = GetNonConstantType(MaybeUnboxExpression(discriminant)); + ES2PANDA_ASSERT(discriminantType != nullptr); if (!discriminantType->HasTypeFlag(TypeFlag::VALID_SWITCH_TYPE)) { if (!(discriminantType->IsETSObjectType() && discriminantType->AsETSObjectType()->HasObjectFlag( @@ -2421,7 +2422,9 @@ util::StringView ETSChecker::GetHashFromFunctionType(ir::ETSFunctionType *type) std::stringstream ss; for (auto *p : type->Params()) { auto *const param = p->AsETSParameterExpression(); - param->TypeAnnotation()->GetType(this)->ToString(ss, true); + auto *paramType = param->TypeAnnotation()->GetType(this); + ES2PANDA_ASSERT(paramType != nullptr); + paramType->ToString(ss, true); ss << ";"; } @@ -2435,7 +2438,9 @@ util::StringView ETSChecker::GetHashFromFunctionType(ir::ETSFunctionType *type) } ss << "extensionFunction;"; } else { - type->ReturnType()->GetType(this)->ToString(ss, true); + auto *returnType = type->ReturnType()->GetType(this); + ES2PANDA_ASSERT(returnType != nullptr); + returnType->ToString(ss, true); } ss << ";"; @@ -2829,6 +2834,7 @@ ir::MethodDefinition *ETSChecker::GenerateDefaultGetterSetter(ir::ClassProperty auto *methodIdent = property->Key()->AsIdentifier()->Clone(checker->ProgramAllocator(), nullptr); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *funcExpr = checker->ProgramAllocNode(func); + CHECK_NOT_NULL(funcExpr); funcExpr->SetRange(func->Range()); func->AddFlag(ir::ScriptFunctionFlags::METHOD); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) @@ -2838,17 +2844,20 @@ ir::MethodDefinition *ETSChecker::GenerateDefaultGetterSetter(ir::ClassProperty auto *decl = checker->ProgramAllocator()->New( checker->ProgramAllocator(), property->Key()->AsIdentifier()->Name(), method); auto *var = checker->ProgramAllocator()->New(decl, varbinder::VariableFlags::VAR); + CHECK_NOT_NULL(var); var->AddFlag(varbinder::VariableFlags::METHOD); methodIdent->SetVariable(var); - method->Id()->SetMutator(); - method->SetRange(field->Range()); auto *methodId = method->Id(); CHECK_NOT_NULL(methodId); + methodId->SetMutator(); + method->SetRange(field->Range()); + auto *methodFunc = method->Function(); + CHECK_NOT_NULL(methodFunc); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) - method->Function()->SetIdent(methodId->Clone(checker->ProgramAllocator(), nullptr)); - method->Function()->AddModifier(method->Modifiers()); + methodFunc->SetIdent(methodId->Clone(checker->ProgramAllocator(), nullptr)); + methodFunc->AddModifier(method->Modifiers()); method->SetVariable(var); method->SetParent(field->Parent()); @@ -3110,6 +3119,7 @@ Type *ETSChecker::GetImportSpecifierObjectType(ir::ETSImportDeclaration *importD ETSChecker::NamedAccessMeta ETSChecker::FormNamedAccessMetadata(varbinder::Variable const *prop) { + CHECK_NOT_NULL(prop); const auto *field = prop->Declaration()->Node()->AsClassProperty(); const auto *owner = field->Parent()->AsClassDefinition(); auto *fieldId = field->Id(); diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index 6382f115a3..21c384f139 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -582,7 +582,7 @@ static void ResolveDeclaredMethodsOfObject(ETSChecker *checker, const ETSObjectT auto *method = it->Declaration()->Node()->AsMethodDefinition(); auto *function = method->Function(); - + ES2PANDA_ASSERT(function != nullptr); if (function->IsProxy()) { continue; } @@ -736,8 +736,10 @@ void ETSChecker::CreateFunctionTypesFromAbstracts(const std::vector void ETSChecker::ComputeAbstractsFromInterface(ETSObjectType *interfaceType) { - auto cached = GetCachedComputedAbstracts()->find(interfaceType); - if (cached != GetCachedComputedAbstracts()->end()) { + auto cachedComputedAbstracts = GetCachedComputedAbstracts(); + ES2PANDA_ASSERT(cachedComputedAbstracts != nullptr); + auto cached = cachedComputedAbstracts->find(interfaceType); + if (cached != cachedComputedAbstracts->end()) { return; } @@ -750,8 +752,8 @@ void ETSChecker::ComputeAbstractsFromInterface(ETSObjectType *interfaceType) ArenaUnorderedSet abstractInheritanceTarget(ProgramAllocator()->Adapter()); for (auto *interface : interfaceType->Interfaces()) { - auto found = GetCachedComputedAbstracts()->find(interface); - ES2PANDA_ASSERT(found != GetCachedComputedAbstracts()->end()); + auto found = cachedComputedAbstracts->find(interface); + ES2PANDA_ASSERT(found != cachedComputedAbstracts->end()); if (!abstractInheritanceTarget.insert(found->first).second) { continue; @@ -764,7 +766,7 @@ void ETSChecker::ComputeAbstractsFromInterface(ETSObjectType *interfaceType) } } - GetCachedComputedAbstracts()->insert({interfaceType, {merged, abstractInheritanceTarget}}); + cachedComputedAbstracts->insert({interfaceType, {merged, abstractInheritanceTarget}}); } ArenaVector &ETSChecker::GetAbstractsForClass(ETSObjectType *classType) @@ -2268,9 +2270,9 @@ void ETSChecker::WarnForEndlessLoopInGetterSetter(const ir::MemberExpression *co } auto ident = memberExpr->Property()->AsIdentifier(); auto parent = memberExpr->Parent(); - while (parent != nullptr && - (!parent->IsMethodDefinition() || (!parent->AsMethodDefinition()->Function()->IsGetter() && - !parent->AsMethodDefinition()->Function()->IsSetter()))) { + while (parent != nullptr && (!parent->IsMethodDefinition() || parent->AsMethodDefinition()->Function() == nullptr || + (!parent->AsMethodDefinition()->Function()->IsGetter() && + !parent->AsMethodDefinition()->Function()->IsSetter()))) { parent = parent->Parent(); } if (parent != nullptr && parent->AsMethodDefinition()->Function() != nullptr && diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index 8be27e914d..a898411d0b 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -925,6 +925,7 @@ void ETSChecker::CheckAmbientAnnotation(ir::AnnotationDeclaration *annoImpl, ir: for (auto *prop : annoDecl->Properties()) { auto *field = prop->AsClassProperty(); + ES2PANDA_ASSERT(field->Id() != nullptr); fieldMap[field->Id()->Name()] = field; } @@ -1174,10 +1175,10 @@ void ETSChecker::CheckMultiplePropertiesAnnotation(ir::AnnotationUsage *st, util { for (auto *it : st->Properties()) { auto *param = it->AsClassProperty(); - auto result = fieldMap.find(param->Id()->Name()); + auto *id = param->Id(); + ES2PANDA_ASSERT(id != nullptr); + auto result = fieldMap.find(id->Name()); if (result == fieldMap.end()) { - auto *id = param->Id(); - ES2PANDA_ASSERT(id != nullptr); LogError(diagnostic::ANNOT_PROP_UNDEFINED, {id->Name(), baseName}, param->Start()); continue; } diff --git a/ets2panda/checker/ets/typeCreation.cpp b/ets2panda/checker/ets/typeCreation.cpp index 96fcde8db9..67c37078cd 100644 --- a/ets2panda/checker/ets/typeCreation.cpp +++ b/ets2panda/checker/ets/typeCreation.cpp @@ -253,6 +253,7 @@ Signature *ETSChecker::CreateSignature(SignatureInfo *info, Type *returnType, ir return nullptr; } auto signature = ProgramAllocator()->New(info, returnType, nullptr); + ES2PANDA_ASSERT(signature != nullptr); signature->AddSignatureFlag(ConvertToSignatureFlags(ir::ModifierFlags::NONE, sff)); // synthetic arrow type signature flags auto extraFlags = SignatureFlags::ABSTRACT | SignatureFlags::CALL | SignatureFlags::PUBLIC; @@ -439,6 +440,7 @@ std::tuple ETSChecker::CreateBuiltinArraySign util::UString param(std::to_string(i), ProgramAllocator()); auto *paramVar = varbinder::Scope::CreateVar(ProgramAllocator(), param.View(), varbinder::VariableFlags::NONE, nullptr); + ES2PANDA_ASSERT(paramVar != nullptr); paramVar->SetTsType(GlobalIntType()); info->params.push_back(paramVar); diff --git a/ets2panda/checker/ets/typeRelationContext.h b/ets2panda/checker/ets/typeRelationContext.h index ef6c5017f9..b198336e9f 100644 --- a/ets2panda/checker/ets/typeRelationContext.h +++ b/ets2panda/checker/ets/typeRelationContext.h @@ -34,6 +34,8 @@ public: auto *const etsChecker = relation->GetChecker()->AsETSChecker(); + ES2PANDA_ASSERT(target != nullptr); + ES2PANDA_ASSERT(node != nullptr); if (target->IsETSArrayType() && node->IsArrayExpression()) { assignable_ = ValidateArrayTypeInitializerByElement(relation, node->AsArrayExpression(), target->AsETSArrayType()); diff --git a/ets2panda/checker/ets/utilityTypeHandlers.cpp b/ets2panda/checker/ets/utilityTypeHandlers.cpp index 227461a466..2ec9d1551d 100644 --- a/ets2panda/checker/ets/utilityTypeHandlers.cpp +++ b/ets2panda/checker/ets/utilityTypeHandlers.cpp @@ -232,6 +232,7 @@ ir::ClassProperty *ETSChecker::CreateNullishPropertyFromAccessor(ir::MethodDefin ES2PANDA_ASSERT(id != nullptr); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *ident = id->Clone(ProgramAllocator(), nullptr); + ES2PANDA_ASSERT(accessor->Function() != nullptr); auto modifierFlag = accessor->Function()->IsGetter() && accessor->Overloads().empty() ? ir::ModifierFlags::READONLY : ir::ModifierFlags::NONE; @@ -365,6 +366,7 @@ ir::TSTypeParameterDeclaration *ETSChecker::ProcessTypeParamAndGenSubstitution( CloneNodeIfNotNullptr(classOrInterfaceDefTypeParam->Constraint(), ProgramAllocator()), // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) CloneNodeIfNotNullptr(classOrInterfaceDefTypeParam->DefaultType(), ProgramAllocator()), ProgramAllocator()); + ES2PANDA_ASSERT(newTypeParam != nullptr); newTypeParams->AddParam(newTypeParam); newTypeParam->SetParent(newTypeParams); ES2PANDA_ASSERT(likeSubstitution != nullptr); @@ -404,6 +406,7 @@ ir::TSTypeParameterInstantiation *ETSChecker::CreateNewSuperPartialRefTypeParams typeParamRefPart->Name()->SetParent(typeParamRefPart); // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *typeParamRef = ProgramAllocNode(typeParamRefPart, ProgramAllocator()); + ES2PANDA_ASSERT(typeParamRef != nullptr); typeParamRefPart->SetParent(typeParamRef); typeParamRef->SetParent(superPartialRefTypeParams); @@ -463,7 +466,7 @@ void ETSChecker::CreatePartialClassDeclaration(ir::ClassDefinition *const newCla // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) ProgramAllocNode(std::move(typeParams), classDef->TypeParams()->RequiredParams()); - + ES2PANDA_ASSERT(newTypeParams != nullptr); newClassDefinition->SetTypeParams(newTypeParams); newTypeParams->SetParent(newClassDefinition); } @@ -475,7 +478,8 @@ void ETSChecker::CreatePartialClassDeclaration(ir::ClassDefinition *const newCla // Only handle class properties (members) // Method calls on partial classes will make the class not type safe, so we don't copy any methods if (prop->IsClassProperty()) { - if (prop->AsClassProperty()->Id()->Name().Mutf8().find(compiler::Signatures::PROPERTY, 0) == 0) { + if (prop->AsClassProperty()->Id() == nullptr || + prop->AsClassProperty()->Id()->Name().Mutf8().find(compiler::Signatures::PROPERTY, 0) == 0) { continue; } @@ -489,6 +493,7 @@ void ETSChecker::CreatePartialClassDeclaration(ir::ClassDefinition *const newCla (prop->AsMethodDefinition()->Function()->IsGetter() || prop->AsMethodDefinition()->Function()->IsSetter())) { auto *method = prop->AsMethodDefinition(); + ES2PANDA_ASSERT(method->Id() != nullptr); if (newClassDefinition->Scope()->FindLocal(method->Id()->Name(), varbinder::ResolveBindingOptions::VARIABLES) != nullptr) { continue; @@ -613,6 +618,7 @@ ir::TSInterfaceDeclaration *ETSChecker::CreateInterfaceProto(util::StringView na Language(Language::Id::ETS)}); const auto classCtx = varbinder::LexicalScope(VarBinder()); + ES2PANDA_ASSERT(partialInterface != nullptr); partialInterface->TypeParams()->SetParent(partialInterface); partialInterface->SetScope(classCtx.GetScope()); partialInterface->SetVariable(var); @@ -673,6 +679,7 @@ void ETSChecker::CreatePartialTypeInterfaceMethods(ir::TSInterfaceDeclaration *c } for (auto *overload : method->Overloads()) { + ES2PANDA_ASSERT(overload->Function() != nullptr); if (overload->Function()->IsGetter() || overload->Function()->IsSetter()) { // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) addNullishAccessor(CreateNullishAccessor(overload, partialInterface)); @@ -775,6 +782,7 @@ ir::ClassDefinition *ETSChecker::CreateClassPrototype(util::StringView name, par // Create class name, and declaration variable // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) auto *const classId = ProgramAllocNode(name, ProgramAllocator()); + ES2PANDA_ASSERT(classId != nullptr); const auto [decl, var] = VarBinder()->NewVarDecl(classId->Start(), classId->Name()); classId->SetVariable(var); @@ -784,6 +792,7 @@ ir::ClassDefinition *ETSChecker::CreateClassPrototype(util::StringView name, par // SUPPRESS_CSA_NEXTLINE(alpha.core.AllocatorETSCheckerHint) ProgramAllocNode(ProgramAllocator(), classId, ir::ClassDefinitionModifiers::DECLARATION, ir::ModifierFlags::NONE, Language(Language::Id::ETS)); + ES2PANDA_ASSERT(classDef != nullptr); classDef->SetScope(classCtx.GetScope()); classDef->SetVariable(var); @@ -904,7 +913,7 @@ std::pair ETSChecker::CreateScriptFuncti ir::ScriptFunctionFlags::CONSTRUCTOR | ir::ScriptFunctionFlags::EXPRESSION, ir::ModifierFlags::PUBLIC}); - + ES2PANDA_ASSERT(func != nullptr); func->SetScope(scope); scope->BindNode(func); func->SetIdent(id); @@ -965,6 +974,7 @@ Type *ETSChecker::GetReadonlyType(Type *type) if (type->IsETSArrayType()) { ETSArrayType *const clonedArrayType = ProgramAllocator()->New(type->AsETSArrayType()->ElementType()); + ES2PANDA_ASSERT(clonedArrayType != nullptr); clonedArrayType->AddTypeFlag(TypeFlag::READONLY); return clonedArrayType; } diff --git a/ets2panda/checker/ts/destructuringContext.cpp b/ets2panda/checker/ts/destructuringContext.cpp index db1636c4d1..62212a8fca 100644 --- a/ets2panda/checker/ts/destructuringContext.cpp +++ b/ets2panda/checker/ts/destructuringContext.cpp @@ -154,7 +154,7 @@ void DestructuringContext::HandleAssignmentPattern(ir::AssignmentExpression *ass if (!checker_->HasStatus(CheckerStatus::IN_CONST_CONTEXT)) { defaultType = checker_->GetBaseTypeOfLiteralType(defaultType); } - + ES2PANDA_ASSERT(defaultType != nullptr); if (validateDefault && assignmentPattern->Right()->IsObjectExpression() && assignmentPattern->Left()->IsObjectPattern()) { ValidateObjectLiteralType(defaultType->AsObjectType(), assignmentPattern->Left()->AsObjectPattern()); @@ -560,6 +560,7 @@ Type *ObjectDestructuringContext::CreateObjectTypeForRest(ObjectType *objType) if (!it->HasFlag(varbinder::VariableFlags::INFERRED_IN_PATTERN)) { auto *memberVar = varbinder::Scope::CreateVar(checker_->Allocator(), it->Name(), varbinder::VariableFlags::NONE, nullptr); + ES2PANDA_ASSERT(memberVar != nullptr); memberVar->SetTsType(it->TsType()); memberVar->AddFlag(it->Flags()); ES2PANDA_ASSERT(desc != nullptr); @@ -568,6 +569,7 @@ Type *ObjectDestructuringContext::CreateObjectTypeForRest(ObjectType *objType) } Type *returnType = checker_->Allocator()->New(desc); + ES2PANDA_ASSERT(returnType != nullptr); returnType->AsObjectType()->AddObjectFlag(ObjectFlags::RESOLVED_MEMBERS); return returnType; } diff --git a/ets2panda/checker/ts/function.cpp b/ets2panda/checker/ts/function.cpp index b572291219..7b0634260a 100644 --- a/ets2panda/checker/ts/function.cpp +++ b/ets2panda/checker/ts/function.cpp @@ -149,8 +149,9 @@ Type *TSChecker::CreateParameterTypeForArrayAssignmentPattern(ir::ArrayExpressio return inferredType; } - TupleType *newTuple = - inferredTuple->Instantiate(Allocator(), Relation(), GetGlobalTypesHolder())->AsObjectType()->AsTupleType(); + auto initTuple = inferredTuple->Instantiate(Allocator(), Relation(), GetGlobalTypesHolder()); + ES2PANDA_ASSERT(initTuple != nullptr); + TupleType *newTuple = initTuple->AsObjectType()->AsTupleType(); for (uint32_t index = inferredTuple->FixedLength(); index < arrayPattern->Elements().size(); index++) { util::StringView memberIndex = util::Helpers::ToStringView(Allocator(), index); @@ -392,6 +393,7 @@ std::tuple TSCheck if (cache) { Type *placeholder = Allocator()->New(GlobalAnyType()); + ES2PANDA_ASSERT(placeholder != nullptr); placeholder->SetVariable(std::get<0>(result)); param->SetTsType(placeholder); } @@ -609,14 +611,16 @@ void TSChecker::InferFunctionDeclarationType(const varbinder::FunctionDecl *decl if (descWithOverload->callSignatures.empty()) { Type *funcType = CreateFunctionTypeWithSignature(bodyCallSignature); + ES2PANDA_ASSERT(funcType != nullptr); funcType->SetVariable(funcVar); funcVar->SetTsType(funcType); } - + ES2PANDA_ASSERT(bodyCallSignature != nullptr); bodyCallSignature->SetReturnType(HandleFunctionReturn(bodyDeclaration)); if (!descWithOverload->callSignatures.empty()) { Type *funcType = Allocator()->New(descWithOverload); + ES2PANDA_ASSERT(funcType != nullptr); funcType->SetVariable(funcVar); funcVar->SetTsType(funcType); diff --git a/ets2panda/checker/ts/object.cpp b/ets2panda/checker/ts/object.cpp index bf9d836a98..0c9e3c25c3 100644 --- a/ets2panda/checker/ts/object.cpp +++ b/ets2panda/checker/ts/object.cpp @@ -152,6 +152,7 @@ void TSChecker::ResolveUnionTypeMembers(UnionType *type) } ObjectType *mergedType = Allocator()->New(desc); + ES2PANDA_ASSERT(mergedType != nullptr); mergedType->AddObjectFlag(ObjectFlags::RESOLVED_MEMBERS); type->SetMergedObjectType(mergedType); } @@ -388,6 +389,7 @@ IndexInfo *TSChecker::GetApplicableIndexInfo(Type *type, Type *indexType) Type *TSChecker::GetPropertyTypeForIndexType(Type *type, Type *indexType) { + ES2PANDA_ASSERT(type != nullptr); if (type->IsArrayType()) { return type->AsArrayType()->ElementType(); } diff --git a/ets2panda/checker/types/ets/etsFunctionType.cpp b/ets2panda/checker/types/ets/etsFunctionType.cpp index 23a5f92808..ad1fa74e55 100644 --- a/ets2panda/checker/types/ets/etsFunctionType.cpp +++ b/ets2panda/checker/types/ets/etsFunctionType.cpp @@ -75,7 +75,7 @@ static ETSObjectType *FunctionTypeToFunctionalInterfaceType(ETSChecker *checker, bool isExtensionHack = signature->HasSignatureFlag(SignatureFlags::EXTENSION_FUNCTION); if (signature->RestVar() != nullptr) { - auto *functionN = checker->GlobalBuiltinFunctionType(arity, true)->AsETSObjectType(); + auto *functionN = checker->GlobalBuiltinFunctionType(arity, true); auto *substitution = checker->NewSubstitution(); auto *elementType = !signature->RestVar()->TsType()->IsETSTupleType() ? checker->GetElementTypeOfArray(signature->RestVar()->TsType()) @@ -91,7 +91,7 @@ static ETSObjectType *FunctionTypeToFunctionalInterfaceType(ETSChecker *checker, return nullptr; } - auto *funcIface = checker->GlobalBuiltinFunctionType(arity, false)->AsETSObjectType(); + auto *funcIface = checker->GlobalBuiltinFunctionType(arity, false); auto *substitution = checker->NewSubstitution(); for (size_t i = 0; i < arity; i++) { diff --git a/ets2panda/checker/types/ets/etsObjectType.cpp b/ets2panda/checker/types/ets/etsObjectType.cpp index 556cfe28fb..80ed356e4f 100644 --- a/ets2panda/checker/types/ets/etsObjectType.cpp +++ b/ets2panda/checker/types/ets/etsObjectType.cpp @@ -185,6 +185,7 @@ varbinder::LocalVariable *ETSObjectType::CreateSyntheticVarFromEverySignature(co varbinder::VariableFlags::METHOD); ETSFunctionType *funcType = CreateMethodTypeForProp(name); + ES2PANDA_ASSERT(funcType != nullptr); for (auto &s : signatures) { funcType->AddCallSignature(s); } diff --git a/ets2panda/checker/types/signature.cpp b/ets2panda/checker/types/signature.cpp index 4e5c3c5fe2..0bcb243d17 100644 --- a/ets2panda/checker/types/signature.cpp +++ b/ets2panda/checker/types/signature.cpp @@ -115,7 +115,7 @@ void Signature::ToAssemblerType(std::stringstream &ss) const Signature *Signature::Copy(ArenaAllocator *allocator, TypeRelation *relation, GlobalTypesHolder *globalTypes) { SignatureInfo *copiedInfo = allocator->New(signatureInfo_, allocator); - + ES2PANDA_ASSERT(copiedInfo != nullptr); for (size_t idx = 0U; idx < signatureInfo_->params.size(); ++idx) { auto *const paramType = signatureInfo_->params[idx]->TsType(); if (paramType->HasTypeFlag(TypeFlag::GENERIC) && paramType->IsETSObjectType()) { @@ -302,6 +302,7 @@ Signature *Signature::ToArrowSignature(ETSChecker *checker) auto *retType = checker->MaybeBoxType(returnType_); auto *resultSig = allocator->New(sigInfo, retType); + ES2PANDA_ASSERT(resultSig != nullptr); resultSig->flags_ = flags_; resultSig->SetOwner(Owner()); resultSig->SetOwnerVar(OwnerVar()); diff --git a/ets2panda/checker/types/ts/objectDescriptor.cpp b/ets2panda/checker/types/ts/objectDescriptor.cpp index 6dfe4e610e..ccd7d48a60 100644 --- a/ets2panda/checker/types/ts/objectDescriptor.cpp +++ b/ets2panda/checker/types/ts/objectDescriptor.cpp @@ -38,8 +38,8 @@ void ObjectDescriptor::Copy(ArenaAllocator *allocator, ObjectDescriptor *copiedD // copy by hand for (auto *it : properties) { auto *copiedProp = it->Copy(allocator, it->Declaration()); + ES2PANDA_ASSERT(copiedProp != nullptr); copiedProp->SetTsType(it->TsType()->Instantiate(allocator, relation, globalTypes)); - ES2PANDA_ASSERT(copiedDesc != nullptr); copiedDesc->properties.push_back(copiedProp); } diff --git a/ets2panda/parser/ASparser.cpp b/ets2panda/parser/ASparser.cpp index 9c5f9cb7cc..f2567fef3d 100644 --- a/ets2panda/parser/ASparser.cpp +++ b/ets2panda/parser/ASparser.cpp @@ -578,6 +578,7 @@ ir::TypeNode *ASParser::ParseTypeAnnotationLiteralIdentHelper(ir::TypeNode *type ES2PANDA_ASSERT(typeName != nullptr); typeName->SetRange(Lexer()->GetToken().Loc()); type = AllocNode(typeName, Allocator()); + ES2PANDA_ASSERT(type != nullptr); type->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -656,6 +657,7 @@ ir::TypeNode *ASParser::ParseTypeAnnotationTokens(ir::TypeNode *type, bool throw ES2PANDA_ASSERT(typeName != nullptr); typeName->SetRange(Lexer()->GetToken().Loc()); type = AllocNode(typeName, Allocator()); + ES2PANDA_ASSERT(type != nullptr); type->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); return type; @@ -893,6 +895,7 @@ ArenaVector ASParser::ParseInterfaceExtendsClause() ES2PANDA_ASSERT(extendsName != nullptr); extendsName->SetRange(Lexer()->GetToken().Loc()); auto *extendsClause = AllocNode(extendsName, Allocator()); + ES2PANDA_ASSERT(extendsClause != nullptr); extendsClause->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -1154,6 +1157,7 @@ ArenaVector ASParser::ParseClassImplementClause() } auto *impl = AllocNode(current, implTypeParams); + ES2PANDA_ASSERT(impl != nullptr); impl->SetRange({implementStart, Lexer()->GetToken().End()}); implements.push_back(impl); diff --git a/ets2panda/parser/ETSparser.cpp b/ets2panda/parser/ETSparser.cpp index 6f423f8142..895f7b3749 100644 --- a/ets2panda/parser/ETSparser.cpp +++ b/ets2panda/parser/ETSparser.cpp @@ -277,6 +277,7 @@ void ETSParser::ParseParseListElement(const util::ImportPathManager::ParseInfo & { const auto &importData = parseListElem.importData; auto src = importData.HasSpecifiedDeclPath() ? importData.declPath : importData.resolvedSource; + ES2PANDA_ASSERT(extSrc != nullptr); SourceFile sf {src, extSrc->View().Utf8(), importData.resolvedSource, false, importData.HasSpecifiedDeclPath()}; parser::Program *newProg = ParseSource(sf); ES2PANDA_ASSERT(newProg != nullptr); @@ -1198,6 +1199,7 @@ ir::ETSImportDeclaration *ETSParser::ParseImportPathBuildImport(ArenaVectorGetToken().Type() == lexer::TokenType::LITERAL_STRING); auto pathToResolve = Lexer()->GetToken().Ident(); auto *importPathStringLiteral = AllocNode(pathToResolve); + ES2PANDA_ASSERT(importPathStringLiteral != nullptr); importPathStringLiteral->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); auto importFlags = (GetContext().Status() & parser::ParserStatus::IN_DEFAULT_IMPORTS) != 0U @@ -1530,6 +1532,7 @@ ir::AstNode *ETSParser::ParseImportDefaultSpecifier(ArenaVector * } auto *specifier = AllocNode(imported); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange({imported->Start(), imported->End()}); specifiers->push_back(specifier); @@ -2066,7 +2069,6 @@ ir::TSTypeParameter *ETSParser::ParseTypeParameter([[maybe_unused]] TypeAnnotati auto *typeParam = AllocNode(paramIdent, constraint, defaultType, varianceModifier, Allocator()); - ES2PANDA_ASSERT(typeParam); ES2PANDA_ASSERT(typeParam != nullptr); ApplyAnnotationsToNode(typeParam, std::move(annotations), saveLoc); @@ -2218,6 +2220,7 @@ ir::FunctionDeclaration *ETSParser::ParseAccessorWithReceiver(ir::ModifierFlags func->SetIdent(funcIdentNode); auto *funcDecl = AllocNode(Allocator(), func); + ES2PANDA_ASSERT(funcDecl != nullptr); funcDecl->SetRange(func->Range()); func->AddModifier(modifiers); func->SetStart(startLoc); diff --git a/ets2panda/parser/ETSparserAnnotations.cpp b/ets2panda/parser/ETSparserAnnotations.cpp index f5f9d5c3a9..1194431c69 100644 --- a/ets2panda/parser/ETSparserAnnotations.cpp +++ b/ets2panda/parser/ETSparserAnnotations.cpp @@ -132,6 +132,7 @@ ArenaVector ETSParser::ParseAnnotationProperties(ir::ModifierFlag } auto *fieldName = ExpectIdentifier(); + ES2PANDA_ASSERT(fieldName != nullptr); if (fieldName->IsErrorPlaceHolder()) { // Try to recover from error: simplest strategy: only one step ahead. // Probably we can seek for identifier till the enclosing right brace (staring after the next comma?) @@ -401,6 +402,7 @@ ir::AnnotationUsage *ETSParser::ParseAnnotationUsage() auto *singleParam = AllocNode(singleParamName, initializer, nullptr, ir::ModifierFlags::ANNOTATION_USAGE, Allocator(), false); + ES2PANDA_ASSERT(singleParam != nullptr); singleParam->SetRange( {singleParamName->Start(), initializer != nullptr ? initializer->End() : singleParamName->End()}); properties.push_back(singleParam); diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index a1cbd70d36..57e844e8c2 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -455,6 +455,7 @@ ir::TypeNode *ETSParser::ConvertToOptionalUnionType(ir::TypeNode *typeAnno) types.push_back(AllocNode(Allocator())); types.back()->SetRange(typeAnno->Range()); auto *newTypeAnno = AllocNode(std::move(types), Allocator()); + ES2PANDA_ASSERT(newTypeAnno != nullptr); newTypeAnno->SetRange(typeAnno->Range()); return newTypeAnno; } @@ -564,6 +565,7 @@ ir::MethodDefinition *ETSParser::ParseClassMethodDefinition(ir::Identifier *meth auto *method = AllocNode(methodKind, methodName->Clone(Allocator(), nullptr)->AsExpression(), funcExpr, modifiers, Allocator(), false); + ES2PANDA_ASSERT(method != nullptr); method->SetDefaultAccessModifier(isDefault); method->SetRange(funcExpr->Range()); return method; @@ -1343,6 +1345,7 @@ void ETSParser::CreateImplicitConstructor([[maybe_unused]] ir::MethodDefinition } auto *methodDef = BuildImplicitConstructor(ir::ClassDefinitionModifiers::SET_CTOR_ID, startLoc); + ES2PANDA_ASSERT(methodDef != nullptr); if ((flags & ir::ModifierFlags::DECLARE) != 0) { auto func = methodDef->Function(); ES2PANDA_ASSERT(func != nullptr); diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index f8425e7790..94d864e473 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -52,6 +52,7 @@ ir::Expression *ETSParser::ParseFunctionParameterExpression(ir::AnnotatedExpress auto const lexerPos = Lexer()->Save().Iterator(); Lexer()->NextToken(); // eat '=' + ES2PANDA_ASSERT(paramIdent != nullptr); if (paramIdent->IsRestElement()) { LogError(diagnostic::NO_DEFAULT_FOR_REST); } @@ -677,6 +678,7 @@ ir::Expression *ETSParser::ParseNewExpression() ParseArgumentsNewExpression(arguments, typeReference); auto *newExprNode = AllocNode(typeReference, std::move(arguments)); + ES2PANDA_ASSERT(newExprNode != nullptr); newExprNode->SetRange({start, Lexer()->GetToken().End()}); return newExprNode; diff --git a/ets2panda/parser/TSparser.cpp b/ets2panda/parser/TSparser.cpp index 402df097d4..d2545ce425 100644 --- a/ets2panda/parser/TSparser.cpp +++ b/ets2panda/parser/TSparser.cpp @@ -528,7 +528,7 @@ ir::TypeNode *TSParser::ParseTypeOperatorOrTypeReference() ir::TypeNode *type = ParseTypeAnnotation(&options); auto *typeOperator = AllocNode(type, ir::TSOperatorType::KEYOF, Allocator()); - + ES2PANDA_ASSERT(typeOperator != nullptr); typeOperator->SetRange({typeOperatorStart, type->End()}); return typeOperator; @@ -693,6 +693,7 @@ ir::TypeNode *TSParser::ParseTypeReferenceOrQuery(bool parseQuery) Lexer()->GetToken().Type() == lexer::TokenType::KEYW_EXTENDS); ir::Expression *typeName = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(typeName != nullptr); typeName->SetRange(Lexer()->GetToken().Loc()); if (Lexer()->Lookahead() == lexer::LEX_CHAR_LESS_THAN) { diff --git a/ets2panda/parser/TypedParser.cpp b/ets2panda/parser/TypedParser.cpp index d39bcaae81..1c0e3b1036 100644 --- a/ets2panda/parser/TypedParser.cpp +++ b/ets2panda/parser/TypedParser.cpp @@ -330,6 +330,7 @@ ir::TSModuleDeclaration *TypedParser::ParseModuleOrNamespaceDeclaration(const le auto *moduleDecl = AllocNode(Allocator(), identNode, body, ir::TSModuleDeclaration::ConstructorFlags {false, false}); + ES2PANDA_ASSERT(moduleDecl != nullptr); moduleDecl->SetRange({startLoc, Lexer()->GetToken().End()}); return moduleDecl; @@ -428,6 +429,7 @@ ir::TypeNode *TypedParser::ParseInterfaceExtendsElement() } auto *typeReference = AllocNode(expr, typeParamInst, Allocator()); + ES2PANDA_ASSERT(typeReference != nullptr); typeReference->SetRange({heritageStart, heritageEnd}); return typeReference; } @@ -762,7 +764,7 @@ ir::TSTypeParameter *TypedParser::ParseTypeParameter(TypeAnnotationParsingOption } auto *typeParam = AllocNode(paramIdent, constraint, defaultType, Allocator()); - + ES2PANDA_ASSERT(typeParam != nullptr); typeParam->SetRange({startLoc, Lexer()->GetToken().End()}); return typeParam; diff --git a/ets2panda/parser/context/classPrivateContext.cpp b/ets2panda/parser/context/classPrivateContext.cpp index d191b3b597..048ec7177a 100644 --- a/ets2panda/parser/context/classPrivateContext.cpp +++ b/ets2panda/parser/context/classPrivateContext.cpp @@ -25,7 +25,7 @@ bool ClassPrivateContext::AddElement(const ir::ClassElement *elem) { bool newPropIsStatic = elem->IsStatic(); auto id = elem->Id(); - ES2PANDA_ASSERT(id); + ES2PANDA_ASSERT(id != nullptr); util::StringView newPropName = id->Name(); ir::MethodDefinitionKind newPropMethodKind = ir::MethodDefinitionKind::METHOD; @@ -64,7 +64,7 @@ bool ClassPrivateContext::FindElement(const ir::Identifier *elem) const { for (const auto *it : elements_) { auto id = it->Id(); - ES2PANDA_ASSERT(id); + ES2PANDA_ASSERT(id != nullptr); if (id->Name().Compare(elem->Name()) == 0) { return true; } diff --git a/ets2panda/parser/expressionParser.cpp b/ets2panda/parser/expressionParser.cpp index 3c86c8373d..75394a9264 100644 --- a/ets2panda/parser/expressionParser.cpp +++ b/ets2panda/parser/expressionParser.cpp @@ -114,7 +114,7 @@ ir::YieldExpression *ParserImpl::ParseYieldExpression() } auto *yieldNode = AllocNode(argument, isDelegate); - ES2PANDA_ASSERT(yieldNode); + ES2PANDA_ASSERT(yieldNode != nullptr); yieldNode->SetRange({startLoc, endLoc}); return yieldNode; @@ -209,7 +209,7 @@ ir::ArrayExpression *ParserImpl::ParseArrayExpression(ExpressionParseFlags flags auto nodeType = inPattern ? ir::AstNodeType::ARRAY_PATTERN : ir::AstNodeType::ARRAY_EXPRESSION; auto *arrayExpressionNode = AllocNode(nodeType, std::move(elements), Allocator(), trailingComma); - ES2PANDA_ASSERT(arrayExpressionNode); + ES2PANDA_ASSERT(arrayExpressionNode != nullptr); arrayExpressionNode->SetRange({startLoc, endLoc}); if (inPattern) { @@ -341,6 +341,7 @@ ir::ArrowFunctionExpression *ParserImpl::ParseArrowFunctionExpressionBody(ArrowF {}, context_.GetLanguage()}); // clang-format on + ES2PANDA_ASSERT(funcNode != nullptr); funcNode->SetRange({desc->startLoc, endLoc}); auto *arrowFuncNode = AllocNode(funcNode, Allocator()); @@ -577,7 +578,7 @@ ir::Expression *ParserImpl::CreateBinaryAssignmentExpression(ir::Expression *ass { auto *binaryAssignmentExpression = AllocNode(lhsExpression, assignmentExpression, tokenType); - ES2PANDA_ASSERT(binaryAssignmentExpression); + ES2PANDA_ASSERT(binaryAssignmentExpression != nullptr); binaryAssignmentExpression->SetRange({lhsExpression->Start(), assignmentExpression->End()}); return binaryAssignmentExpression; @@ -593,7 +594,7 @@ ir::Expression *ParserImpl::ParseAssignmentExpression(ir::Expression *lhsExpress ir::Expression *consequent = ParseAssignmentExpressionHelper(); ir::Expression *alternate = ParseExpression(); auto *conditionalExpr = AllocNode(lhsExpression, consequent, alternate); - ES2PANDA_ASSERT(conditionalExpr); + ES2PANDA_ASSERT(conditionalExpr != nullptr); conditionalExpr->SetRange({lhsExpression->Start(), alternate->End()}); return conditionalExpr; } @@ -707,7 +708,7 @@ ir::Expression *ParserImpl::ParseAssignmentEqualExpression(const lexer::TokenTyp auto *binaryAssignmentExpression = AllocNode(lhsExpression, assignmentExpression, tokenType); - ES2PANDA_ASSERT(binaryAssignmentExpression); + ES2PANDA_ASSERT(binaryAssignmentExpression != nullptr); binaryAssignmentExpression->SetRange({lhsExpression->Start(), assignmentExpression->End()}); return binaryAssignmentExpression; @@ -748,6 +749,7 @@ ir::TemplateLiteral *ParserImpl::ParseTemplateLiteral() const auto templateStr = lexer_->ScanTemplateString(); if (templateStr.validSequence) { auto *const element = AllocNode(templateStr.str.View(), cooked); + ES2PANDA_ASSERT(element != nullptr); element->SetRange({lexer::SourcePosition {startPos.Iterator().Index(), startPos.Line(), GetProgram()}, lexer::SourcePosition {templateStr.end, lexer_->Line(), GetProgram()}}); quasis.push_back(element); @@ -798,7 +800,7 @@ ir::Expression *ParserImpl::ParseNewExpression() if (lexer_->GetToken().Type() != lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS) { lexer::SourcePosition endLoc = callee->End(); auto *newExprNode = AllocNode(callee, std::move(arguments)); - ES2PANDA_ASSERT(newExprNode); + ES2PANDA_ASSERT(newExprNode != nullptr); newExprNode->SetRange({start, endLoc}); return newExprNode; @@ -824,7 +826,7 @@ ir::Expression *ParserImpl::ParseNewExpression() &endLoc, true); auto *newExprNode = AllocNode(callee, std::move(arguments)); - ES2PANDA_ASSERT(newExprNode); + ES2PANDA_ASSERT(newExprNode != nullptr); newExprNode->SetRange({start, endLoc}); return newExprNode; @@ -853,7 +855,7 @@ ir::MetaProperty *ParserImpl::ParsePotentialNewTarget() } auto *metaProperty = AllocNode(ir::MetaProperty::MetaPropertyKind::NEW_TARGET); - ES2PANDA_ASSERT(metaProperty); + ES2PANDA_ASSERT(metaProperty != nullptr); metaProperty->SetRange(loc); lexer_->NextToken(); return metaProperty; @@ -866,7 +868,7 @@ ir::MetaProperty *ParserImpl::ParsePotentialNewTarget() ir::Identifier *ParserImpl::ParsePrimaryExpressionIdent([[maybe_unused]] ExpressionParseFlags flags) { auto *identNode = AllocNode(lexer_->GetToken().Ident(), Allocator()); - ES2PANDA_ASSERT(identNode); + ES2PANDA_ASSERT(identNode != nullptr); identNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -879,7 +881,7 @@ ir::BooleanLiteral *ParserImpl::ParseBooleanLiteral() lexer_->GetToken().Type() == lexer::TokenType::LITERAL_FALSE); auto *booleanNode = AllocNode(lexer_->GetToken().Type() == lexer::TokenType::LITERAL_TRUE); - ES2PANDA_ASSERT(booleanNode); + ES2PANDA_ASSERT(booleanNode != nullptr); booleanNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -890,7 +892,7 @@ ir::NullLiteral *ParserImpl::ParseNullLiteral() { ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::LITERAL_NULL); auto *nullNode = AllocNode(); - ES2PANDA_ASSERT(nullNode); + ES2PANDA_ASSERT(nullNode != nullptr); nullNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -909,7 +911,7 @@ ir::Literal *ParserImpl::ParseNumberLiteral() numberNode = AllocNode(lexer_->GetToken().GetNumber()); } - ES2PANDA_ASSERT(numberNode); + ES2PANDA_ASSERT(numberNode != nullptr); numberNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -921,7 +923,7 @@ ir::CharLiteral *ParserImpl::ParseCharLiteral() ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::LITERAL_CHAR); auto *charNode = AllocNode(lexer_->GetToken().Utf16()); - ES2PANDA_ASSERT(charNode); + ES2PANDA_ASSERT(charNode != nullptr); charNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -933,7 +935,7 @@ ir::StringLiteral *ParserImpl::ParseStringLiteral() ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::LITERAL_STRING); auto *stringNode = AllocNode(lexer_->GetToken().String()); - ES2PANDA_ASSERT(stringNode); + ES2PANDA_ASSERT(stringNode != nullptr); stringNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -944,7 +946,7 @@ ir::UndefinedLiteral *ParserImpl::ParseUndefinedLiteral() { ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::KEYW_UNDEFINED); auto *undefinedNode = AllocNode(); - ES2PANDA_ASSERT(undefinedNode); + ES2PANDA_ASSERT(undefinedNode != nullptr); undefinedNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -976,7 +978,7 @@ ir::RegExpLiteral *ParserImpl::ParseRegularExpression() reParser.ParsePattern(); auto *regexpNode = AllocNode(regexp.patternStr, regexp.flags, regexp.flagsStr); - ES2PANDA_ASSERT(regexpNode); + ES2PANDA_ASSERT(regexpNode != nullptr); regexpNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -988,7 +990,7 @@ ir::SuperExpression *ParserImpl::ParseSuperExpression() ES2PANDA_ASSERT(lexer_->GetToken().Type() == lexer::TokenType::KEYW_SUPER); auto *superExprNode = AllocNode(); - ES2PANDA_ASSERT(superExprNode); + ES2PANDA_ASSERT(superExprNode != nullptr); superExprNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); // eat super @@ -1037,7 +1039,7 @@ ir::Expression *ParserImpl::ParseHashMaskOperator() } auto *privateIdent = AllocNode(lexer_->GetToken().Ident(), Allocator()); - ES2PANDA_ASSERT(privateIdent); + ES2PANDA_ASSERT(privateIdent != nullptr); privateIdent->SetPrivate(true); lexer_->NextToken(); @@ -1059,7 +1061,7 @@ ir::Expression *ParserImpl::ParseClassExpression() } auto *classExpr = AllocNode(classDefinition); - ES2PANDA_ASSERT(classExpr); + ES2PANDA_ASSERT(classExpr != nullptr); classExpr->SetRange({startLoc, classDefinition->End()}); return classExpr; @@ -1298,7 +1300,7 @@ void ParserImpl::CreateAmendedBinaryExpression(ir::Expression *const left, ir::E amended->SetParent(nullptr); // Next line overwrite parent auto *binaryExpr = AllocNode(left, amended, operatorType); - ES2PANDA_ASSERT(binaryExpr); + ES2PANDA_ASSERT(binaryExpr != nullptr); binaryExpr->SetRange({left->Start(), amended->End()}); SetAmendedChildExpression(right, binaryExpr); } @@ -1357,7 +1359,7 @@ ir::Expression *ParserImpl::ParseBinaryExpression(ir::Expression *left, const le } const lexer::SourcePosition &endPos = rightExpr->End(); rightExpr = AllocNode(left, rightExpr, operatorType); - ES2PANDA_ASSERT(rightExpr); + ES2PANDA_ASSERT(rightExpr != nullptr); rightExpr->SetRange({left->Start(), endPos}); } @@ -1423,7 +1425,7 @@ ir::CallExpression *ParserImpl::ParseCallExpression(ir::Expression *callee, bool callExpr = AllocNode(callee, std::move(arguments), nullptr, isOptionalChain, trailingComma); } - ES2PANDA_ASSERT(callExpr); + ES2PANDA_ASSERT(callExpr != nullptr); callExpr->SetRange({callee->Start(), endLoc}); isOptionalChain = false; @@ -1453,12 +1455,13 @@ ir::Expression *ParserImpl::ParseOptionalChain(ir::Expression *leftSideExpr) const auto tokenType = lexer_->GetToken().Type(); if (tokenType == lexer::TokenType::LITERAL_IDENT) { auto *identNode = AllocNode(lexer_->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(identNode != nullptr); identNode->SetPrivate(isPrivate); identNode->SetRange(lexer_->GetToken().Loc()); returnExpression = AllocNode(leftSideExpr, identNode, ir::MemberExpressionKind::PROPERTY_ACCESS, false, true); - ES2PANDA_ASSERT(returnExpression); + ES2PANDA_ASSERT(returnExpression != nullptr); returnExpression->SetRange({leftSideExpr->Start(), identNode->End()}); lexer_->NextToken(); } @@ -1475,7 +1478,7 @@ ir::Expression *ParserImpl::ParseOptionalChain(ir::Expression *leftSideExpr) returnExpression = AllocNode(leftSideExpr, propertyNode, ir::MemberExpressionKind::ELEMENT_ACCESS, true, true); - ES2PANDA_ASSERT(returnExpression); + ES2PANDA_ASSERT(returnExpression != nullptr); returnExpression->SetRange({leftSideExpr->Start(), endLoc}); lexer_->NextToken(); } @@ -1499,7 +1502,7 @@ ir::ArrowFunctionExpression *ParserImpl::ParsePotentialArrowExpression(ir::Expre switch (lexer_->GetToken().Type()) { case lexer::TokenType::KEYW_FUNCTION: { *returnExpression = ParseFunctionExpression(ParserStatus::ASYNC_FUNCTION); - ES2PANDA_ASSERT(returnExpression); + ES2PANDA_ASSERT(returnExpression != nullptr); (*returnExpression)->SetStart(startLoc); break; } @@ -1575,7 +1578,7 @@ ir::MemberExpression *ParserImpl::ParseElementAccess(ir::Expression *primaryExpr auto *memberExpr = AllocNode(primaryExpr, propertyNode, ir::MemberExpressionKind::ELEMENT_ACCESS, true, isOptional); - ES2PANDA_ASSERT(memberExpr); + ES2PANDA_ASSERT(memberExpr != nullptr); memberExpr->SetRange({primaryExpr->Start(), lexer_->GetToken().End()}); lexer_->NextToken(); return memberExpr; @@ -1589,14 +1592,14 @@ ir::MemberExpression *ParserImpl::ParsePrivatePropertyAccess(ir::Expression *pri ValidatePrivateIdentifier(); auto *privateIdent = AllocNode(lexer_->GetToken().Ident(), Allocator()); - ES2PANDA_ASSERT(privateIdent); + ES2PANDA_ASSERT(privateIdent != nullptr); privateIdent->SetRange({memberStart, lexer_->GetToken().End()}); privateIdent->SetPrivate(true); lexer_->NextToken(); auto *memberExpr = AllocNode(primaryExpr, privateIdent, ir::MemberExpressionKind::PROPERTY_ACCESS, false, false); - ES2PANDA_ASSERT(memberExpr); + ES2PANDA_ASSERT(memberExpr != nullptr); memberExpr->SetRange({primaryExpr->Start(), privateIdent->End()}); return memberExpr; } @@ -1606,7 +1609,7 @@ ir::MemberExpression *ParserImpl::ParsePropertyAccess(ir::Expression *primaryExp ir::Identifier *ident = ExpectIdentifier(true); auto *memberExpr = AllocNode(primaryExpr, ident, ir::MemberExpressionKind::PROPERTY_ACCESS, false, isOptional); - ES2PANDA_ASSERT(memberExpr); + ES2PANDA_ASSERT(memberExpr != nullptr); memberExpr->SetRange({primaryExpr->Start(), ident->End()}); return memberExpr; @@ -1669,11 +1672,11 @@ ir::Expression *ParserImpl::ParsePostPrimaryExpressionBackTick(ir::Expression *r const lexer::SourcePosition startLoc) { ir::TemplateLiteral *propertyNode = ParseTemplateLiteral(); - ES2PANDA_ASSERT(propertyNode); + ES2PANDA_ASSERT(propertyNode != nullptr); lexer::SourcePosition endLoc = propertyNode->End(); returnExpression = AllocNode(returnExpression, propertyNode, nullptr); - ES2PANDA_ASSERT(returnExpression); + ES2PANDA_ASSERT(returnExpression != nullptr); returnExpression->SetRange({startLoc, endLoc}); return returnExpression; @@ -1734,7 +1737,7 @@ ir::Expression *ParserImpl::SetupChainExpr(ir::Expression *const top, lexer::Sou lexer::SourcePosition endLoc = expr->End(); auto chain = AllocNode(expr); - ES2PANDA_ASSERT(chain); + ES2PANDA_ASSERT(chain != nullptr); chain->SetRange({startLoc, endLoc}); if (expr == top) { @@ -1783,7 +1786,7 @@ ir::Expression *ParserImpl::ParseMemberExpression(bool ignoreCallExpression, Exp returnExpression = AllocNode(returnExpression, lexer_->GetToken().Type(), false); - ES2PANDA_ASSERT(returnExpression); + ES2PANDA_ASSERT(returnExpression != nullptr); returnExpression->SetRange({start, lexer_->GetToken().End()}); lexer_->NextToken(); } @@ -1834,7 +1837,7 @@ ir::Expression *ParserImpl::ParsePatternElement(ExpressionParseFlags flags, bool ir::Expression *rightNode = ParseExpression(); auto *assignmentExpression = AllocNode( ir::AstNodeType::ASSIGNMENT_PATTERN, returnNode, rightNode, lexer::TokenType::PUNCTUATOR_SUBSTITUTION); - ES2PANDA_ASSERT(assignmentExpression); + ES2PANDA_ASSERT(assignmentExpression != nullptr); assignmentExpression->SetRange({returnNode->Start(), rightNode->End()}); return assignmentExpression; @@ -1941,7 +1944,7 @@ ir::Property *ParserImpl::ParseShorthandProperty(const lexer::LexerPosition *sta const util::StringView &ident = lexer_->GetToken().Ident(); auto *key = AllocNode(ident, Allocator()); - ES2PANDA_ASSERT(key); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(lexer_->GetToken().Loc()); ir::Expression *value = AllocNode(ident, Allocator()); @@ -1959,6 +1962,7 @@ ir::Property *ParserImpl::ParseShorthandProperty(const lexer::LexerPosition *sta auto *assignmentExpression = AllocNode( ir::AstNodeType::ASSIGNMENT_PATTERN, value, rightNode, lexer::TokenType::PUNCTUATOR_SUBSTITUTION); + ES2PANDA_ASSERT(assignmentExpression != nullptr); assignmentExpression->SetRange({value->Start(), rightNode->End()}); end = rightNode->End(); value = assignmentExpression; @@ -1968,7 +1972,7 @@ ir::Property *ParserImpl::ParseShorthandProperty(const lexer::LexerPosition *sta } auto *returnProperty = AllocNode(key, value); - ES2PANDA_ASSERT(returnProperty); + ES2PANDA_ASSERT(returnProperty != nullptr); returnProperty->SetRange({start, end}); return returnProperty; @@ -2035,7 +2039,7 @@ ir::Expression *ParserImpl::ParsePropertyKey(ExpressionParseFlags flags) case lexer::TokenType::LITERAL_IDENT: { const util::StringView &ident = lexer_->GetToken().Ident(); key = AllocNode(ident, Allocator()); - ES2PANDA_ASSERT(key); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); return key; @@ -2043,7 +2047,7 @@ ir::Expression *ParserImpl::ParsePropertyKey(ExpressionParseFlags flags) case lexer::TokenType::LITERAL_STRING: { const util::StringView &string = lexer_->GetToken().String(); key = AllocNode(string); - ES2PANDA_ASSERT(key); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); return key; @@ -2054,7 +2058,7 @@ ir::Expression *ParserImpl::ParsePropertyKey(ExpressionParseFlags flags) } else { key = AllocNode(lexer_->GetToken().GetNumber()); } - ES2PANDA_ASSERT(key); + ES2PANDA_ASSERT(key != nullptr); key->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); return key; @@ -2120,12 +2124,13 @@ ir::Expression *ParserImpl::ParsePropertyValue(const ir::PropertyKind *propertyK } ir::ScriptFunction *methodDefinitonNode = ParseFunction(newStatus); + ES2PANDA_ASSERT(methodDefinitonNode != nullptr); methodDefinitonNode->AddFlag(ir::ScriptFunctionFlags::METHOD); size_t paramsSize = methodDefinitonNode->Params().size(); auto *value = AllocNode(methodDefinitonNode); - ES2PANDA_ASSERT(value); + ES2PANDA_ASSERT(value != nullptr); value->SetRange(methodDefinitonNode->Range()); if (*propertyKind == ir::PropertyKind::SET && paramsSize != 1) { @@ -2175,12 +2180,12 @@ ir::Expression *ParserImpl::ParsePropertyDefinition([[maybe_unused]] ExpressionP } ir::Expression *value = ParsePropertyValue(&propertyKind, &methodStatus, flags); - ES2PANDA_ASSERT(value); + ES2PANDA_ASSERT(value != nullptr); lexer::SourcePosition end = value->End(); auto *returnProperty = AllocNode(propertyKind, key, value, methodStatus != ParserStatus::NO_OPTS, isComputed); - ES2PANDA_ASSERT(returnProperty); + ES2PANDA_ASSERT(returnProperty != nullptr); returnProperty->SetRange({start, end}); return returnProperty; @@ -2256,7 +2261,7 @@ ir::ObjectExpression *ParserImpl::ParseObjectExpression(ExpressionParseFlags fla auto nodeType = inPattern ? ir::AstNodeType::OBJECT_PATTERN : ir::AstNodeType::OBJECT_EXPRESSION; auto *objectExpression = AllocNode(nodeType, Allocator(), std::move(properties), trailingComma); - ES2PANDA_ASSERT(objectExpression); + ES2PANDA_ASSERT(objectExpression != nullptr); objectExpression->SetRange({start, lexer_->GetToken().End()}); lexer_->NextToken(); @@ -2303,7 +2308,7 @@ ir::SequenceExpression *ParserImpl::ParseSequenceExpression(ir::Expression *star lexer::SourcePosition end = sequence.back()->End(); auto *sequenceNode = AllocNode(std::move(sequence)); - ES2PANDA_ASSERT(sequenceNode); + ES2PANDA_ASSERT(sequenceNode != nullptr); sequenceNode->SetRange({start, end}); return sequenceNode; @@ -2395,7 +2400,7 @@ ir::Expression *ParserImpl::ParseImportExpression() } auto *metaProperty = AllocNode(ir::MetaProperty::MetaPropertyKind::IMPORT_META); - ES2PANDA_ASSERT(metaProperty); + ES2PANDA_ASSERT(metaProperty != nullptr); metaProperty->SetRange({startLoc, endLoc}); lexer_->NextToken(); @@ -2448,7 +2453,7 @@ ir::FunctionExpression *ParserImpl::ParseFunctionExpression(ParserStatus newStat functionNode->SetStart(startLoc); auto *funcExpr = AllocNode(ident, functionNode); - ES2PANDA_ASSERT(funcExpr); + ES2PANDA_ASSERT(funcExpr != nullptr); funcExpr->SetRange(functionNode->Range()); return funcExpr; diff --git a/ets2panda/parser/expressionTSParser.cpp b/ets2panda/parser/expressionTSParser.cpp index fe80a876b9..fc615e5bff 100644 --- a/ets2panda/parser/expressionTSParser.cpp +++ b/ets2panda/parser/expressionTSParser.cpp @@ -137,7 +137,7 @@ ir::Expression *TSParser::ParsePotentialAsExpression(ir::Expression *expr) lexer::SourcePosition startLoc = expr->Start(); auto *asExpr = AllocNode(expr, typeAnnotation, isConst); - ES2PANDA_ASSERT(asExpr); + ES2PANDA_ASSERT(asExpr != nullptr); asExpr->SetRange({startLoc, Lexer()->GetToken().End()}); if (Lexer()->GetToken().KeywordType() == lexer::TokenType::KEYW_AS) { @@ -170,7 +170,7 @@ ir::AnnotatedExpression *TSParser::ParsePatternElementGetReturnNode(ExpressionPa } case lexer::TokenType::LITERAL_IDENT: { ir::AnnotatedExpression *returnNode = AllocNode(Lexer()->GetToken().Ident(), Allocator()); - ES2PANDA_ASSERT(returnNode); + ES2PANDA_ASSERT(returnNode != nullptr); if (returnNode->AsIdentifier()->Decorators().empty()) { returnNode->SetRange(Lexer()->GetToken().Loc()); @@ -330,6 +330,7 @@ ir::Expression *TSParser::ParseModuleReference() } result = AllocNode(Lexer()->GetToken().String()); + ES2PANDA_ASSERT(result != nullptr); result->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -342,7 +343,7 @@ ir::Expression *TSParser::ParseModuleReference() Lexer()->NextToken(); // eat ')' } else { result = AllocNode(Lexer()->GetToken().Ident(), Allocator()); - ES2PANDA_ASSERT(result); + ES2PANDA_ASSERT(result != nullptr); result->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); @@ -357,6 +358,7 @@ ir::Expression *TSParser::ParseModuleReference() ir::TSTypeReference *TSParser::ParseConstExpression() { auto *identRef = AllocNode(Lexer()->GetToken().Ident(), Allocator()); + ES2PANDA_ASSERT(identRef != nullptr); identRef->SetRange(Lexer()->GetToken().Loc()); auto *typeReference = AllocNode(identRef, nullptr, Allocator()); @@ -383,7 +385,7 @@ bool TSParser::ParsePotentialNonNullExpression(ir::Expression **returnExpression } *returnExpression = AllocNode(*returnExpression); - ES2PANDA_ASSERT(*returnExpression); + ES2PANDA_ASSERT(*returnExpression != nullptr); // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) (*returnExpression)->SetRange({startLoc, Lexer()->GetToken().End()}); Lexer()->NextToken(); @@ -451,7 +453,7 @@ ir::ArrowFunctionExpression *TSParser::ParsePotentialArrowExpression(ir::Express switch (Lexer()->GetToken().Type()) { case lexer::TokenType::KEYW_FUNCTION: { *returnExpression = ParseFunctionExpression(ParserStatus::ASYNC_FUNCTION); - ES2PANDA_ASSERT(*returnExpression); + ES2PANDA_ASSERT(*returnExpression != nullptr); (*returnExpression)->SetStart(startLoc); break; } diff --git a/ets2panda/parser/parserImpl.cpp b/ets2panda/parser/parserImpl.cpp index d3ff773b2c..b9415f03fd 100644 --- a/ets2panda/parser/parserImpl.cpp +++ b/ets2panda/parser/parserImpl.cpp @@ -82,7 +82,7 @@ void ParserImpl::ParseProgram(ScriptKind kind) auto statements = ParseStatementList(StatementParsingFlags::STMT_GLOBAL_LEXICAL); auto *blockStmt = AllocNode(Allocator(), std::move(statements)); - ES2PANDA_ASSERT(blockStmt); + ES2PANDA_ASSERT(blockStmt != nullptr); blockStmt->SetRange({startLoc, lexer_->GetToken().End()}); program_->SetAst(blockStmt); @@ -352,7 +352,7 @@ ir::Expression *ParserImpl::ParseClassKey(ClassElementDescriptor *desc) ValidateClassKey(desc); propName = AllocNode(lexer_->GetToken().Ident(), Allocator()); - ES2PANDA_ASSERT(propName); + ES2PANDA_ASSERT(propName != nullptr); propName->SetRange(lexer_->GetToken().Loc()); propName->AsIdentifier()->SetPrivate(desc->isPrivateIdent); break; @@ -369,7 +369,7 @@ ir::Expression *ParserImpl::ParseClassKey(ClassElementDescriptor *desc) } propName = AllocNode(lexer_->GetToken().String()); - ES2PANDA_ASSERT(propName); + ES2PANDA_ASSERT(propName != nullptr); propName->SetRange(lexer_->GetToken().Loc()); break; } @@ -381,7 +381,7 @@ ir::Expression *ParserImpl::ParseClassKey(ClassElementDescriptor *desc) } else { propName = AllocNode(lexer_->GetToken().GetNumber()); } - ES2PANDA_ASSERT(propName); + ES2PANDA_ASSERT(propName != nullptr); propName->SetRange(lexer_->GetToken().Loc()); break; @@ -461,7 +461,7 @@ ir::MethodDefinition *ParserImpl::ParseClassMethod(ClassElementDescriptor *desc, ir::ScriptFunction *func = ParseFunction(desc->newStatus); auto *funcExpr = AllocNode(func); - ES2PANDA_ASSERT(funcExpr); + ES2PANDA_ASSERT(funcExpr != nullptr); funcExpr->SetRange(func->Range()); if (desc->methodKind == ir::MethodDefinitionKind::SET) { @@ -487,7 +487,7 @@ ir::ClassElement *ParserImpl::ParseClassProperty(ClassElementDescriptor *desc, const ArenaVector &properties, ir::Expression *propName, ir::TypeNode *typeAnnotation) { - ES2PANDA_ASSERT(propName); + ES2PANDA_ASSERT(propName != nullptr); lexer::SourcePosition propEnd = propName->End(); ir::ClassElement *property = nullptr; @@ -595,7 +595,7 @@ ir::ClassElement *ParserImpl::ParseClassStaticBlock() auto *funcExpr = AllocNode(func); auto *staticBlock = AllocNode(funcExpr, Allocator()); - ES2PANDA_ASSERT(staticBlock); + ES2PANDA_ASSERT(staticBlock != nullptr); staticBlock->SetRange({startPos, lexer_->GetToken().End()}); lexer_->NextToken(); // eat '}' @@ -712,7 +712,7 @@ void ParserImpl::CreateImplicitConstructor(ir::MethodDefinition *&ctor, ctor = BuildImplicitConstructor(modifiers, startLoc); if ((flags & ir::ModifierFlags::DECLARE) != 0) { auto *ctorFunc = ctor->Function(); - ES2PANDA_ASSERT(ctorFunc); + ES2PANDA_ASSERT(ctorFunc != nullptr); ctorFunc->AddFlag(ir::ScriptFunctionFlags::EXTERNAL); } } @@ -799,7 +799,7 @@ ir::ClassDefinition *ParserImpl::ParseClassDefinition(ir::ClassDefinitionModifie auto *classDefinition = AllocNode(identNode, nullptr, superTypeParams, std::move(implements), ctor, superClass, std::move(properties), modifiers, flags, GetContext().GetLanguage()); - ES2PANDA_ASSERT(classDefinition); + ES2PANDA_ASSERT(classDefinition != nullptr); classDefinition->SetInternalName(privateBinding.View()); classDefinition->SetRange(bodyRange); @@ -950,7 +950,7 @@ std::tuple ParserImpl:: } ir::BlockStatement *body = ParseBlockStatement(); - ES2PANDA_ASSERT(body); + ES2PANDA_ASSERT(body != nullptr); return {true, body, body->End(), false}; } @@ -1016,7 +1016,7 @@ ir::ScriptFunction *ParserImpl::ParseFunction(ParserStatus newStatus) functionContext.Flags(), // CC-OFFNXT(G.FMT.02-CPP) project code style {}, // CC-OFFNXT(G.FMT.02-CPP) project code style context_.GetLanguage()}); // CC-OFF(G.FMT.02-CPP) project code style - ES2PANDA_ASSERT(funcNode); + ES2PANDA_ASSERT(funcNode != nullptr); funcNode->SetRange({startLoc, endLoc}); @@ -1046,7 +1046,7 @@ ir::SpreadElement *ParserImpl::ParseSpreadElement(ExpressionParseFlags flags) auto nodeType = inPattern ? ir::AstNodeType::REST_ELEMENT : ir::AstNodeType::SPREAD_ELEMENT; auto *spreadElementNode = AllocNode(nodeType, Allocator(), argument); - ES2PANDA_ASSERT(spreadElementNode); + ES2PANDA_ASSERT(spreadElementNode != nullptr); spreadElementNode->SetRange({startLocation, argument->End()}); return spreadElementNode; } @@ -1287,7 +1287,7 @@ ir::Identifier *ParserImpl::ExpectIdentifier([[maybe_unused]] bool isReference, } auto *ident = AllocNode(tokenName, Allocator()); - ES2PANDA_ASSERT(ident); + ES2PANDA_ASSERT(ident != nullptr); // NOTE: here actual token can be changed! ident->SetRange({tokenStart, lexer_->GetToken().End()}); lexer_->NextToken(); @@ -1463,7 +1463,7 @@ ir::Identifier *ParserImpl::AllocBrokenExpression(const lexer::SourcePosition &p ir::Identifier *ParserImpl::AllocBrokenExpression(const lexer::SourceRange &range) { auto *node = AllocNode(Allocator()); - ES2PANDA_ASSERT(node); + ES2PANDA_ASSERT(node != nullptr); node->SetRange(range); return node; } @@ -1476,7 +1476,7 @@ ir::TypeNode *ParserImpl::AllocBrokenType(const lexer::SourcePosition &pos) ir::TypeNode *ParserImpl::AllocBrokenType(const lexer::SourceRange &range) { auto node = AllocNode(Allocator()); - ES2PANDA_ASSERT(node); + ES2PANDA_ASSERT(node != nullptr); node->SetRange(range); return node; } diff --git a/ets2panda/parser/program/program.cpp b/ets2panda/parser/program/program.cpp index 403d7d8830..61c73eed14 100644 --- a/ets2panda/parser/program/program.cpp +++ b/ets2panda/parser/program/program.cpp @@ -98,7 +98,7 @@ void Program::SetPackageInfo(const util::StringView &name, util::ModuleKind kind // NOTE(vpukhov): part of ongoing design void Program::MaybeTransformToDeclarationModule() { - ES2PANDA_ASSERT(ast_); + ES2PANDA_ASSERT(ast_ != nullptr); if (IsPackage() || ast_->Statements().empty()) { return; } diff --git a/ets2panda/parser/statementParser.cpp b/ets2panda/parser/statementParser.cpp index 3fefb15d68..fc137fdec5 100644 --- a/ets2panda/parser/statementParser.cpp +++ b/ets2panda/parser/statementParser.cpp @@ -225,7 +225,7 @@ ir::Statement *ParserImpl::ParseLetStatement(StatementParsingFlags flags) } auto *variableDecl = ParseVariableDeclaration(VariableParsingFlags::LET); - ES2PANDA_ASSERT(variableDecl); + ES2PANDA_ASSERT(variableDecl != nullptr); if (variableDecl->IsBrokenStatement()) { // Error processing. return variableDecl; } @@ -244,7 +244,7 @@ ir::Statement *ParserImpl::ParseConstStatement(StatementParsingFlags flags) lexer_->NextToken(); auto *variableDecl = ParseVariableDeclaration(VariableParsingFlags::CONST | VariableParsingFlags::NO_SKIP_VAR_KIND); - ES2PANDA_ASSERT(variableDecl); + ES2PANDA_ASSERT(variableDecl != nullptr); if (variableDecl->IsBrokenStatement()) { // Error processing. return variableDecl; } @@ -258,7 +258,7 @@ ir::Statement *ParserImpl::ParseConstStatement(StatementParsingFlags flags) ir::EmptyStatement *ParserImpl::ParseEmptyStatement() { auto *empty = AllocNode(); - ES2PANDA_ASSERT(empty); + ES2PANDA_ASSERT(empty != nullptr); empty->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); return empty; @@ -267,7 +267,7 @@ ir::EmptyStatement *ParserImpl::ParseEmptyStatement() ir::Statement *ParserImpl::ParseDebuggerStatement() { auto *debuggerNode = AllocNode(); - ES2PANDA_ASSERT(debuggerNode); + ES2PANDA_ASSERT(debuggerNode != nullptr); debuggerNode->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); ConsumeSemicolon(debuggerNode); @@ -287,7 +287,7 @@ ir::Statement *ParserImpl::ParseFunctionStatement(StatementParsingFlags flags) stmts.push_back(funcDecl); auto *localBlockStmt = AllocNode(Allocator(), std::move(stmts)); - ES2PANDA_ASSERT(localBlockStmt); + ES2PANDA_ASSERT(localBlockStmt != nullptr); localBlockStmt->SetRange(funcDecl->Range()); return funcDecl; @@ -333,7 +333,7 @@ ir::Statement *ParserImpl::ParseStructDeclaration(ir::ClassDefinitionModifiers m lexer::SourcePosition endLoc = classDefinition->End(); auto *structDecl = AllocNode(classDefinition, Allocator()); - ES2PANDA_ASSERT(structDecl); + ES2PANDA_ASSERT(structDecl != nullptr); structDecl->SetRange({startLoc, endLoc}); return structDecl; } @@ -354,7 +354,7 @@ ir::Statement *ParserImpl::ParseClassDeclaration(ir::ClassDefinitionModifiers mo lexer::SourcePosition endLoc = classDefinition->End(); auto *classDecl = AllocNode(classDefinition, Allocator()); - ES2PANDA_ASSERT(classDecl); + ES2PANDA_ASSERT(classDecl != nullptr); classDecl->SetRange({startLoc, endLoc}); return classDecl; } @@ -381,7 +381,7 @@ void ParserImpl::ConsumeSemicolon(ir::Statement *statement) auto const &token = lexer_->GetToken(); auto tokenType = token.Type(); if (tokenType == lexer::TokenType::PUNCTUATOR_SEMI_COLON) { - ES2PANDA_ASSERT(statement); + ES2PANDA_ASSERT(statement != nullptr); statement->SetEnd(token.End()); lexer_->NextToken(); return; @@ -437,7 +437,7 @@ bool ParserImpl::ParseDirective(ArenaVector *statements) bool isDirective = exprNode->IsStringLiteral(); auto *exprStatement = AllocNode(exprNode); - ES2PANDA_ASSERT(exprStatement); + ES2PANDA_ASSERT(exprStatement != nullptr); exprStatement->SetRange(exprNode->Range()); ConsumeSemicolon(exprStatement); @@ -468,7 +468,7 @@ ir::BlockStatement *ParserImpl::ParseBlockStatement() auto statements = ParseStatementList(); auto *blockNode = AllocNode(Allocator(), std::move(statements)); - ES2PANDA_ASSERT(blockNode); + ES2PANDA_ASSERT(blockNode != nullptr); blockNode->SetRange({startLoc, lexer_->GetToken().End()}); ExpectToken(lexer::TokenType::PUNCTUATOR_RIGHT_BRACE); @@ -500,7 +500,7 @@ ir::Statement *ParserImpl::ParseBreakStatement() } auto *breakStatement = AllocNode(); - ES2PANDA_ASSERT(breakStatement); + ES2PANDA_ASSERT(breakStatement != nullptr); breakStatement->SetRange({startLoc, lexer_->GetToken().End()}); if (lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_SEMI_COLON) { @@ -551,6 +551,7 @@ ir::Statement *ParserImpl::ParseContinueStatement() if (lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_SEMI_COLON) { auto *continueStatement = AllocNode(); + ES2PANDA_ASSERT(continueStatement != nullptr); continueStatement->SetRange({startLoc, lexer_->GetToken().End()}); lexer_->NextToken(); return continueStatement; @@ -559,6 +560,7 @@ ir::Statement *ParserImpl::ParseContinueStatement() if (lexer_->GetToken().NewLine() || lexer_->GetToken().Type() == lexer::TokenType::EOS || lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_RIGHT_BRACE) { auto *continueStatement = AllocNode(); + ES2PANDA_ASSERT(continueStatement != nullptr); continueStatement->SetRange({startLoc, endLoc}); return continueStatement; } @@ -576,7 +578,7 @@ ir::Statement *ParserImpl::ParseContinueStatement() identNode->SetRange(lexer_->GetToken().Loc()); auto *continueStatement = AllocNode(identNode); - ES2PANDA_ASSERT(continueStatement); + ES2PANDA_ASSERT(continueStatement != nullptr); continueStatement->SetRange({startLoc, lexer_->GetToken().End()}); lexer_->NextToken(); @@ -625,7 +627,7 @@ ir::Statement *ParserImpl::ParseDoWhileStatement() ExpectToken(lexer::TokenType::PUNCTUATOR_RIGHT_PARENTHESIS); auto *doWhileStatement = AllocNode(body, condition); - ES2PANDA_ASSERT(doWhileStatement); + ES2PANDA_ASSERT(doWhileStatement != nullptr); doWhileStatement->SetRange({startLoc, endLoc}); if (lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_SEMI_COLON) { @@ -672,7 +674,7 @@ ir::FunctionDeclaration *ParserImpl::ParseFunctionDeclaration(bool canBeAnonymou newStatus |= ParserStatus::FUNCTION_DECLARATION; ir::ScriptFunction *func = ParseFunction(newStatus | ParserStatus::NEED_RETURN_TYPE); - ES2PANDA_ASSERT(func); + ES2PANDA_ASSERT(func != nullptr); func->SetIdent(identNode); func->SetStart(startLoc); @@ -729,7 +731,7 @@ ir::Statement *ParserImpl::ParseExpressionStatement(StatementParsingFlags flags) lexer::SourcePosition endPos = exprNode->End(); auto *exprStatementNode = AllocNode(exprNode); - ES2PANDA_ASSERT(exprStatementNode); + ES2PANDA_ASSERT(exprStatementNode != nullptr); exprStatementNode->SetRange({startPos.GetToken().Start(), endPos}); ConsumeSemicolon(exprStatementNode); @@ -860,7 +862,7 @@ std::tuple ir::AstNode *initNode = lexer_->GetToken().Type() == lexer::TokenType::PUNCTUATOR_COMMA ? ParseSequenceExpression(expr) : expr; - ES2PANDA_ASSERT(initNode); + ES2PANDA_ASSERT(initNode != nullptr); if (initNode->IsConditionalExpression()) { ir::ConditionalExpression *condExpr = initNode->AsConditionalExpression(); @@ -1013,7 +1015,7 @@ ir::Statement *ParserImpl::CreateForStatement(ForStatementNodes &&nodes, ForStat } } - ES2PANDA_ASSERT(forStatement); + ES2PANDA_ASSERT(forStatement != nullptr); forStatement->SetRange({startLoc, nodes.body->End()}); return forStatement; @@ -1091,7 +1093,7 @@ ir::Statement *ParserImpl::ParseIfStatement() } auto *ifStatement = AllocNode(test, consequent, alternate); - ES2PANDA_ASSERT(ifStatement); + ES2PANDA_ASSERT(ifStatement != nullptr); ifStatement->SetRange({startLoc, endLoc}); return ifStatement; } @@ -1111,6 +1113,7 @@ ir::Statement *ParserImpl::ParseLabelledStatement(const lexer::LexerPosition &po SavedParserContext newCtx(this, ParserStatus::IN_LABELED, actualLabel); auto *identNode = AllocNode(actualLabel, Allocator()); + ES2PANDA_ASSERT(identNode != nullptr); identNode->SetRange(pos.GetToken().Loc()); lexer_->NextToken(); @@ -1122,7 +1125,7 @@ ir::Statement *ParserImpl::ParseLabelledStatement(const lexer::LexerPosition &po ir::Statement *body = ParseStatement(StatementParsingFlags::LABELLED); auto *labeledStatement = AllocNode(identNode, body); - ES2PANDA_ASSERT(labeledStatement); + ES2PANDA_ASSERT(labeledStatement != nullptr); labeledStatement->SetRange({pos.GetToken().Start(), body->End()}); return labeledStatement; @@ -1162,7 +1165,7 @@ ir::Statement *ParserImpl::ParseReturnStatement() returnStatement = AllocNode(); } - ES2PANDA_ASSERT(returnStatement); + ES2PANDA_ASSERT(returnStatement != nullptr); returnStatement->SetRange({startLoc, endLoc}); ConsumeSemicolon(returnStatement); @@ -1218,7 +1221,7 @@ ir::SwitchCaseStatement *ParserImpl::ParseSwitchCaseStatement(bool *seenDefault) } auto *caseNode = AllocNode(testExpr, std::move(consequents)); - ES2PANDA_ASSERT(caseNode); + ES2PANDA_ASSERT(caseNode != nullptr); caseNode->SetRange({caseStartLoc, caseEndLoc}); return caseNode; } @@ -1250,7 +1253,7 @@ ir::Statement *ParserImpl::ParseSwitchStatement() ExpectToken(lexer::TokenType::PUNCTUATOR_RIGHT_BRACE); auto *switchStatement = AllocNode(discriminant, std::move(cases)); - ES2PANDA_ASSERT(switchStatement); + ES2PANDA_ASSERT(switchStatement != nullptr); switchStatement->SetRange({startLoc, endLoc}); return switchStatement; } @@ -1275,7 +1278,7 @@ ir::Statement *ParserImpl::ParseThrowStatement() lexer::SourcePosition endLoc = expression->End(); auto *throwStatement = AllocNode(expression); - ES2PANDA_ASSERT(throwStatement); + ES2PANDA_ASSERT(throwStatement != nullptr); throwStatement->SetRange({startLoc, endLoc}); ConsumeSemicolon(throwStatement); @@ -1327,10 +1330,11 @@ ir::CatchClause *ParserImpl::ParseCatchClause() } ir::BlockStatement *catchBlock = ParseBlockStatement(); + ES2PANDA_ASSERT(catchBlock != nullptr); lexer::SourcePosition endLoc = catchBlock->End(); auto *catchClause = AllocNode(param, catchBlock); - ES2PANDA_ASSERT(catchClause); + ES2PANDA_ASSERT(catchClause != nullptr); catchClause->SetRange({catchStartLoc, endLoc}); return catchClause; @@ -1375,7 +1379,7 @@ ir::Statement *ParserImpl::ParseTryStatement() lexer_->NextToken(); // eat 'finally' keyword finallyClause = ParseBlockStatement(); - ES2PANDA_ASSERT(finallyClause); + ES2PANDA_ASSERT(finallyClause != nullptr); endLoc = finallyClause->End(); } @@ -1546,7 +1550,7 @@ ir::Statement *ParserImpl::ParseVariableDeclaration(VariableParsingFlags flags) lexer::SourcePosition endLoc = declarators.back()->End(); auto *declaration = AllocNode(varKind, Allocator(), std::move(declarators)); - ES2PANDA_ASSERT(declaration); + ES2PANDA_ASSERT(declaration != nullptr); declaration->SetRange({startLoc, endLoc}); return declaration; @@ -1574,7 +1578,7 @@ ir::Statement *ParserImpl::ParseWhileStatement() lexer::SourcePosition endLoc = body->End(); auto *whileStatement = AllocNode(condition, body); - ES2PANDA_ASSERT(whileStatement); + ES2PANDA_ASSERT(whileStatement != nullptr); whileStatement->SetRange({startLoc, endLoc}); return whileStatement; @@ -1625,7 +1629,7 @@ ir::ExportDefaultDeclaration *ParserImpl::ParseExportDefaultDeclaration(const le ES2PANDA_ASSERT(declNode != nullptr); lexer::SourcePosition endLoc = declNode->End(); auto *exportDeclaration = AllocNode(declNode, isExportEquals); - ES2PANDA_ASSERT(exportDeclaration); + ES2PANDA_ASSERT(exportDeclaration != nullptr); exportDeclaration->SetRange({startLoc, endLoc}); if (eatSemicolon) { @@ -1649,7 +1653,7 @@ ir::Identifier *ParserImpl::ParseNamedExport(lexer::Token *exportedToken) const util::StringView &exportedString = exportedToken->Ident(); auto *exported = AllocNode(exportedString, Allocator()); - ES2PANDA_ASSERT(exported); + ES2PANDA_ASSERT(exported != nullptr); exported->SetRange(exportedToken->Loc()); return exported; @@ -1667,11 +1671,11 @@ ir::ExportAllDeclaration *ParserImpl::ParseExportAllDeclaration(const lexer::Sou lexer_->NextToken(); // eat exported name } ir::StringLiteral *source = ParseFromClause(); - ES2PANDA_ASSERT(source); + ES2PANDA_ASSERT(source != nullptr); lexer::SourcePosition endLoc = source->End(); auto *exportDeclaration = AllocNode(source, exported); - ES2PANDA_ASSERT(exportDeclaration); + ES2PANDA_ASSERT(exportDeclaration != nullptr); exportDeclaration->SetRange({startLoc, endLoc}); ConsumeSemicolon(exportDeclaration); @@ -1726,7 +1730,7 @@ ir::ExportNamedDeclaration *ParserImpl::ParseExportNamedSpecifiers(const lexer:: } auto *exportDeclaration = AllocNode(Allocator(), source, std::move(specifiers)); - ES2PANDA_ASSERT(exportDeclaration); + ES2PANDA_ASSERT(exportDeclaration != nullptr); exportDeclaration->SetRange({startLoc, endPos}); ConsumeSemicolon(exportDeclaration); @@ -1781,7 +1785,7 @@ ir::Statement *ParserImpl::ParseNamedExportDeclaration(const lexer::SourcePositi lexer::SourcePosition endLoc = decl->End(); ArenaVector specifiers(Allocator()->Adapter()); auto *exportDeclaration = AllocNode(Allocator(), decl, std::move(specifiers)); - ES2PANDA_ASSERT(exportDeclaration); + ES2PANDA_ASSERT(exportDeclaration != nullptr); exportDeclaration->SetRange({startLoc, endLoc}); return exportDeclaration; @@ -1830,7 +1834,7 @@ void ParserImpl::ParseNameSpaceImport(ArenaVector *specifiers) ir::Identifier *local = ParseNamedImport(&lexer_->GetToken()); auto *specifier = AllocNode(local); - ES2PANDA_ASSERT(specifier); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange({namespaceStart, lexer_->GetToken().End()}); specifiers->push_back(specifier); @@ -1848,7 +1852,7 @@ ir::Identifier *ParserImpl::ParseNamedImport(lexer::Token *importedToken) CheckRestrictedBinding(importedToken->KeywordType()); auto *local = AllocNode(importedToken->Ident(), Allocator()); - ES2PANDA_ASSERT(local); + ES2PANDA_ASSERT(local != nullptr); local->SetRange(importedToken->Loc()); return local; @@ -1895,7 +1899,7 @@ ir::AstNode *ParserImpl::ParseImportDefaultSpecifier(ArenaVector lexer_->NextToken(); // eat local name auto *specifier = AllocNode(local); - ES2PANDA_ASSERT(specifier); + ES2PANDA_ASSERT(specifier != nullptr); specifier->SetRange(specifier->Local()->Range()); specifiers->push_back(specifier); @@ -1928,7 +1932,7 @@ ir::StringLiteral *ParserImpl::ParseFromClause(bool requireFrom) } auto *source = AllocNode(lexer_->GetToken().String()); - ES2PANDA_ASSERT(source); + ES2PANDA_ASSERT(source != nullptr); source->SetRange(lexer_->GetToken().Loc()); lexer_->NextToken(); @@ -1987,7 +1991,7 @@ ir::Statement *ParserImpl::ParseImportDeclaration(StatementParsingFlags flags) lexer::SourcePosition endLoc = source->End(); auto *importDeclaration = AllocNode(source, std::move(specifiers)); - ES2PANDA_ASSERT(importDeclaration); + ES2PANDA_ASSERT(importDeclaration != nullptr); importDeclaration->SetRange({startLoc, endLoc}); ConsumeSemicolon(importDeclaration); @@ -2003,7 +2007,7 @@ ir::Statement *ParserImpl::AllocBrokenStatement(const lexer::SourcePosition &pos ir::Statement *ParserImpl::AllocBrokenStatement(const lexer::SourceRange &range) { auto *broken = AllocNode(true); - ES2PANDA_ASSERT(broken); + ES2PANDA_ASSERT(broken != nullptr); broken->SetRange(range); return broken; } @@ -2019,7 +2023,7 @@ bool ParserImpl::IsBrokenStatement(ir::Statement *st) ir::Statement *ParserImpl::AllocEmptyStatement() { auto *empty = AllocNode(); - ES2PANDA_ASSERT(empty); + ES2PANDA_ASSERT(empty != nullptr); empty->SetRange(lexer_->GetToken().Loc()); return empty; } diff --git a/ets2panda/parser/statementTSParser.cpp b/ets2panda/parser/statementTSParser.cpp index 2a4840d461..4cd60c24db 100644 --- a/ets2panda/parser/statementTSParser.cpp +++ b/ets2panda/parser/statementTSParser.cpp @@ -131,7 +131,7 @@ ir::TSImportEqualsDeclaration *TSParser::ParseTsImportEqualsDeclaration(const le } auto *id = AllocNode(Lexer()->GetToken().Ident(), Allocator()); - ES2PANDA_ASSERT(id); + ES2PANDA_ASSERT(id != nullptr); id->SetRange(Lexer()->GetToken().Loc()); Lexer()->NextToken(); // eat id name @@ -191,7 +191,7 @@ ir::ExportDefaultDeclaration *TSParser::ParseExportDefaultDeclaration(const lexe lexer::SourcePosition endLoc = declNode->End(); auto *exportDeclaration = AllocNode(declNode, isExportEquals); - ES2PANDA_ASSERT(exportDeclaration); + ES2PANDA_ASSERT(exportDeclaration != nullptr); exportDeclaration->SetRange({startLoc, endLoc}); if (eatSemicolon) { @@ -267,7 +267,7 @@ ir::Statement *TSParser::ParseNamedExportDeclaration(const lexer::SourcePosition lexer::SourcePosition endLoc = decl->End(); ArenaVector specifiers(Allocator()->Adapter()); auto *exportDeclaration = AllocNode(Allocator(), decl, std::move(specifiers)); - ES2PANDA_ASSERT(exportDeclaration); + ES2PANDA_ASSERT(exportDeclaration != nullptr); exportDeclaration->SetRange({startLoc, endLoc}); return exportDeclaration; @@ -296,7 +296,7 @@ ir::Statement *TSParser::ParseExportDeclaration(StatementParsingFlags flags) } default: { auto ret = ParseNamedExportDeclaration(startLoc); - ES2PANDA_ASSERT(ret); + ES2PANDA_ASSERT(ret != nullptr); if (ret->IsBrokenStatement()) { return ret; } @@ -326,7 +326,7 @@ ir::Statement *TSParser::ParseConstStatement(StatementParsingFlags flags) } auto *variableDecl = ParseVariableDeclaration(VariableParsingFlags::CONST | VariableParsingFlags::NO_SKIP_VAR_KIND); - ES2PANDA_ASSERT(variableDecl); + ES2PANDA_ASSERT(variableDecl != nullptr); variableDecl->SetStart(constVarStar); ConsumeSemicolon(variableDecl); @@ -369,7 +369,7 @@ ir::Statement *TSParser::ParseImportDeclaration([[maybe_unused]] StatementParsin source = ParseFromClause(false); } - ES2PANDA_ASSERT(source); + ES2PANDA_ASSERT(source != nullptr); lexer::SourcePosition endLoc = source->End(); auto *importDeclaration = AllocNode(source, std::move(specifiers)); importDeclaration->SetRange({startLoc, endLoc}); -- Gitee From 313a729c2120955c5caa160d2e4aba1b4d84074b Mon Sep 17 00:00:00 2001 From: lihao Date: Thu, 22 May 2025 23:08:37 +0800 Subject: [PATCH 106/145] File-based hybrid compilation 0603 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICJ9SU Signed-off-by: lihao Change-Id: I78d2de025868419775f8ba10d63ccabb9fff60a1 --- .../build_system/src/build/base_mode.ts | 31 +++++++--- .../build_system/src/build/declgen_worker.ts | 4 +- .../src/build/generate_arktsconfig.ts | 60 +++++++++++++++---- .../driver/build_system/src/error_code.ts | 4 +- 4 files changed, 77 insertions(+), 22 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index 745a5482da..f7ee9c8d3e 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -353,16 +353,16 @@ export abstract class BaseMode { } private getDependentModules(moduleInfo: ModuleInfo): Map[] { - const dynamicDepModules: Map = new Map(); - const staticDepModules: Map = new Map(); + let dynamicDepModules: Map = new Map(); + let staticDepModules: Map = new Map(); + this.collectDependencyModules(moduleInfo.packageName, moduleInfo, dynamicDepModules, staticDepModules); 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); + this.collectDependencyModules(packageName, module, dynamicDepModules, staticDepModules); }); return [dynamicDepModules, staticDepModules]; } @@ -377,17 +377,32 @@ export abstract class BaseMode { ); this.logger.printErrorAndExit(logData); } else { - depModuleInfo.language === LANGUAGE_VERSION.ARKTS_1_2 ? - staticDepModules.set(packageName, depModuleInfo) : dynamicDepModules.set(packageName, depModuleInfo); + this.collectDependencyModules(packageName, depModuleInfo, dynamicDepModules, staticDepModules); } }); } return [dynamicDepModules, staticDepModules]; } + private collectDependencyModules( + packageName: string, + module: ModuleInfo, + dynamicDepModules: Map, + staticDepModules: Map + ): void { + if (module.language === LANGUAGE_VERSION.ARKTS_1_2) { + staticDepModules.set(packageName, module); + } else if (module.language === LANGUAGE_VERSION.ARKTS_1_1) { + dynamicDepModules.set(packageName, module); + } else if (module.language === LANGUAGE_VERSION.ARKTS_HYBRID) { + staticDepModules.set(packageName, module); + dynamicDepModules.set(packageName, module); + } + } + protected generateArkTSConfigForModules(): void { - this.moduleInfos.forEach((moduleInfo: ModuleInfo, _: string) => { - ArkTSConfigGenerator.getInstance(this.buildConfig, this.moduleInfos).writeArkTSConfigFile(moduleInfo); + this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { + ArkTSConfigGenerator.getInstance(this.buildConfig, this.moduleInfos).writeArkTSConfigFile(moduleInfo, this.enableDeclgenEts2Ts); }); } diff --git a/ets2panda/driver/build_system/src/build/declgen_worker.ts b/ets2panda/driver/build_system/src/build/declgen_worker.ts index 135acab0dd..663d0363bb 100644 --- a/ets2panda/driver/build_system/src/build/declgen_worker.ts +++ b/ets2panda/driver/build_system/src/build/declgen_worker.ts @@ -78,13 +78,13 @@ process.on('message', (message: { arktsGlobal.compilerContext = arkts.Context.createFromString(source); pluginDriver.getPluginContext().setArkTSProgram(arktsGlobal.compilerContext.program); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, true); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, arktsGlobal.compilerContext.peer, true); let ast = arkts.EtsScript.fromContext(); pluginDriver.getPluginContext().setArkTSAst(ast); pluginDriver.runPluginHook(PluginHook.PARSED); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, true); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, arktsGlobal.compilerContext.peer, true); ast = arkts.EtsScript.fromContext(); pluginDriver.getPluginContext().setArkTSAst(ast); diff --git a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts index 6cac43bb3e..197b6efdd6 100644 --- a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts +++ b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts @@ -49,7 +49,7 @@ interface ArkTSConfigObject { baseUrl: string, paths: Record; dependencies: string[] | undefined; - entry: string; + entry?: string; dynamicPaths: Record; useEmptyPackage?: boolean; } @@ -152,17 +152,40 @@ export class ArkTSConfigGenerator { 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]) - ]; - } - + if (moduleInfo.language !== LANGUAGE_VERSION.ARKTS_1_2 && moduleInfo.language !== LANGUAGE_VERSION.ARKTS_HYBRID) { + return; + } + if (!moduleInfo.entryFile) { + return; + } + this.handleEntryFile(moduleInfo); }); - return this.pathSection; } + private handleEntryFile(moduleInfo: ModuleInfo): void { + try { + const stat = fs.statSync(moduleInfo.entryFile); + if (!stat.isFile()) { + return; + } + const entryFilePath = moduleInfo.entryFile; + const firstLine = fs.readFileSync(entryFilePath, 'utf-8').split('\n')[0]; + // If the file is an ArkTS 1.2 implementation, configure the path in pathSection. + if (moduleInfo.language === LANGUAGE_VERSION.ARKTS_1_2 || moduleInfo.language === LANGUAGE_VERSION.ARKTS_HYBRID && firstLine.includes('use static')) { + this.pathSection[moduleInfo.packageName] = [ + path.resolve(moduleInfo.moduleRootPath, moduleInfo.sourceRoots[0]) + ]; + } + } catch (error) { + const logData: LogData = LogDataFactory.newInstance( + ErrorCode.BUILDSYSTEM_HANDLE_ENTRY_FILE, + `Error handle entry file for module ${moduleInfo.packageName}` + ); + this.logger.printError(logData); + } + } + private getDependenciesSection(moduleInfo: ModuleInfo, dependenciesSection: string[]): void { let depModules: Map = moduleInfo.staticDepModuleInfos; depModules.forEach((depModuleInfo: ModuleInfo) => { @@ -203,7 +226,7 @@ export class ArkTSConfigGenerator { }); } - public writeArkTSConfigFile(moduleInfo: ModuleInfo): void { + public writeArkTSConfigFile(moduleInfo: ModuleInfo, enableDeclgenEts2Ts: boolean): void { if (!moduleInfo.sourceRoots || moduleInfo.sourceRoots.length === 0) { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_SOURCEROOTS_NOT_SET_FAIL, @@ -214,9 +237,11 @@ export class ArkTSConfigGenerator { let pathSection = this.getPathSection(); let dependenciesSection: string[] = []; this.getDependenciesSection(moduleInfo, dependenciesSection); - let dynamicPathSection: Record = {}; - this.getDynamicPathSection(moduleInfo, dynamicPathSection); + + if (!enableDeclgenEts2Ts) { + this.getDynamicPathSection(moduleInfo, dynamicPathSection); + } let baseUrl: string = path.resolve(moduleInfo.moduleRootPath, moduleInfo.sourceRoots[0]); let arktsConfig: ArkTSConfigObject = { @@ -229,6 +254,19 @@ export class ArkTSConfigGenerator { dynamicPaths: dynamicPathSection } }; + + if (moduleInfo.entryFile && moduleInfo.language === LANGUAGE_VERSION.ARKTS_HYBRID) { + const entryFilePath = moduleInfo.entryFile; + const stat = fs.statSync(entryFilePath); + if (fs.existsSync(entryFilePath) && stat.isFile()) { + const firstLine = fs.readFileSync(entryFilePath, 'utf-8').split('\n')[0]; + // If the entryFile is not an ArkTS 1.2 implementation, remove the entry property field. + if (!firstLine.includes('use static')) { + delete arktsConfig.compilerOptions.entry; + } + } + } + if (moduleInfo.frameworkMode) { arktsConfig.compilerOptions.useEmptyPackage = moduleInfo.useEmptyPackage; } diff --git a/ets2panda/driver/build_system/src/error_code.ts b/ets2panda/driver/build_system/src/error_code.ts index 5a0dc72b4c..25da0af026 100644 --- a/ets2panda/driver/build_system/src/error_code.ts +++ b/ets2panda/driver/build_system/src/error_code.ts @@ -34,5 +34,7 @@ export enum ErrorCode { BUILDSYSTEM_DECLGEN_FAIL = '11410013', BUILDSYSTEM_LOAD_HASH_CACHE_FAIL = '11410014', BUILDSYSTEM_Dependency_Analyze_FAIL = '11410015', - BUILDSYSTEM_Dependency_Analyzer_NOT_FOUND_FAIL = '11410016' + BUILDSYSTEM_Dependency_Analyzer_NOT_FOUND_FAIL = '11410016', + BUILDSYSTEM_ABC_FILE_MISSING_IN_BCHAR = '11410017', + BUILDSYSTEM_HANDLE_ENTRY_FILE = '11410018', } -- Gitee From d9c152c6d67c5dcbf85cbba4ab1826399a302c8b Mon Sep 17 00:00:00 2001 From: zmw Date: Tue, 8 Jul 2025 23:06:10 +0800 Subject: [PATCH 107/145] Fix switchCase clone crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKWR1 Description: Fix switchCase clone crash Signed-off-by: zmw --- ets2panda/parser/statementParser.cpp | 1 + ...lid_switch_case_in_function_assignment.ets | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/invalid_switch_case_in_function_assignment.ets diff --git a/ets2panda/parser/statementParser.cpp b/ets2panda/parser/statementParser.cpp index 3fefb15d68..f3ed113968 100644 --- a/ets2panda/parser/statementParser.cpp +++ b/ets2panda/parser/statementParser.cpp @@ -1198,6 +1198,7 @@ ir::SwitchCaseStatement *ParserImpl::ParseSwitchCaseStatement(bool *seenDefault) default: { LogError(diagnostic::UNEXPECTED_TOKEN_PARAM_EXPECTED_CASE_OR_DEFAULT, {lexer::TokenToString(lexer_->GetToken().Type())}); + testExpr = AllocBrokenExpression(caseStartLoc); } } diff --git a/ets2panda/test/ast/compiler/ets/invalid_switch_case_in_function_assignment.ets b/ets2panda/test/ast/compiler/ets/invalid_switch_case_in_function_assignment.ets new file mode 100644 index 0000000000..37691e5067 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/invalid_switch_case_in_function_assignment.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. + */ + +let a = foo() { + switch (x) { + "unreachable" + } +} + +/* @@? 16:9 Error TypeError: Unresolved reference foo */ +/* @@? 16:9 Error TypeError: This expression is not callable. */ +/* @@? 18:9 Error SyntaxError: Unexpected token 'string literal', expected 'case' or 'default'. */ +/* @@? 18:9 Error SyntaxError: Expected ':', got 'string literal'. */ -- Gitee From c70d84fe74b5165272b9dd6a97faa8b1f02c0249 Mon Sep 17 00:00:00 2001 From: zenghang Date: Thu, 19 Jun 2025 00:27:42 +0800 Subject: [PATCH 108/145] add pathSection to support file level compile Issue: ICC75O Signed-off-by: zenghang Change-Id: Id38c7a892a217cda9d1805f2f9ad3cf5d8f225b4 --- .../build_system/src/build/base_mode.ts | 48 +++++++++++++------ .../build_system/src/build/build_mode.ts | 2 +- .../build_system/src/build/declgen_worker.ts | 4 +- .../src/build/generate_arktsconfig.ts | 38 ++++++++++++++- ets2panda/driver/build_system/src/types.ts | 7 +++ ets2panda/driver/build_system/src/utils.ts | 6 +++ 6 files changed, 85 insertions(+), 20 deletions(-) diff --git a/ets2panda/driver/build_system/src/build/base_mode.ts b/ets2panda/driver/build_system/src/build/base_mode.ts index f7ee9c8d3e..1c05abf17a 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -85,6 +85,7 @@ export abstract class BaseMode { public isDebug: boolean; public enableDeclgenEts2Ts: boolean; public declgenV1OutPath: string | undefined; + public declgenV2OutPath: string | undefined; public declgenBridgeCodePath: string | undefined; public hasMainModule: boolean; public abcFiles: Set; @@ -93,6 +94,7 @@ export abstract class BaseMode { public isCacheFileExists: boolean; public dependencyFileMap: DependencyFileConfig | null; public isBuildConfigModified: boolean | undefined; + public byteCodeHar: boolean; constructor(buildConfig: BuildConfig) { this.buildConfig = buildConfig; @@ -116,6 +118,7 @@ export abstract class BaseMode { this.isDebug = buildConfig.buildMode as string === BUILD_MODE.DEBUG; this.enableDeclgenEts2Ts = buildConfig.enableDeclgenEts2Ts as boolean; this.declgenV1OutPath = buildConfig.declgenV1OutPath as string | undefined; + this.declgenV2OutPath = buildConfig.declgenV2OutPath as string | undefined; this.declgenBridgeCodePath = buildConfig.declgenBridgeCodePath as string | undefined; this.hasMainModule = buildConfig.hasMainModule; this.abcFiles = new Set(); @@ -124,6 +127,7 @@ export abstract class BaseMode { this.isCacheFileExists = fs.existsSync(this.hashCacheFile); this.dependencyFileMap = null; this.isBuildConfigModified = buildConfig.isBuildConfigModified as boolean | undefined; + this.byteCodeHar = buildConfig.byteCodeHar as boolean; } public declgen(fileInfo: CompileFileInfo): void { @@ -364,6 +368,9 @@ export abstract class BaseMode { } this.collectDependencyModules(packageName, module, dynamicDepModules, staticDepModules); }); + if (moduleInfo.language === LANGUAGE_VERSION.ARKTS_HYBRID) { + dynamicDepModules.set(moduleInfo.packageName, moduleInfo); + } return [dynamicDepModules, staticDepModules]; } @@ -402,7 +409,8 @@ export abstract class BaseMode { protected generateArkTSConfigForModules(): void { this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { - ArkTSConfigGenerator.getInstance(this.buildConfig, this.moduleInfos).writeArkTSConfigFile(moduleInfo, this.enableDeclgenEts2Ts); + ArkTSConfigGenerator.getInstance(this.buildConfig, this.moduleInfos) + .writeArkTSConfigFile(moduleInfo, this.enableDeclgenEts2Ts, this.buildConfig); }); } @@ -432,7 +440,10 @@ export abstract class BaseMode { ); this.logger.printError(logData); } - const moduleInfo: ModuleInfo = { + if (this.moduleInfos.has(module.packageName)) { + return; + } + let moduleInfo: ModuleInfo = { isMainModule: false, packageName: module.packageName, moduleRootPath: module.modulePath, @@ -444,9 +455,11 @@ export abstract class BaseMode { dynamicDepModuleInfos: new Map(), staticDepModuleInfos: new Map(), declgenV1OutPath: module.declgenV1OutPath, + declgenV2OutPath: module.declgenV2OutPath, declgenBridgeCodePath: module.declgenBridgeCodePath, language: module.language, declFilesPath: module.declFilesPath, + byteCodeHar: module.byteCodeHar, dependencies: module.dependencies }; this.moduleInfos.set(module.packageName, moduleInfo); @@ -455,19 +468,24 @@ export abstract class BaseMode { } protected getMainModuleInfo(): ModuleInfo { + const mainModuleInfo = this.dependentModuleList.find((module: DependentModuleConfig) => module.packageName === this.packageName); return { - 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 + 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, + declgenV2OutPath: this.declgenV2OutPath, + declgenBridgeCodePath: this.declgenBridgeCodePath, + byteCodeHar: this.byteCodeHar, + language: mainModuleInfo?.language ?? LANGUAGE_VERSION.ARKTS_1_2, + declFilesPath: mainModuleInfo?.declFilesPath, }; } @@ -773,7 +791,7 @@ export abstract class BaseMode { } } - public async runParallell(): Promise { + public async runParallel(): Promise { this.generateModuleInfos(); if (!cluster.isPrimary) { diff --git a/ets2panda/driver/build_system/src/build/build_mode.ts b/ets2panda/driver/build_system/src/build/build_mode.ts index 59bdb759ab..a8bfd42778 100644 --- a/ets2panda/driver/build_system/src/build/build_mode.ts +++ b/ets2panda/driver/build_system/src/build/build_mode.ts @@ -26,6 +26,6 @@ export class BuildMode extends BaseMode { } public async run(): Promise { - await super.runParallell(); + await super.runParallel(); } } \ No newline at end of file diff --git a/ets2panda/driver/build_system/src/build/declgen_worker.ts b/ets2panda/driver/build_system/src/build/declgen_worker.ts index 663d0363bb..135acab0dd 100644 --- a/ets2panda/driver/build_system/src/build/declgen_worker.ts +++ b/ets2panda/driver/build_system/src/build/declgen_worker.ts @@ -78,13 +78,13 @@ process.on('message', (message: { arktsGlobal.compilerContext = arkts.Context.createFromString(source); pluginDriver.getPluginContext().setArkTSProgram(arktsGlobal.compilerContext.program); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, arktsGlobal.compilerContext.peer, true); + 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, arktsGlobal.compilerContext.peer, true); + arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, true); ast = arkts.EtsScript.fromContext(); pluginDriver.getPluginContext().setArkTSAst(ast); diff --git a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts index 197b6efdd6..edb1224fb7 100644 --- a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts +++ b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts @@ -26,7 +26,9 @@ import { } from '../error_code'; import { changeFileExtension, - ensurePathExists + ensurePathExists, + isSubPathOf, + toUnixPath } from '../utils'; import { BuildConfig, @@ -226,7 +228,11 @@ export class ArkTSConfigGenerator { }); } - public writeArkTSConfigFile(moduleInfo: ModuleInfo, enableDeclgenEts2Ts: boolean): void { + public writeArkTSConfigFile( + moduleInfo: ModuleInfo, + enableDeclgenEts2Ts: boolean, + buildConfig: BuildConfig + ): void { if (!moduleInfo.sourceRoots || moduleInfo.sourceRoots.length === 0) { const logData: LogData = LogDataFactory.newInstance( ErrorCode.BUILDSYSTEM_SOURCEROOTS_NOT_SET_FAIL, @@ -237,6 +243,8 @@ export class ArkTSConfigGenerator { let pathSection = this.getPathSection(); let dependenciesSection: string[] = []; this.getDependenciesSection(moduleInfo, dependenciesSection); + this.getAllFilesToPathSectionForHybrid(moduleInfo, buildConfig); + let dynamicPathSection: Record = {}; if (!enableDeclgenEts2Ts) { @@ -274,4 +282,30 @@ export class ArkTSConfigGenerator { ensurePathExists(moduleInfo.arktsConfigFile); fs.writeFileSync(moduleInfo.arktsConfigFile, JSON.stringify(arktsConfig, null, 2), 'utf-8'); } + + public getAllFilesToPathSectionForHybrid( + moduleInfo: ModuleInfo, + buildConfig: BuildConfig + ): void { + if (moduleInfo?.language !== LANGUAGE_VERSION.ARKTS_HYBRID) { + return; + } + + const projectRoot = toUnixPath(buildConfig.projectRootPath) + '/'; + const moduleRoot = toUnixPath(moduleInfo.moduleRootPath); + + for (const file of buildConfig.compileFiles) { + const unixFilePath = toUnixPath(file); + + if (!isSubPathOf(unixFilePath, moduleRoot)) { + continue; + } + + let relativePath = unixFilePath.startsWith(projectRoot) + ? unixFilePath.substring(projectRoot.length) + : unixFilePath; + const keyWithoutExtension = relativePath.replace(/\.[^/.]+$/, ''); + this.pathSection[keyWithoutExtension] = [file]; + } + } } diff --git a/ets2panda/driver/build_system/src/types.ts b/ets2panda/driver/build_system/src/types.ts index 7a49cc64f5..37745789b4 100644 --- a/ets2panda/driver/build_system/src/types.ts +++ b/ets2panda/driver/build_system/src/types.ts @@ -74,6 +74,7 @@ export interface ModuleConfig { moduleType: string; moduleRootPath: string; sourceRoots: string[]; + byteCodeHar: boolean; } export interface PathConfig { @@ -85,6 +86,7 @@ export interface PathConfig { externalApiPaths: string[]; abcLinkerPath?: string; dependencyAnalyzerPath?: string; + projectRootPath: string; } /** @@ -111,6 +113,7 @@ export interface FrameworkConfig { export interface DeclgenConfig { enableDeclgenEts2Ts: boolean; declgenV1OutPath?: string; + declgenV2OutPath?: string; declgenBridgeCodePath?: string; } @@ -129,7 +132,9 @@ export interface DependentModuleConfig { declFilesPath?: string; dependencies?: string[]; declgenV1OutPath?: string; + declgenV2OutPath?: string; declgenBridgeCodePath?: string; + byteCodeHar: boolean; } export interface BuildConfig extends BuildBaseConfig, DeclgenConfig, LoggerConfig, ModuleConfig, PathConfig, FrameworkConfig { @@ -157,6 +162,7 @@ export interface ModuleInfo { arktsConfigFile: string, compileFileInfos: CompileFileInfo[], declgenV1OutPath: string | undefined, + declgenV2OutPath: string | undefined, declgenBridgeCodePath: string | undefined, dependencies?: string[] staticDepModuleInfos: Map; @@ -165,6 +171,7 @@ export interface ModuleInfo { declFilesPath?: string; frameworkMode?: boolean; useEmptyPackage?: boolean; + byteCodeHar: boolean; } export type SetupClusterOptions = { diff --git a/ets2panda/driver/build_system/src/utils.ts b/ets2panda/driver/build_system/src/utils.ts index 2e6919a9a9..45698b054b 100644 --- a/ets2panda/driver/build_system/src/utils.ts +++ b/ets2panda/driver/build_system/src/utils.ts @@ -82,3 +82,9 @@ export function readFirstLineSync(filePath: string): string | null { return firstLine; } + +export function isSubPathOf(targetPath: string, parentDir: string): boolean { + const resolvedParent = toUnixPath(path.resolve(parentDir)); + const resolvedTarget = toUnixPath(path.resolve(targetPath)); + return resolvedTarget === resolvedParent || resolvedTarget.startsWith(resolvedParent + '/'); +} -- Gitee From 653f9226144d92b4281df7db0e09d4dcc08b7f3b Mon Sep 17 00:00:00 2001 From: oh-rgx Date: Wed, 9 Jul 2025 16:31:54 +0800 Subject: [PATCH 109/145] Fix createPartial crash Issue: #ICL4IM Signed-off-by: oh-rgx --- ets2panda/parser/ETSparserClasses.cpp | 3 +- .../ast/compiler/ets/interface_partial.ets | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/interface_partial.ets diff --git a/ets2panda/parser/ETSparserClasses.cpp b/ets2panda/parser/ETSparserClasses.cpp index a1cbd70d36..9169fcc0f2 100644 --- a/ets2panda/parser/ETSparserClasses.cpp +++ b/ets2panda/parser/ETSparserClasses.cpp @@ -994,7 +994,8 @@ ir::ModifierFlags ETSParser::ParseInterfaceMethodModifiers() ir::TypeNode *ETSParser::ParseInterfaceTypeAnnotation(ir::Identifier *name) { if (!Lexer()->TryEatTokenType(lexer::TokenType::PUNCTUATOR_COLON) && - Lexer()->GetToken().Type() != lexer::TokenType::LITERAL_IDENT) { + Lexer()->GetToken().Type() != lexer::TokenType::LITERAL_IDENT && + Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_RIGHT_BRACE) { LogError(diagnostic::INTERFACE_FIELDS_TYPE_ANNOTATION); Lexer()->GetToken().SetTokenType(lexer::TokenType::PUNCTUATOR_COLON); Lexer()->NextToken(); diff --git a/ets2panda/test/ast/compiler/ets/interface_partial.ets b/ets2panda/test/ast/compiler/ets/interface_partial.ets new file mode 100644 index 0000000000..5e85493e9d --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/interface_partial.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. + */ + +interface I { + arr +} + +function foo (bar: Partial) { + if (bar.var_one != undefined) { + bar.var_one = "asddsf"; + } +} + +function main() { + let a : I = {var_one: "initial_var_one", var_two: "initial_var_two_a"}; + foo(a.var_one); + let a : I = {var_two: "initial_var_two_b"}; + foo(break.var_one); +} + +/* @@? 18:1 Error SyntaxError: Invalid Type. */ +/* @@? 21:13 Error TypeError: Property 'var_one' does not exist on type 'I$partial' */ +/* @@? 22:13 Error TypeError: Property 'var_one' does not exist on type 'I$partial' */ +/* @@? 27:18 Error TypeError: type I has no property named var_one */ +/* @@? 28:11 Error TypeError: Property 'var_one' does not exist on type 'I' */ +/* @@? 29:9 Error TypeError: Variable 'a' has already been declared. */ +/* @@? 29:18 Error TypeError: type I has no property named var_two */ +/* @@? 30:9 Error SyntaxError: Unexpected token 'break'. */ -- Gitee From 0eefa7e44586058901815e1af20a5e6f2c474f23 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Wed, 9 Jul 2025 11:00:31 +0800 Subject: [PATCH 110/145] Fixing invalid method crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKZDA Description: After obtaining the method variable, it was not checked whether it was a TypeError, and it was directly cast to AsETSFunctionType, causing the compilation to crash. Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/checker/ETSAnalyzerHelpers.cpp | 2 +- .../ast/compiler/ets/fuzz_invalid_method.ets | 58 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/fuzz_invalid_method.ets diff --git a/ets2panda/checker/ETSAnalyzerHelpers.cpp b/ets2panda/checker/ETSAnalyzerHelpers.cpp index 8b864b8652..25830d0c36 100644 --- a/ets2panda/checker/ETSAnalyzerHelpers.cpp +++ b/ets2panda/checker/ETSAnalyzerHelpers.cpp @@ -51,7 +51,7 @@ void CheckExtensionIsShadowedInCurrentClassOrInterface(checker::ETSChecker *chec // check if there are class and interfaces' instance methods with the same name as extensions. auto *const methodVariable = objType->GetOwnProperty(methodName); - if (methodVariable == nullptr) { + if (methodVariable == nullptr || methodVariable->TsType()->IsTypeError()) { return; } diff --git a/ets2panda/test/ast/compiler/ets/fuzz_invalid_method.ets b/ets2panda/test/ast/compiler/ets/fuzz_invalid_method.ets new file mode 100644 index 0000000000..9afd798864 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzz_invalid_method.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. + */ + +function foo(this:A, p: T): T { + return this.data; +} + +class A { + data: T + constructor(p: T) { + this.data = p; + } + goo1(): T { + return this.foo(this.data); + } + + goo + return this./* @@ label */classVal; + +(): T { + return foo(this, this.data); + } + +} + +/* @@? 30:9 Error SyntaxError: Unexpected token 'return'. */ +/* @@? 30:9 Error SyntaxError: Field type annotation expected. */ +/* @@? 30:16 Error SyntaxError: Unexpected token 'this'. */ +/* @@? 30:20 Error SyntaxError: Unexpected token '.'. */ +/* @@? 30:43 Error SyntaxError: Field type annotation expected. */ +/* @@? 32:1 Error SyntaxError: Unexpected token '('. */ +/* @@? 32:2 Error SyntaxError: Unexpected token ')'. */ +/* @@? 32:3 Error SyntaxError: Unexpected token ':'. */ +/* @@? 32:7 Error SyntaxError: Field type annotation expected. */ +/* @@? 32:7 Error SyntaxError: Unexpected token '{'. */ +/* @@? 33:9 Error SyntaxError: Unexpected token 'return'. */ +/* @@? 33:19 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 33:24 Error SyntaxError: The function parameter 'this' must explicitly specify the typeAnnotation. */ +/* @@? 33:30 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 33:30 Error SyntaxError: Unexpected token '.'. */ +/* @@? 33:30 Error SyntaxError: The function parameter 'this' must explicitly specify the typeAnnotation. */ +/* @@? 33:31 Error TypeError: Variable 'data' has already been declared. */ +/* @@? 33:31 Error TypeError: Property 'data' must be accessed through 'this' */ +/* @@? 33:35 Error SyntaxError: Field type annotation expected. */ +/* @@? 33:35 Error SyntaxError: Unexpected token ')'. */ +/* @@? 36:1 Error SyntaxError: Unexpected token '}'. */ -- Gitee From fc9bcedf765b4be37abf75c2800853d4319121c0 Mon Sep 17 00:00:00 2001 From: a00917162 Date: Sun, 6 Jul 2025 17:25:49 +0300 Subject: [PATCH 111/145] Fix nullptr in async function expression Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKAUD Testing: all CI tests passed. Results are availible in gg watcher. Signed-off-by: Akmaev Aleksey --- ets2panda/parser/ETSparserExpressions.cpp | 5 ++ .../ets/async-function-expression1.ets | 54 +++++++++++++++ .../ets/async-function-expression2.ets | 66 +++++++++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/async-function-expression1.ets create mode 100644 ets2panda/test/ast/compiler/ets/async-function-expression2.ets diff --git a/ets2panda/parser/ETSparserExpressions.cpp b/ets2panda/parser/ETSparserExpressions.cpp index 94d864e473..6f7e0cb04a 100644 --- a/ets2panda/parser/ETSparserExpressions.cpp +++ b/ets2panda/parser/ETSparserExpressions.cpp @@ -687,6 +687,11 @@ ir::Expression *ETSParser::ParseNewExpression() ir::Expression *ETSParser::ParseAsyncExpression() { Lexer()->NextToken(); // eat 'async' + if (Lexer()->GetToken().Type() == lexer::TokenType::KEYW_FUNCTION) { + LogError(diagnostic::FUNC_EXPR); + ParseFunctionDeclaration(true, ir::ModifierFlags::NONE); + return AllocBrokenExpression(Lexer()->GetToken().Loc()); + } if (Lexer()->GetToken().Type() != lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS || !IsArrowFunctionExpressionStart()) { LogExpectedToken(lexer::TokenType::PUNCTUATOR_LEFT_PARENTHESIS); diff --git a/ets2panda/test/ast/compiler/ets/async-function-expression1.ets b/ets2panda/test/ast/compiler/ets/async-function-expression1.ets new file mode 100644 index 0000000000..de02a74245 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/async-function-expression1.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. + */ + +function relationalStoreCustomDirTest() { + it(async function () {}) + + it(async function () { + let storestore = null; + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { + "name": "", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await storestore.insert("test", valueBucket); + }) + + it(async function () { + const STORE_CONFIG = { + name: "", + securityLevel: data_Rdb.SecurityLevel.S1, + customDir: "" + } + let storestore = await data_Rdb.getRdbStore(context, STORE_CONFIG); + await storestore.executeSql(CREATE_TABLE_TEST, null); + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { + "name": "", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await storestore.insert("test", valueBucket); + }) +} +/* @@? 17:5 Error TypeError: Unresolved reference it */ +/* @@? 17:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 19:5 Error TypeError: This expression is not callable. */ +/* @@? 19:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 31:5 Error TypeError: This expression is not callable. */ +/* @@? 31:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ diff --git a/ets2panda/test/ast/compiler/ets/async-function-expression2.ets b/ets2panda/test/ast/compiler/ets/async-function-expression2.ets new file mode 100644 index 0000000000..c4fef79dcf --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/async-function-expression2.ets @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 relationalStoreCustomDirTest() { + it(async function function() {}) + + it(async function function() { + let storestore = null; + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { + "name": "", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await storestore.insert("test", valueBucket); + }) + + it(async function function() { + const STORE_CONFIG = { + name: "", + securityLevel: data_Rdb.SecurityLevel.S1, + customDir: "" + } + let storestore = await data_Rdb.getRdbStore(context, STORE_CONFIG); + await storestore.executeSql(CREATE_TABLE_TEST, null); + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { + "name": "", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await storestore.insert("test", valueBucket); + }) +} +/* @@? 17:5 Error TypeError: Unresolved reference it */ +/* @@? 17:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 17:23 Error SyntaxError: Unexpected token, expected '('. */ +/* @@? 17:31 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 17:31 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 17:31 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 19:5 Error TypeError: This expression is not callable. */ +/* @@? 19:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 19:23 Error SyntaxError: Unexpected token, expected '('. */ +/* @@? 19:31 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 19:31 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 19:31 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 31:5 Error TypeError: This expression is not callable. */ +/* @@? 31:14 Error SyntaxError: Function expressions are not supported, use arrow functions instead */ +/* @@? 31:23 Error SyntaxError: Unexpected token, expected '('. */ +/* @@? 31:31 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 31:31 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 31:31 Error SyntaxError: Unexpected token, expected ',' or ')'. */ -- Gitee From 198abd42e2e3efcb8219b34e1469a0afd57b876d Mon Sep 17 00:00:00 2001 From: Zhelyapov Aleksey Date: Mon, 7 Jul 2025 15:40:00 +0300 Subject: [PATCH 112/145] Fix codecheck Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKLNU Signed-off-by: Zhelyapov Aleksey --- ets2panda/aot/main.cpp | 18 +++++++++++++---- ets2panda/checker/ts/destructuringContext.cpp | 1 + ets2panda/compiler/core/compilerImpl.cpp | 20 +++++++++++++++---- .../compiler/lowering/ets/enumLowering.cpp | 2 ++ .../ets/interfacePropertyDeclarations.cpp | 3 +++ ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 1 + ets2panda/ir/brokenTypeNode.cpp | 1 + ets2panda/ir/ts/tsTupleType.cpp | 1 + 8 files changed, 39 insertions(+), 8 deletions(-) diff --git a/ets2panda/aot/main.cpp b/ets2panda/aot/main.cpp index b8f59a420f..2782245c60 100644 --- a/ets2panda/aot/main.cpp +++ b/ets2panda/aot/main.cpp @@ -100,6 +100,15 @@ static int CompileMultipleFiles(es2panda::Compiler &compiler, std::vector &parserInputs, unsigned int returnCode) +{ + for (auto *input : parserInputs) { + delete input; + } + parserInputs.clear(); + return returnCode; +} + static unsigned int CompileFromConfig(es2panda::Compiler &compiler, util::Options *options, util::DiagnosticEngine &diagnosticEngine) { @@ -110,6 +119,7 @@ static unsigned int CompileFromConfig(es2panda::Compiler &compiler, util::Option } std::vector inputs {}; + std::vector parserInputs; unsigned int overallRes = 0; for (auto &[src, dst] : compilationList) { std::ifstream inputStream(src); @@ -119,14 +129,14 @@ static unsigned int CompileFromConfig(es2panda::Compiler &compiler, util::Option } std::stringstream ss; ss << inputStream.rdbuf(); - auto *parserInput = new std::string(ss.str()); + parserInputs.push_back(new std::string(ss.str())); inputStream.close(); - es2panda::SourceFile input(src, *parserInput, options->IsModule(), std::string_view(dst)); + es2panda::SourceFile input(src, *parserInputs.back(), options->IsModule(), std::string_view(dst)); inputs.push_back(input); } if (options->IsPermArena() && (options->GetExtension() == util::gen::extension::ETS)) { - return CompileMultipleFiles(compiler, inputs, options, diagnosticEngine); + return ReleaseInputsAndReturn(parserInputs, CompileMultipleFiles(compiler, inputs, options, diagnosticEngine)); } for (auto &input : inputs) { @@ -140,7 +150,7 @@ static unsigned int CompileFromConfig(es2panda::Compiler &compiler, util::Option overallRes |= static_cast(res); } } - return overallRes; + return ReleaseInputsAndReturn(parserInputs, overallRes); } static std::optional> InitializePlugins(std::vector const &names, diff --git a/ets2panda/checker/ts/destructuringContext.cpp b/ets2panda/checker/ts/destructuringContext.cpp index 62212a8fca..3a0994723c 100644 --- a/ets2panda/checker/ts/destructuringContext.cpp +++ b/ets2panda/checker/ts/destructuringContext.cpp @@ -157,6 +157,7 @@ void DestructuringContext::HandleAssignmentPattern(ir::AssignmentExpression *ass ES2PANDA_ASSERT(defaultType != nullptr); if (validateDefault && assignmentPattern->Right()->IsObjectExpression() && assignmentPattern->Left()->IsObjectPattern()) { + ES2PANDA_ASSERT(defaultType != nullptr); ValidateObjectLiteralType(defaultType->AsObjectType(), assignmentPattern->Left()->AsObjectPattern()); } diff --git a/ets2panda/compiler/core/compilerImpl.cpp b/ets2panda/compiler/core/compilerImpl.cpp index 0f206c0f0d..5a0a5ce4e1 100644 --- a/ets2panda/compiler/core/compilerImpl.cpp +++ b/ets2panda/compiler/core/compilerImpl.cpp @@ -427,10 +427,22 @@ static bool ExecuteParsingAndCompiling(const CompilationUnit &unit, public_lib:: return !context->diagnosticEngine->IsAnyError(); } +static pandasm::Program *ClearContextAndReturnProgam(public_lib::Context *context, pandasm::Program *program) +{ + context->config = nullptr; + context->parser = nullptr; + context->checker->SetAnalyzer(nullptr); + context->checker = nullptr; + context->analyzer = nullptr; + context->phaseManager = nullptr; + context->parserProgram = nullptr; + context->emitter = nullptr; + return program; +} + template -static pandasm::Program *Compile(const CompilationUnit &unit, CompilerImpl *compilerImpl, - [[maybe_unused]] public_lib::Context *context) +static pandasm::Program *Compile(const CompilationUnit &unit, CompilerImpl *compilerImpl, public_lib::Context *context) { auto config = public_lib::ConfigImpl {}; context->config = &config; @@ -475,9 +487,9 @@ static pandasm::Program *Compile(const CompilationUnit &unit, CompilerImpl *comp context->checker->Initialize(varbinder); if (!ExecuteParsingAndCompiling(unit, context)) { - return nullptr; + return ClearContextAndReturnProgam(context, nullptr); } - return EmitProgram(compilerImpl, context, unit); + return ClearContextAndReturnProgam(context, EmitProgram(compilerImpl, context, unit)); } pandasm::Program *CompilerImpl::Compile(const CompilationUnit &unit, public_lib::Context *context) diff --git a/ets2panda/compiler/lowering/ets/enumLowering.cpp b/ets2panda/compiler/lowering/ets/enumLowering.cpp index 5212c1dc3a..115baffb4b 100644 --- a/ets2panda/compiler/lowering/ets/enumLowering.cpp +++ b/ets2panda/compiler/lowering/ets/enumLowering.cpp @@ -152,6 +152,7 @@ template auto *const arrayClassProp = AllocNode( arrayIdent, arrayExpr, typeAnnotation, ir::ModifierFlags::STATIC | ir::ModifierFlags::PRIVATE | ir::ModifierFlags::READONLY, Allocator(), false); + ES2PANDA_ASSERT(arrayClassProp != nullptr); arrayClassProp->SetParent(enumClass); enumClass->Body().push_back(arrayClassProp); @@ -316,6 +317,7 @@ void EnumLoweringPhase::CreateCCtorForEnumClass(ir::ClassDefinition *const enumC auto *const methodDef = AllocNode(ir::MethodDefinitionKind::METHOD, identClone, funcExpr, ir::ModifierFlags::PRIVATE | ir::ModifierFlags::STATIC, Allocator(), false); + ES2PANDA_ASSERT(methodDef != nullptr); methodDef->SetParent(enumClass); enumClass->Body().push_back(methodDef); } diff --git a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp index f9832dc3c3..14ab736122 100644 --- a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp +++ b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp @@ -85,6 +85,7 @@ ir::FunctionSignature InterfacePropertyDeclarationsPhase::GenerateGetterOrSetter InitScopesPhaseETS::RunExternalNode(paramIdent, varbinder); auto *const paramExpression = ctx->AllocNode(paramIdent, false, ctx->Allocator()); + ES2PANDA_ASSERT(paramExpression != nullptr); paramExpression->SetRange(paramIdent->Range()); auto [paramVar, node] = paramScope->AddParamDecl(ctx->Allocator(), varbinder, paramExpression); if (node != nullptr) { @@ -108,6 +109,7 @@ ir::MethodDefinition *InterfacePropertyDeclarationsPhase::GenerateGetterOrSetter auto classScope = NearestScope(field); auto *paramScope = ctx->Allocator()->New(ctx->Allocator(), classScope); auto *functionScope = ctx->Allocator()->New(ctx->Allocator(), paramScope); + ES2PANDA_ASSERT(functionScope != nullptr); functionScope->BindParamScope(paramScope); paramScope->BindFunctionScope(functionScope); @@ -253,6 +255,7 @@ ir::Expression *InterfacePropertyDeclarationsPhase::UpdateInterfaceProperties(pu } auto newInterface = ctx->AllocNode(std::move(newPropertyList)); + ES2PANDA_ASSERT(newInterface != nullptr); newInterface->SetRange(interface->Range()); newInterface->SetParent(interface->Parent()); diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index d14977f265..51ef162a7c 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -618,6 +618,7 @@ void TSDeclGen::GenFunctionType(const checker::ETSFunctionType *etsFunctionType, const bool isSetter = methodDef != nullptr ? methodDef->Kind() == ir::MethodDefinitionKind::SET : false; // CC-OFFNXT(G.FMT.14-CPP) project code style const auto *sig = GetFuncSignature(etsFunctionType, methodDef); + ES2PANDA_ASSERT(sig != nullptr); if (sig->HasFunction()) { GenTypeParameters(sig->Function()->TypeParams()); const auto *funcBody = sig->Function()->Body(); diff --git a/ets2panda/ir/brokenTypeNode.cpp b/ets2panda/ir/brokenTypeNode.cpp index 110222066d..05ef63679f 100644 --- a/ets2panda/ir/brokenTypeNode.cpp +++ b/ets2panda/ir/brokenTypeNode.cpp @@ -72,6 +72,7 @@ checker::VerifiedType BrokenTypeNode::Check([[maybe_unused]] checker::ETSChecker BrokenTypeNode *BrokenTypeNode::Clone(ArenaAllocator *const allocator, AstNode *const parent) { auto *const clone = allocator->New(allocator); + ES2PANDA_ASSERT(clone != nullptr); if (parent != nullptr) { clone->SetParent(parent); } diff --git a/ets2panda/ir/ts/tsTupleType.cpp b/ets2panda/ir/ts/tsTupleType.cpp index c6f8052957..45d7df04c4 100644 --- a/ets2panda/ir/ts/tsTupleType.cpp +++ b/ets2panda/ir/ts/tsTupleType.cpp @@ -93,6 +93,7 @@ checker::Type *GetNumberIndexType(ArenaVector numberIndexTypes, static void SetMemberVarType(checker::Type *memberType, varbinder::LocalVariable *memberVar) { + ES2PANDA_ASSERT(memberType != nullptr); memberType->SetVariable(memberVar); memberVar->SetTsType(memberType); } -- Gitee From 050d89180c92f2f5ebafcbdf5544a41027560853 Mon Sep 17 00:00:00 2001 From: dongchao Date: Thu, 3 Jul 2025 20:23:55 +0800 Subject: [PATCH 113/145] Fix interface optional scene in declgen_ets2ts Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICL8RP Signed-off-by: dongchao Change-Id: I49dbbf9598ba2d46731dba2b58f792eeb7d16d86 --- .../ets/interfacePropertyDeclarations.cpp | 2 + ets2panda/declgen_ets2ts/declgenEts2Ts.cpp | 137 +++++++++++++----- ets2panda/declgen_ets2ts/declgenEts2Ts.h | 2 + ...est_ets2ts_isolated_interface-expected.txt | 10 ++ 4 files changed, 114 insertions(+), 37 deletions(-) create mode 100644 ets2panda/test/unit/declgen/ets2ts_isolated/test_ets2ts_isolated_interface-expected.txt diff --git a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp index f9832dc3c3..7a83087a0b 100644 --- a/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp +++ b/ets2panda/compiler/lowering/ets/interfacePropertyDeclarations.cpp @@ -218,7 +218,9 @@ ir::Expression *InterfacePropertyDeclarationsPhase::UpdateInterfaceProperties(pu HandleInternalGetterOrSetterMethod(prop); continue; } + auto *originProp = prop->Clone(ctx->allocator, nullptr); auto getter = GenerateGetterOrSetter(ctx, varbinder, prop->AsClassProperty(), false); + getter->SetOriginalNode(originProp); auto methodScope = scope->AsClassScope()->InstanceMethodScope(); auto name = getter->Key()->AsIdentifier()->Name(); diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp index d14977f265..42df5c15cd 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.cpp @@ -70,6 +70,8 @@ bool TSDeclGen::GenGlobalDescriptor() OutEndlTs(); OutTs("ETSGLOBAL.", compiler::Signatures::INIT_METHOD, "();"); OutEndlTs(); + OutTs("export {};"); + OutEndlTs(); return true; } @@ -156,7 +158,9 @@ void TSDeclGen::ProcessClassDependencies(const ir::ClassDeclaration *classDecl) if (state_.super != nullptr) { AddSuperType(state_.super); } - ProcessInterfacesDependencies(classDef->TsType()->AsETSObjectType()->Interfaces()); + if (classDef->TsType() != nullptr && classDef->TsType()->IsETSObjectType()) { + ProcessInterfacesDependencies(classDef->TsType()->AsETSObjectType()->Interfaces()); + } if (classDef->TypeParams() != nullptr) { GenSeparated( @@ -215,6 +219,9 @@ void TSDeclGen::ProcessClassMethodDependencies(const ir::MethodDefinition *metho void TSDeclGen::AddSuperType(const ir::Expression *super) { + if (super->TsType() == nullptr) { + return; + } const auto superType = checker::ETSChecker::ETSType(super->TsType()); if (superType == checker::TypeFlag::ETS_OBJECT || superType == checker::TypeFlag::ETS_DYNAMIC_TYPE) { auto objectType = super->TsType()->AsETSObjectType(); @@ -1073,16 +1080,19 @@ void TSDeclGen::GenNamespaceImport(const ir::AstNode *specifier, const std::stri void TSDeclGen::GenDefaultImport(const ir::AstNode *specifier, const std::string &source, bool isTypeKind) { - const auto local = specifier->AsImportDefaultSpecifier()->Local()->Name(); - if (specifier->AsImportDefaultSpecifier()->Local()->Variable() && - specifier->AsImportDefaultSpecifier()->Local()->Variable()->Declaration() && - specifier->AsImportDefaultSpecifier()->Local()->Variable()->Declaration()->Node() && - specifier->AsImportDefaultSpecifier()->Local()->Variable()->Declaration()->Node()->IsTSInterfaceDeclaration()) { - OutTs("import type ", local, " from \"", source, "\";"); - } else { - OutTs(isTypeKind ? "import type " : "import ", local, " from \"", source, "\";"); + auto importDefaultSpecifier = specifier->AsImportDefaultSpecifier(); + auto variable = importDefaultSpecifier->Local()->Variable(); + const auto local = importDefaultSpecifier->Local()->Name(); + bool isTypeDeclaration = false; + if (variable != nullptr && variable->Declaration() != nullptr && variable->Declaration()->Node() != nullptr) { + auto *node = variable->Declaration()->Node(); + isTypeDeclaration = node->IsTSTypeAliasDeclaration() || node->IsTSInterfaceDeclaration(); } - OutEndlTs(); + if (!isTypeKind && !isTypeDeclaration) { + OutTs("import ", local, " from \"", source, "\";"); + OutEndlTs(); + } + if (importSet_.find(local.Mutf8()) == importSet_.end()) { return; } @@ -1100,8 +1110,9 @@ void TSDeclGen::GenNamedImports(const ir::ETSImportDeclaration *importDeclaratio std::vector normalSpecifiers; SeparateInterfaceSpecifiers(specifiers, interfaceSpecifiers, normalSpecifiers); - GenTsImportStatement(interfaceSpecifiers, importDeclaration, true); - GenTsImportStatement(normalSpecifiers, importDeclaration); + if (!isTypeKind) { + GenTsImportStatement(normalSpecifiers, importDeclaration); + } auto importSpecifiers = FilterValidImportSpecifiers(specifiers); GenDtsImportStatement(importSpecifiers, importDeclaration, isTypeKind); @@ -1195,8 +1206,9 @@ void TSDeclGen::GenReExportDeclaration(const ir::ETSReExportDeclaration *reExpor GenDtsReExportStatement(specifiers, importDeclaration, isTypeKind); - GenTsReExportStatement(interfaceSpecifiers, importDeclaration, true); - GenTsReExportStatement(normalSpecifiers, importDeclaration); + if (!isTypeKind) { + GenTsReExportStatement(normalSpecifiers, importDeclaration); + } } bool TSDeclGen::GenNamespaceReExportDeclaration(const ir::AstNode *specifier, @@ -1223,10 +1235,14 @@ void TSDeclGen::SeparateInterfaceSpecifiers(const ArenaVector &sp if (!specifier->IsImportSpecifier()) { continue; } - if (specifier->AsImportSpecifier()->Imported()->Variable() && - specifier->AsImportSpecifier()->Imported()->Variable()->Declaration() && - specifier->AsImportSpecifier()->Imported()->Variable()->Declaration()->Node() && - specifier->AsImportSpecifier()->Imported()->Variable()->Declaration()->Node()->IsTSInterfaceDeclaration()) { + auto importSpecifier = specifier->AsImportSpecifier(); + auto variable = importSpecifier->Imported()->Variable(); + bool isTypeDeclaration = false; + if (variable != nullptr && variable->Declaration() != nullptr && variable->Declaration()->Node() != nullptr) { + auto *node = variable->Declaration()->Node(); + isTypeDeclaration = node->IsTSTypeAliasDeclaration() || node->IsTSInterfaceDeclaration(); + } + if (isTypeDeclaration) { interfaceSpecifiers.push_back(specifier); } else { normalSpecifiers.push_back(specifier); @@ -1522,16 +1538,6 @@ void TSDeclGen::GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAl 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(); } void TSDeclGen::GenEnumDeclaration(const ir::ClassProperty *enumMember) @@ -1606,16 +1612,68 @@ void TSDeclGen::GenInterfaceDeclaration(const ir::TSInterfaceDeclaration *interf void TSDeclGen::ProcessInterfaceBody(const ir::TSInterfaceBody *body) { - std::unordered_set processedMethods; for (auto *prop : body->Body()) { if (prop->IsMethodDefinition()) { - ProcessMethodDefinition(prop->AsMethodDefinition(), processedMethods); + ProcessInterfaceMethodDefinition(prop->AsMethodDefinition()); } else if (prop->IsClassProperty()) { GenPropDeclaration(prop->AsClassProperty()); } } } +void TSDeclGen::ProcessInterfaceMethodDefinition(const ir::MethodDefinition *methodDef) +{ + if (GenInterfaceProp(methodDef)) { + return; + } + + if (methodDef->IsGetter() || methodDef->IsSetter()) { + GenMethodDeclaration(methodDef); + } + if (!methodDef->Overloads().empty()) { + for (const auto *overloadMethd : methodDef->Overloads()) { + if (overloadMethd->IsGetter() || overloadMethd->IsSetter()) { + GenMethodDeclaration(overloadMethd); + } + } + return; + } + if (!methodDef->IsGetter() && !methodDef->IsSetter()) { + GenMethodDeclaration(methodDef); + } +} + +bool TSDeclGen::GenInterfaceProp(const ir::MethodDefinition *methodDef) +{ + if (!methodDef->IsGetter()) { + return false; + } + if (methodDef->OriginalNode() == nullptr) { + return false; + } + if (!methodDef->OriginalNode()->IsClassProperty()) { + return false; + } + + const auto methodName = GetKeyIdent(methodDef->Key())->Name().Mutf8(); + const auto classProp = methodDef->OriginalNode()->AsClassProperty(); + bool isReadOnly = classProp->IsReadonly(); + bool isOptional = classProp->IsOptionalDeclaration(); + ProcessIndent(); + if (isReadOnly) { + OutDts("readonly "); + } + OutDts(methodName); + if (isOptional) { + OutDts("?"); + } + OutDts(": "); + GenType(methodDef->Function()->Signature()->ReturnType()); + OutDts(";"); + OutEndlDts(); + return true; +} + void TSDeclGen::ProcessMethodDefinition(const ir::MethodDefinition *methodDef, std::unordered_set &processedMethods) { @@ -1681,9 +1739,11 @@ void TSDeclGen::EmitClassDeclaration(const ir::ClassDefinition *classDef, const if (classDef->IsNamespaceTransformed()) { EmitDeclarationPrefix(classDef, "namespace ", className); OutTs("export namespace ", className, " {"); + OutEndlTs(); } else if (classDef->IsEnumTransformed()) { EmitDeclarationPrefix(classDef, "enum ", className); OutTs("export const enum ", className, " {"); + OutEndlTs(); } else if (classDef->IsFromStruct()) { EmitDeclarationPrefix(classDef, "struct ", className); } else if (classDef->IsAbstract()) { @@ -1691,7 +1751,6 @@ void TSDeclGen::EmitClassDeclaration(const ir::ClassDefinition *classDef, const } else { EmitDeclarationPrefix(classDef, "class ", className); } - OutEndlTs(); } std::string TSDeclGen::GetIndent() const @@ -1750,10 +1809,10 @@ void TSDeclGen::HandleClassDeclarationTypeInfo(const ir::ClassDefinition *classD HandleClassInherit(super); } - const auto &interfaces = classDef->TsType()->AsETSObjectType()->Interfaces(); - if (!interfaces.empty()) { + if (classDef->TsType() != nullptr && classDef->TsType()->IsETSObjectType() && + !classDef->TsType()->AsETSObjectType()->Interfaces().empty()) { OutDts(" implements "); - ES2PANDA_ASSERT(classDef->TsType()->IsETSObjectType()); + const auto &interfaces = classDef->TsType()->AsETSObjectType()->Interfaces(); GenSeparated(interfaces, [this](checker::ETSObjectType *interface) { GenType(interface); }); } else if (!classDef->Implements().empty()) { OutDts(" implements "); @@ -1775,7 +1834,7 @@ void TSDeclGen::HandleClassInherit(const ir::Expression *expr) void TSDeclGen::EmitClassGlueCode(const ir::ClassDefinition *classDef, const std::string &className) { - if (classNode_.isIndirect) { + if (classNode_.isIndirect || classDef->IsExportedType()) { return; } const std::string exportPrefix = classDef->Parent()->IsDefaultExported() ? "const " : "export const "; @@ -1848,7 +1907,9 @@ void TSDeclGen::ProcessClassBody(const ir::ClassDefinition *classDef) GenClassDeclaration(prop->AsClassDeclaration()); } } - ProcessMethodsFromInterfaces(processedMethods, classDef->TsType()->AsETSObjectType()->Interfaces()); + if (classDef->TsType() != nullptr && classDef->TsType()->IsETSObjectType()) { + ProcessMethodsFromInterfaces(processedMethods, classDef->TsType()->AsETSObjectType()->Interfaces()); + } } void TSDeclGen::CloseClassBlock(const bool isDts) @@ -2030,7 +2091,9 @@ void TSDeclGen::GenMethodSignature(const ir::MethodDefinition *methodDef, const if (methodDef->TsType() == nullptr) { LogWarning(diagnostic::UNTYPED_METHOD, {methodName}, methodIdent->Start()); OutDts(": any"); - } else { + return; + } + if (methodDef->TsType()->IsETSFunctionType()) { GenFunctionType(methodDef->TsType()->AsETSFunctionType(), methodDef); } } diff --git a/ets2panda/declgen_ets2ts/declgenEts2Ts.h b/ets2panda/declgen_ets2ts/declgenEts2Ts.h index ccd20774e5..78b6cce4a0 100644 --- a/ets2panda/declgen_ets2ts/declgenEts2Ts.h +++ b/ets2panda/declgen_ets2ts/declgenEts2Ts.h @@ -143,6 +143,7 @@ private: void GenTypeAliasDeclaration(const ir::TSTypeAliasDeclaration *typeAlias); void GenEnumDeclaration(const ir::ClassProperty *enumMember); void GenInterfaceDeclaration(const ir::TSInterfaceDeclaration *interfaceDecl); + bool GenInterfaceProp(const ir::MethodDefinition *methodDef); void GenClassDeclaration(const ir::ClassDeclaration *classDecl); void GenMethodDeclaration(const ir::MethodDefinition *methodDef); bool GenMethodDeclarationPrefix(const ir::MethodDefinition *methodDef, const ir::Identifier *methodIdent, @@ -223,6 +224,7 @@ private: void HandleTypeArgument(checker::Type *arg, const std::string &typeStr); void ProcessInterfaceBody(const ir::TSInterfaceBody *body); + void ProcessInterfaceMethodDefinition(const ir::MethodDefinition *methodDef); void ProcessMethodDefinition(const ir::MethodDefinition *methodDef, std::unordered_set &processedMethods); diff --git a/ets2panda/test/unit/declgen/ets2ts_isolated/test_ets2ts_isolated_interface-expected.txt b/ets2panda/test/unit/declgen/ets2ts_isolated/test_ets2ts_isolated_interface-expected.txt new file mode 100644 index 0000000000..072a2020c2 --- /dev/null +++ b/ets2panda/test/unit/declgen/ets2ts_isolated/test_ets2ts_isolated_interface-expected.txt @@ -0,0 +1,10 @@ +export declare interface User { + id: number; + name: string; + age?: number | undefined; + readonly apiUrl: string; +} +export declare interface Animal { + name: string; + makeSound(): void; +} -- Gitee From 173b24e6d38d502d2591c3592b10990974fa7cd8 Mon Sep 17 00:00:00 2001 From: sunfei Date: Mon, 12 May 2025 11:06:55 +0800 Subject: [PATCH 114/145] supprot paths config for build_system Issue: https://gitee.com/openharmony/build/issues/ICA7PN Signed-off-by: sunfei Change-Id: I6a7a52bac1c96731c220266e3ebb6f40f33a199c --- ets2panda/driver/build_system/src/build/base_mode.ts | 3 ++- .../driver/build_system/src/build/generate_arktsconfig.ts | 8 +++++++- ets2panda/driver/build_system/src/types.ts | 5 +++++ 3 files changed, 14 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 1c05abf17a..dccb49481f 100644 --- a/ets2panda/driver/build_system/src/build/base_mode.ts +++ b/ets2panda/driver/build_system/src/build/base_mode.ts @@ -314,7 +314,8 @@ export abstract class BaseMode { } finally { if (!errorStatus) { // when error occur,wrapper will destroy context. - arktsGlobal.es2panda._DestroyContext(arktsGlobal.compilerContext.peer); + // comment this in 0603 to solve free() invalid pointer + //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 edb1224fb7..c34333082c 100644 --- a/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts +++ b/ets2panda/driver/build_system/src/build/generate_arktsconfig.ts @@ -32,7 +32,8 @@ import { } from '../utils'; import { BuildConfig, - ModuleInfo + ModuleInfo, + PathsConfig } from '../types'; import { LANGUAGE_VERSION, @@ -252,6 +253,11 @@ export class ArkTSConfigGenerator { } let baseUrl: string = path.resolve(moduleInfo.moduleRootPath, moduleInfo.sourceRoots[0]); + if (buildConfig.paths) { + Object.entries(buildConfig.paths).map(([key, value]) => { + pathSection[key] = value + }); + } let arktsConfig: ArkTSConfigObject = { compilerOptions: { package: moduleInfo.packageName, diff --git a/ets2panda/driver/build_system/src/types.ts b/ets2panda/driver/build_system/src/types.ts index 37745789b4..613cde8acc 100644 --- a/ets2panda/driver/build_system/src/types.ts +++ b/ets2panda/driver/build_system/src/types.ts @@ -18,6 +18,10 @@ export interface PluginsConfig { [pluginName: string]: string; } +export interface PathsConfig { + [pathName: string]: string[]; +} + export interface BuildBaseConfig { buildType: 'build' | 'preview' | 'hotreload' | 'coldreload'; buildMode: 'Debug' | 'Release'; @@ -139,6 +143,7 @@ export interface DependentModuleConfig { export interface BuildConfig extends BuildBaseConfig, DeclgenConfig, LoggerConfig, ModuleConfig, PathConfig, FrameworkConfig { plugins: PluginsConfig; + paths: PathsConfig; // paths config passed from template to generate arktsconfig.json "paths" configs. compileFiles: string[]; dependentModuleList: DependentModuleConfig[]; } -- Gitee From 0c8467e52d38741c522e45ac72f07ff1b9e5b41e Mon Sep 17 00:00:00 2001 From: fcc Date: Thu, 10 Jul 2025 10:53:47 +0800 Subject: [PATCH 115/145] Fix lambda with rest param and optional params Compiler crash when lambda have both rest param and optional params. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKSX8 Signed-off-by: fcc --- ets2panda/checker/types/ets/etsFunctionType.cpp | 8 +++++++- .../runtime/ets/lambda_with_restparameter_optinal.ets | 4 ++-- .../ets/lambda_with_restparameter_optinal_fixedarray.ets | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/ets2panda/checker/types/ets/etsFunctionType.cpp b/ets2panda/checker/types/ets/etsFunctionType.cpp index ad1fa74e55..10e8fd6e94 100644 --- a/ets2panda/checker/types/ets/etsFunctionType.cpp +++ b/ets2panda/checker/types/ets/etsFunctionType.cpp @@ -75,8 +75,14 @@ static ETSObjectType *FunctionTypeToFunctionalInterfaceType(ETSChecker *checker, bool isExtensionHack = signature->HasSignatureFlag(SignatureFlags::EXTENSION_FUNCTION); if (signature->RestVar() != nullptr) { - auto *functionN = checker->GlobalBuiltinFunctionType(arity, true); + auto sigParamsSize = signature->Params().size(); + auto nPosParams = arity < sigParamsSize ? arity : sigParamsSize; + auto *functionN = checker->GlobalBuiltinFunctionType(nPosParams, true); auto *substitution = checker->NewSubstitution(); + for (size_t i = 0; i < nPosParams; i++) { + substitution->emplace(functionN->TypeArguments()[i]->AsETSTypeParameter(), + checker->MaybeBoxType(signature->Params()[i]->TsType())); + } auto *elementType = !signature->RestVar()->TsType()->IsETSTupleType() ? checker->GetElementTypeOfArray(signature->RestVar()->TsType()) : checker->GlobalETSAnyType(); diff --git a/ets2panda/test/runtime/ets/lambda_with_restparameter_optinal.ets b/ets2panda/test/runtime/ets/lambda_with_restparameter_optinal.ets index 8329f050c9..40cc731075 100644 --- a/ets2panda/test/runtime/ets/lambda_with_restparameter_optinal.ets +++ b/ets2panda/test/runtime/ets/lambda_with_restparameter_optinal.ets @@ -16,11 +16,11 @@ function main(){ let f1 = (a?:String, b?:String, ...args:String[])=>{ if(a != undefined){ - assertEQ(a,"000"); + arktest.assertEQ(a,"000"); } if(args.length > 0){ - assertEQ(args[0],"222"); + arktest.assertEQ(args[0],"222"); } } f1("000","111","222","333") diff --git a/ets2panda/test/runtime/ets/lambda_with_restparameter_optinal_fixedarray.ets b/ets2panda/test/runtime/ets/lambda_with_restparameter_optinal_fixedarray.ets index 6d0575268d..d5568c937c 100644 --- a/ets2panda/test/runtime/ets/lambda_with_restparameter_optinal_fixedarray.ets +++ b/ets2panda/test/runtime/ets/lambda_with_restparameter_optinal_fixedarray.ets @@ -16,11 +16,11 @@ function main(){ let f1 = (a?:String, b?:String, ...args:FixedArray)=>{ if(a != undefined){ - assertEQ(a,"000"); + arktest.assertEQ(a,"000"); } if(args.length > 0){ - assertEQ(args[0],"222"); + arktest.assertEQ(args[0],"222"); } } f1("000","111","222","333") -- Gitee From 16f82b507baa5146d65e6e304f6993d5955c67a5 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Wed, 9 Jul 2025 16:33:04 +0800 Subject: [PATCH 116/145] Fixing invalid call function crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICL4MR Description: Problem Description: Circular dependency element, tstype without expr set to TypeError, subsequent use of nullptr's tstype causes segv Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/checker/ETSAnalyzer.cpp | 1 + .../compiler/ets/fuzz_invalid_property.ets | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/fuzz_invalid_property.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 0ecc1e27aa..195d8b228d 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -1568,6 +1568,7 @@ checker::Type *ETSAnalyzer::Check(ir::CallExpression *expr) const checker::TypeStackElement tse(checker, expr, {{diagnostic::CYCLIC_CALLEE, {}}}, expr->Start()); if (tse.HasTypeError()) { + expr->SetTsType(checker->GlobalTypeError()); return checker->GlobalTypeError(); } diff --git a/ets2panda/test/ast/compiler/ets/fuzz_invalid_property.ets b/ets2panda/test/ast/compiler/ets/fuzz_invalid_property.ets new file mode 100644 index 0000000000..93b7801f20 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzz_invalid_property.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 D{ + strB = (new StringBuilder).append('{ ').append(strB.toString()).append(' }') +} + +/* @@? 17:12 Error TypeError: Circular call function */ +/* @@? 17:52 Error TypeError: Property 'strB' must be accessed through 'this' */ -- Gitee From a5c27296e0239e9131ffa252c4ad64aeb84ce069 Mon Sep 17 00:00:00 2001 From: oh-rgx Date: Wed, 9 Jul 2025 21:29:51 +0800 Subject: [PATCH 117/145] Fix checkConstructor crash Issue: #ICL8EG Signed-off-by: oh-rgx --- ets2panda/checker/ets/object.cpp | 6 ++ .../compiler/ets/class_cyclic_constructor.ets | 56 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 ets2panda/test/ast/compiler/ets/class_cyclic_constructor.ets diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index ae11441f5d..9f151e0927 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ +#include #include "checker/ETSchecker.h" #include "checker/ets/typeRelationContext.h" #include "checker/types/ets/etsDynamicType.h" @@ -1759,6 +1760,11 @@ void ETSChecker::CheckCyclicConstructorCall(Signature *signature) return; } + // This is a condition set up to handle error scenarios. + if (signature->Function()->Body() == nullptr) { + return; + } + auto *funcBody = signature->Function()->Body()->AsBlockStatement(); TypeStackElement tse(this, signature, {{diagnostic::RECURSIVE_CTOR}}, signature->Function()->Start()); diff --git a/ets2panda/test/ast/compiler/ets/class_cyclic_constructor.ets b/ets2panda/test/ast/compiler/ets/class_cyclic_constructor.ets new file mode 100644 index 0000000000..68b81eef70 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/class_cyclic_constructor.ets @@ -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. + */ + +class A { + public x : int; + + public constructor() { + this(5); + } + + public constructor( + let tuple: {{c.to_type}} = {{caches.value}}; + let a : A = new A(...tuple); + let method_result = A.bar(...tuple); + ) { + this.x = a; + } +} + +/* @@? 23:23 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 24:9 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 24:9 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 24:9 Error SyntaxError: Unexpected token 'let'. */ +/* @@? 24:9 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 24:20 Error SyntaxError: Invalid Type. */ +/* @@? 24:20 Error SyntaxError: Unexpected token '{'. */ +/* @@? 24:21 Error SyntaxError: Unexpected token '{'. */ +/* @@? 24:23 Error SyntaxError: Field type annotation expected. */ +/* @@? 24:23 Error SyntaxError: Unexpected token '.'. */ +/* @@? 24:31 Error SyntaxError: Field type annotation expected. */ +/* @@? 24:32 Error SyntaxError: Unexpected token '}'. */ +/* @@? 24:37 Error SyntaxError: Unexpected token. */ +/* @@? 24:38 Error SyntaxError: Unexpected token. */ +/* @@? 24:51 Error SyntaxError: Unexpected token '}'. */ +/* @@? 25:21 Error TypeError: Expected 0 arguments, got 1. */ +/* @@? 25:21 Error TypeError: No matching construct signature for class_cyclic_constructor.A(...tuple) */ +/* @@? 25:27 Error TypeError: Spread argument cannot be passed for ordinary parameter. */ +/* @@? 25:30 Error TypeError: Unresolved reference tuple */ +/* @@? 26:31 Error TypeError: Property 'bar' does not exist on type 'A' */ +/* @@? 27:5 Error SyntaxError: Unexpected token ')'. */ +/* @@? 27:7 Error SyntaxError: Unexpected token '{'. */ +/* @@? 28:9 Error TypeError: Cannot reference 'this' in this context. */ +/* @@? 28:14 Error TypeError: Property 'x' does not exist on type 'Error' */ +/* @@? 30:1 Error SyntaxError: Unexpected token '}'. */ -- Gitee From a56625aa29de0a6dd48ddb041afa06acc112ff7e Mon Sep 17 00:00:00 2001 From: fcc Date: Tue, 8 Jul 2025 17:49:46 +0800 Subject: [PATCH 118/145] fix crash when function type is TypeError Ensure type IsETSFunctionType before AsETSFunctionType. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICKU8S Signed-off-by: fcc t commit --amend --- ets2panda/checker/ets/function.cpp | 2 +- ets2panda/checker/ets/helpers.cpp | 3 +- ets2panda/checker/ets/object.cpp | 2 +- .../ast/compiler/ets/function_typeerror.ets | 55 +++++++++++++++++++ 4 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/function_typeerror.ets diff --git a/ets2panda/checker/ets/function.cpp b/ets2panda/checker/ets/function.cpp index 6736d65441..778f45b079 100644 --- a/ets2panda/checker/ets/function.cpp +++ b/ets2panda/checker/ets/function.cpp @@ -1752,7 +1752,7 @@ bool ETSChecker::CheckOverride(Signature *signature, ETSObjectType *site) auto *target = site->GetProperty(signature->Function()->Id()->Name(), flags); bool isOverridingAnySignature = false; - if (target == nullptr) { + if (target == nullptr || target->TsType() == nullptr || target->TsType()->IsTypeError()) { return isOverridingAnySignature; } diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index 35eb70cc91..f970840255 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -61,7 +61,8 @@ bool ETSChecker::IsVariableStatic(const varbinder::Variable *var) { CHECK_NOT_NULL(var); if (var->HasFlag(varbinder::VariableFlags::METHOD)) { - return var->TsType()->AsETSFunctionType()->CallSignatures()[0]->HasSignatureFlag(SignatureFlags::STATIC); + return var->TsType()->IsETSFunctionType() && + var->TsType()->AsETSFunctionType()->CallSignatures()[0]->HasSignatureFlag(SignatureFlags::STATIC); } return var->HasFlag(varbinder::VariableFlags::STATIC); } diff --git a/ets2panda/checker/ets/object.cpp b/ets2panda/checker/ets/object.cpp index a3f81609ca..3fcf29a20a 100644 --- a/ets2panda/checker/ets/object.cpp +++ b/ets2panda/checker/ets/object.cpp @@ -83,7 +83,7 @@ static bool CheckGetterSetterDecl(varbinder::LocalVariable const *child, varbind static bool CheckFunctionDecl(varbinder::LocalVariable *child, varbinder::LocalVariable *parent) { ES2PANDA_ASSERT(child->Declaration()->Type() == parent->Declaration()->Type()); - if (!child->TsType()->IsETSMethodType()) { + if (!child->TsType()->IsETSMethodType() || !parent->TsType()->IsETSMethodType()) { return true; } diff --git a/ets2panda/test/ast/compiler/ets/function_typeerror.ets b/ets2panda/test/ast/compiler/ets/function_typeerror.ets new file mode 100644 index 0000000000..bafd22a98c --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/function_typeerror.ets @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Base { + methodOne(this.ownerType!, this.name): Base { + return p; + } +} + +class Derived extends Base { + override methodOne(p: Derived): Base { + return p; + } +} + +function main(): void { + let a = new Base(); + let b = new Derived() + + let resultA = a.methodOne(a); + let resultB = b.methodOne(b); + + arktest.assertEQ(resultA, resultB); +} + +/* @@? 17:14 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 17:19 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 17:19 Error SyntaxError: Unexpected token '.'. */ +/* @@? 17:19 Error SyntaxError: The function parameter 'this' must explicitly specify the typeAnnotation. */ +/* @@? 17:30 Error SyntaxError: Field type annotation expected. */ +/* @@? 17:30 Error SyntaxError: Unexpected token ','. */ +/* @@? 17:32 Error SyntaxError: Unexpected token 'this'. */ +/* @@? 17:36 Error SyntaxError: Unexpected token '.'. */ +/* @@? 17:41 Error SyntaxError: Field type annotation expected. */ +/* @@? 17:41 Error SyntaxError: Unexpected token ')'. */ +/* @@? 17:42 Error SyntaxError: Unexpected token ':'. */ +/* @@? 17:49 Error SyntaxError: Field type annotation expected. */ +/* @@? 17:49 Error SyntaxError: Unexpected token '{'. */ +/* @@? 18:9 Error SyntaxError: Unexpected token 'return'. */ +/* @@? 18:17 Error SyntaxError: Field type annotation expected. */ +/* @@? 20:1 Error SyntaxError: Unexpected token '}'. */ +/* @@? 23:23 Error TypeError: Method methodOne(p: Derived): Base in Derived not overriding any method */ +/* @@? 32:21 Error TypeError: Property 'methodOne' does not exist on type 'Base' */ -- Gitee From 1e286a2f05b8486a72ea2414c8936bfdcec61542 Mon Sep 17 00:00:00 2001 From: zengzengran Date: Fri, 11 Jul 2025 15:51:49 +0800 Subject: [PATCH 119/145] Fixing Invalid override Crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLPA9 Description: IsVariableStatic method directly calls AsETSFunctionType for a variable with Tstype is typeerror, leading to assertion failure and causing compilation crash. Tested-by: ninja tests (passed) ets_testrunner (passed) Signed-off-by: zengzengran # --- ets2panda/checker/ets/helpers.cpp | 3 +- .../compiler/ets/fuzzing_invalid_override.ets | 62 +++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/fuzzing_invalid_override.ets diff --git a/ets2panda/checker/ets/helpers.cpp b/ets2panda/checker/ets/helpers.cpp index 35eb70cc91..f970840255 100644 --- a/ets2panda/checker/ets/helpers.cpp +++ b/ets2panda/checker/ets/helpers.cpp @@ -61,7 +61,8 @@ bool ETSChecker::IsVariableStatic(const varbinder::Variable *var) { CHECK_NOT_NULL(var); if (var->HasFlag(varbinder::VariableFlags::METHOD)) { - return var->TsType()->AsETSFunctionType()->CallSignatures()[0]->HasSignatureFlag(SignatureFlags::STATIC); + return var->TsType()->IsETSFunctionType() && + var->TsType()->AsETSFunctionType()->CallSignatures()[0]->HasSignatureFlag(SignatureFlags::STATIC); } return var->HasFlag(varbinder::VariableFlags::STATIC); } diff --git a/ets2panda/test/ast/compiler/ets/fuzzing_invalid_override.ets b/ets2panda/test/ast/compiler/ets/fuzzing_invalid_override.ets new file mode 100644 index 0000000000..960aae81e8 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/fuzzing_invalid_override.ets @@ -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. + */ + +interface ReadonlyHashMap extends Iterable<[K, V]> { + forEach(callbackFn: (value: V, key: K, map: ReadonlyHashMap) => void): void; +} + +export default class HashMap implements ReadonlyHashMap { + forEach(this.type === XmlDynamicType.START_AND_ATTRIBUTES): void { + this.buckets.forEach((value: V, key: K) => { + callbackFn(value, key, this); + }); + } +} + +/* @@? 20:69 Error TypeError: HashMap is not abstract and does not override abstract method forEach(callbackFn: (value: V, key: K, map: ReadonlyHashMap) => void): void in ReadonlyHashMap */ +/* @@? 21:12 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 21:17 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 21:17 Error SyntaxError: The function parameter 'this' must explicitly specify the typeAnnotation. */ +/* @@? 21:17 Error SyntaxError: Unexpected token '.'. */ +/* @@? 21:23 Error SyntaxError: Unexpected token '==='. */ +/* @@? 21:23 Error SyntaxError: Field type annotation expected. */ +/* @@? 21:41 Error SyntaxError: Field type annotation expected. */ +/* @@? 21:41 Error SyntaxError: Unexpected token '.'. */ +/* @@? 21:62 Error SyntaxError: Field type annotation expected. */ +/* @@? 21:62 Error SyntaxError: Unexpected token ')'. */ +/* @@? 21:63 Error SyntaxError: Unexpected token ':'. */ +/* @@? 21:65 Error SyntaxError: Unexpected token 'void'. */ +/* @@? 21:70 Error SyntaxError: Unexpected token '{'. */ +/* @@? 22:9 Error SyntaxError: Unexpected token 'this'. */ +/* @@? 22:13 Error SyntaxError: Unexpected token '.'. */ +/* @@? 22:21 Error SyntaxError: Field type annotation expected. */ +/* @@? 22:21 Error SyntaxError: Unexpected token '.'. */ +/* @@? 22:30 Error SyntaxError: Unexpected token, expected ',' or ')'. */ +/* @@? 22:30 Error SyntaxError: Unexpected token, expected an identifier. */ +/* @@? 22:30 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 22:30 Error SyntaxError: Unexpected token '('. */ +/* @@? 22:39 Error SyntaxError: Unexpected token ','. */ +/* @@? 22:47 Error SyntaxError: Unexpected token ')'. */ +/* @@? 22:49 Error SyntaxError: Unexpected token '=>'. */ +/* @@? 22:52 Error SyntaxError: Unexpected token '{'. */ +/* @@? 23:23 Error TypeError: Only abstract or native methods can't have body. */ +/* @@? 23:24 Error TypeError: The type of parameter 'value' cannot be inferred */ +/* @@? 23:29 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 23:31 Error TypeError: The type of parameter 'key' cannot be inferred */ +/* @@? 23:34 Error SyntaxError: Parameter declaration should have an explicit type annotation. */ +/* @@? 23:40 Error SyntaxError: The function parameter 'this' must explicitly specify the typeAnnotation. */ +/* @@? 24:10 Error SyntaxError: Unexpected token ')'. */ +/* @@? 25:5 Error SyntaxError: Unexpected token '}'. */ +/* @@? 26:1 Error SyntaxError: Unexpected token '}'. */ -- Gitee From 375249dc43e3fc74986579ddf048992e42f8c6e7 Mon Sep 17 00:00:00 2001 From: zmw Date: Thu, 10 Jul 2025 22:00:05 +0800 Subject: [PATCH 120/145] Fix invalid format crash Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLJ3Q Description: Fix invalid format crash Signed-off-by: zmw --- ets2panda/parser/ETSFormattedParser.cpp | 4 +-- .../parser/ets/invalid_punctuator_format.ets | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 ets2panda/test/ast/parser/ets/invalid_punctuator_format.ets diff --git a/ets2panda/parser/ETSFormattedParser.cpp b/ets2panda/parser/ETSFormattedParser.cpp index cfda403d42..b2e9c03b74 100644 --- a/ets2panda/parser/ETSFormattedParser.cpp +++ b/ets2panda/parser/ETSFormattedParser.cpp @@ -106,8 +106,8 @@ ir::TypeNode *ETSParser::ParseTypeFormatPlaceholder(std::optionalGetToken().Start()); - ES2PANDA_UNREACHABLE(); + LogUnexpectedToken(lexer::TokenType::PUNCTUATOR_FORMAT); + return AllocBrokenType(Lexer()->GetToken().Loc()); } nodeFormat = GetFormatPlaceholderType(); diff --git a/ets2panda/test/ast/parser/ets/invalid_punctuator_format.ets b/ets2panda/test/ast/parser/ets/invalid_punctuator_format.ets new file mode 100644 index 0000000000..2eba0019b6 --- /dev/null +++ b/ets2panda/test/ast/parser/ets/invalid_punctuator_format.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 { +J* @@? +} + +/* @@? 17:2 Error SyntaxError: Interface fields must have type annotation. */ +/* @@? 17:4 Error SyntaxError: Unexpected token '@@'. */ +/* @@? 17:4 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 17:4 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 17:6 Error SyntaxError: Identifier expected. */ +/* @@? 17:6 Error SyntaxError: Unexpected token, expected ','. */ +/* @@? 17:6 Error SyntaxError: Unexpected token, expected 'private' or identifier. */ +/* @@? 18:1 Error SyntaxError: Identifier expected. */ -- Gitee From 48ce0f39937c135fe1f9164e9c737d980b543c6b Mon Sep 17 00:00:00 2001 From: anjiaqi Date: Fri, 11 Jul 2025 16:46:07 +0800 Subject: [PATCH 121/145] 0603-fix-alert include 4 Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICLQAO Signed-off-by: anjiaqi --- ets2panda/checker/ETSchecker.cpp | 2 +- ets2panda/checker/types/ets/etsAnyType.cpp | 1 + ets2panda/compiler/core/ETSGen.cpp | 12 +++++++++++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/ets2panda/checker/ETSchecker.cpp b/ets2panda/checker/ETSchecker.cpp index eed861a87b..f9e052f39f 100644 --- a/ets2panda/checker/ETSchecker.cpp +++ b/ets2panda/checker/ETSchecker.cpp @@ -426,7 +426,7 @@ bool ETSChecker::IsClassStaticMethod(checker::ETSObjectType *objType, checker::S // Bugs: these types do not appear as a valid TypeKind, as the TypeKind has more then one bit set [[maybe_unused]] static constexpr auto NOT_A_TYPE_KIND = TypeFlag::ETS_DYNAMIC_FLAG; - + CHECK_NOT_NULL(type); auto res = static_cast(type->TypeFlags() & ~(TO_CLEAR)); ES2PANDA_ASSERT_POS(res == TypeFlag::NONE || helpers::math::IsPowerOfTwo(res & ~(NOT_A_TYPE_KIND)), ark::es2panda::GetPositionForDiagnostic()); diff --git a/ets2panda/checker/types/ets/etsAnyType.cpp b/ets2panda/checker/types/ets/etsAnyType.cpp index 811705455b..63dc4d1417 100644 --- a/ets2panda/checker/types/ets/etsAnyType.cpp +++ b/ets2panda/checker/types/ets/etsAnyType.cpp @@ -64,6 +64,7 @@ void ETSAnyType::Cast(TypeRelation *relation, Type *target) if (relation->ApplyUnboxing()) { auto *const boxedTarget = relation->GetChecker()->AsETSChecker()->MaybeBoxInRelation(target); + ES2PANDA_ASSERT(boxedTarget != nullptr); conversion::Unboxing(relation, boxedTarget->AsETSObjectType()); relation->Result(true); } diff --git a/ets2panda/compiler/core/ETSGen.cpp b/ets2panda/compiler/core/ETSGen.cpp index bd7cb0bcbe..040790ec1b 100644 --- a/ets2panda/compiler/core/ETSGen.cpp +++ b/ets2panda/compiler/core/ETSGen.cpp @@ -788,6 +788,7 @@ void ETSGen::IsInstanceDynamic(const ir::BinaryExpression *const node, const VRe void ETSGen::TestIsInstanceConstituent(const ir::AstNode *const node, std::tuple