From a53bd43f7833f21934e13234f5a430399bebe4bb Mon Sep 17 00:00:00 2001 From: Urakov Alexandr Date: Tue, 14 Nov 2023 13:23:07 +0300 Subject: [PATCH] [ArkTS][Linter] Extract library part from linter Signed-off-by: Urakov Alexandr --- linter/{src => lib}/Autofixer.ts | 0 linter/{src => lib}/CommandLineOptions.ts | 0 linter/lib/Compiler.ts | 38 +++++++++++++ linter/{src => lib}/CookBookMsg.ts | 0 linter/{src => lib}/FaultAttrs.ts | 0 linter/{src => lib}/FaultDesc.ts | 0 linter/{src => lib}/IncrementalLintInfo.ts | 0 .../{src => lib}/IsFileFromModuleCallback.ts | 0 linter/{src => lib}/LintOptions.ts | 0 linter/{src => lib}/LintRunResult.ts | 0 linter/{src => lib}/LinterRunner.ts | 4 +- linter/lib/Logger.ts | 55 +++++++++++++++++++ linter/{src => lib}/ProblemInfo.ts | 0 linter/{src => lib}/ProblemSeverity.ts | 0 linter/{src => lib}/Problems.ts | 0 linter/{src => lib}/TypeScriptLinter.ts | 10 ++-- linter/{src => lib}/TypeScriptLinterConfig.ts | 0 linter/{src => lib}/autofixes/AutofixInfo.ts | 0 .../{src => lib}/autofixes/AutofixTitles.ts | 0 .../autofixes/ReportAutofixCallback.ts | 0 .../ts-diagnostics/GetTscDiagnostics.ts | 0 .../ts-diagnostics/TSCCompiledProgram.ts | 4 +- .../ts-diagnostics/TransformTscDiagnostics.ts | 0 .../TypeScriptDiagnosticsExtractor.ts | 0 linter/{src => lib}/utils/TsUtils.ts | 2 +- .../utils/consts/AllowedStdSymbolAPI.ts | 0 .../utils/consts/ArkUIDecorators.ts | 0 .../utils/consts/ArktsIgnorePaths.ts | 0 linter/{src => lib}/utils/consts/ESObject.ts | 0 .../consts/FunctionHasNoReturnErrorCode.ts | 0 .../consts/LimitedStandardUtilityTypes.ts | 0 .../utils/consts/LimitedStdGlobalFunc.ts | 0 .../utils/consts/LimitedStdObjectAPI.ts | 0 .../utils/consts/LimitedStdProxyHandlerAPI.ts | 0 .../utils/consts/LimitedStdReflectAPI.ts | 0 .../NonInitializablePropertyDecorators.ts | 0 .../consts/NonReturnFunctionDecorators.ts | 0 .../PropertyHasNoInitializerErrorCode.ts | 0 .../utils/consts/StandardLibraries.ts | 0 .../{src => lib}/utils/consts/TypedArrays.ts | 0 .../utils/functions/ContainsThis.ts | 0 .../utils/functions/DiagnosticChecker.ts | 0 .../utils/functions/ForEachNodeInSubtree.ts | 0 .../utils/functions/GetScriptKind.ts | 0 .../utils/functions/HasPredecessor.ts | 0 .../utils/functions/IsStdLibrary.ts | 0 .../{src => lib}/utils/functions/IsStruct.ts | 0 .../LibraryTypeCallDiagnosticChecker.ts | 0 .../utils/functions/LinterInfo.ts | 0 .../utils/functions/LogTscDiagnostic.ts | 5 +- .../utils/functions/MergeArrayMaps.ts | 0 .../utils/functions/PathHelper.ts | 0 .../functions/identiferUseInValueContext.ts | 0 .../utils/functions/isAssignmentOperator.ts | 0 .../utils/functions/isIntrinsicObjectType.ts | 0 linter/package.json | 4 +- linter/src/CommandLineParser.ts | 22 ++++---- .../{CompilerWrapper.ts => CompilerImpl.ts} | 45 ++++++++------- linter/src/LinterCLI.ts | 16 +++--- linter/src/LoggerImpl.ts | 44 +++++++++++++++ linter/src/TestRunner.ts | 37 +++++++------ linter/src/main.ts | 8 +++ linter/src/ts-compiler/FormTscOptions.ts | 2 +- linter/tsconfig.json | 4 +- 64 files changed, 223 insertions(+), 77 deletions(-) rename linter/{src => lib}/Autofixer.ts (100%) rename linter/{src => lib}/CommandLineOptions.ts (100%) create mode 100644 linter/lib/Compiler.ts rename linter/{src => lib}/CookBookMsg.ts (100%) rename linter/{src => lib}/FaultAttrs.ts (100%) rename linter/{src => lib}/FaultDesc.ts (100%) rename linter/{src => lib}/IncrementalLintInfo.ts (100%) rename linter/{src => lib}/IsFileFromModuleCallback.ts (100%) rename linter/{src => lib}/LintOptions.ts (100%) rename linter/{src => lib}/LintRunResult.ts (100%) rename linter/{src => lib}/LinterRunner.ts (98%) create mode 100644 linter/lib/Logger.ts rename linter/{src => lib}/ProblemInfo.ts (100%) rename linter/{src => lib}/ProblemSeverity.ts (100%) rename linter/{src => lib}/Problems.ts (100%) rename linter/{src => lib}/TypeScriptLinter.ts (99%) rename linter/{src => lib}/TypeScriptLinterConfig.ts (100%) rename linter/{src => lib}/autofixes/AutofixInfo.ts (100%) rename linter/{src => lib}/autofixes/AutofixTitles.ts (100%) rename linter/{src => lib}/autofixes/ReportAutofixCallback.ts (100%) rename linter/{src => lib}/ts-diagnostics/GetTscDiagnostics.ts (100%) rename linter/{src => lib}/ts-diagnostics/TSCCompiledProgram.ts (97%) rename linter/{src => lib}/ts-diagnostics/TransformTscDiagnostics.ts (100%) rename linter/{src => lib}/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts (100%) rename linter/{src => lib}/utils/TsUtils.ts (99%) rename linter/{src => lib}/utils/consts/AllowedStdSymbolAPI.ts (100%) rename linter/{src => lib}/utils/consts/ArkUIDecorators.ts (100%) rename linter/{src => lib}/utils/consts/ArktsIgnorePaths.ts (100%) rename linter/{src => lib}/utils/consts/ESObject.ts (100%) rename linter/{src => lib}/utils/consts/FunctionHasNoReturnErrorCode.ts (100%) rename linter/{src => lib}/utils/consts/LimitedStandardUtilityTypes.ts (100%) rename linter/{src => lib}/utils/consts/LimitedStdGlobalFunc.ts (100%) rename linter/{src => lib}/utils/consts/LimitedStdObjectAPI.ts (100%) rename linter/{src => lib}/utils/consts/LimitedStdProxyHandlerAPI.ts (100%) rename linter/{src => lib}/utils/consts/LimitedStdReflectAPI.ts (100%) rename linter/{src => lib}/utils/consts/NonInitializablePropertyDecorators.ts (100%) rename linter/{src => lib}/utils/consts/NonReturnFunctionDecorators.ts (100%) rename linter/{src => lib}/utils/consts/PropertyHasNoInitializerErrorCode.ts (100%) rename linter/{src => lib}/utils/consts/StandardLibraries.ts (100%) rename linter/{src => lib}/utils/consts/TypedArrays.ts (100%) rename linter/{src => lib}/utils/functions/ContainsThis.ts (100%) rename linter/{src => lib}/utils/functions/DiagnosticChecker.ts (100%) rename linter/{src => lib}/utils/functions/ForEachNodeInSubtree.ts (100%) rename linter/{src => lib}/utils/functions/GetScriptKind.ts (100%) rename linter/{src => lib}/utils/functions/HasPredecessor.ts (100%) rename linter/{src => lib}/utils/functions/IsStdLibrary.ts (100%) rename linter/{src => lib}/utils/functions/IsStruct.ts (100%) rename linter/{src => lib}/utils/functions/LibraryTypeCallDiagnosticChecker.ts (100%) rename linter/{src => lib}/utils/functions/LinterInfo.ts (100%) rename linter/{src => lib}/utils/functions/LogTscDiagnostic.ts (88%) rename linter/{src => lib}/utils/functions/MergeArrayMaps.ts (100%) rename linter/{src => lib}/utils/functions/PathHelper.ts (100%) rename linter/{src => lib}/utils/functions/identiferUseInValueContext.ts (100%) rename linter/{src => lib}/utils/functions/isAssignmentOperator.ts (100%) rename linter/{src => lib}/utils/functions/isIntrinsicObjectType.ts (100%) rename linter/src/{CompilerWrapper.ts => CompilerImpl.ts} (36%) create mode 100644 linter/src/LoggerImpl.ts diff --git a/linter/src/Autofixer.ts b/linter/lib/Autofixer.ts similarity index 100% rename from linter/src/Autofixer.ts rename to linter/lib/Autofixer.ts diff --git a/linter/src/CommandLineOptions.ts b/linter/lib/CommandLineOptions.ts similarity index 100% rename from linter/src/CommandLineOptions.ts rename to linter/lib/CommandLineOptions.ts diff --git a/linter/lib/Compiler.ts b/linter/lib/Compiler.ts new file mode 100644 index 00000000..b8c2aa55 --- /dev/null +++ b/linter/lib/Compiler.ts @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { LintOptions } from './LintOptions'; +import type * as ts from 'typescript'; + +export abstract class Compiler { + static init(instance: Compiler): void { + this.instance_ = instance; + } + + static compile(options: LintOptions, extraOptions?: any): ts.Program { + return this.getInstance().doCompile(options, extraOptions); + } + + protected abstract doCompile(options: LintOptions, extraOptions?: any): ts.Program; + + private static getInstance(): Compiler { + if (!this.instance_) { + throw new Error('Not initialized'); + } + return this.instance_; + } + + private static instance_?: Compiler; +} diff --git a/linter/src/CookBookMsg.ts b/linter/lib/CookBookMsg.ts similarity index 100% rename from linter/src/CookBookMsg.ts rename to linter/lib/CookBookMsg.ts diff --git a/linter/src/FaultAttrs.ts b/linter/lib/FaultAttrs.ts similarity index 100% rename from linter/src/FaultAttrs.ts rename to linter/lib/FaultAttrs.ts diff --git a/linter/src/FaultDesc.ts b/linter/lib/FaultDesc.ts similarity index 100% rename from linter/src/FaultDesc.ts rename to linter/lib/FaultDesc.ts diff --git a/linter/src/IncrementalLintInfo.ts b/linter/lib/IncrementalLintInfo.ts similarity index 100% rename from linter/src/IncrementalLintInfo.ts rename to linter/lib/IncrementalLintInfo.ts diff --git a/linter/src/IsFileFromModuleCallback.ts b/linter/lib/IsFileFromModuleCallback.ts similarity index 100% rename from linter/src/IsFileFromModuleCallback.ts rename to linter/lib/IsFileFromModuleCallback.ts diff --git a/linter/src/LintOptions.ts b/linter/lib/LintOptions.ts similarity index 100% rename from linter/src/LintOptions.ts rename to linter/lib/LintOptions.ts diff --git a/linter/src/LintRunResult.ts b/linter/lib/LintRunResult.ts similarity index 100% rename from linter/src/LintRunResult.ts rename to linter/lib/LintRunResult.ts diff --git a/linter/src/LinterRunner.ts b/linter/lib/LinterRunner.ts similarity index 98% rename from linter/src/LinterRunner.ts rename to linter/lib/LinterRunner.ts index 2737bdb7..48254ef0 100644 --- a/linter/src/LinterRunner.ts +++ b/linter/lib/LinterRunner.ts @@ -21,7 +21,7 @@ import { faultDesc } from './FaultDesc'; import { faultsAttrs } from './FaultAttrs'; import type { LintRunResult } from './LintRunResult'; import * as path from 'node:path'; -import { compile } from './CompilerWrapper'; +import { Compiler } from './Compiler'; import type { LintOptions } from './LintOptions'; import type { CommandLineOptions } from './CommandLineOptions'; import { AutofixInfoSet } from './Autofixer'; @@ -137,7 +137,7 @@ export function createLinter(options: LintOptions): TSCCompiledProgram { if (options.tscDiagnosticsLinter) { return options.tscDiagnosticsLinter; } - const tsProgram = options.tsProgram ?? compile(options, getStrictOptions()); + const tsProgram = options.tsProgram ?? Compiler.compile(options, getStrictOptions()); if (options.realtimeLint) { return new TSCCompiledProgramSimple(tsProgram); } diff --git a/linter/lib/Logger.ts b/linter/lib/Logger.ts new file mode 100644 index 00000000..73002788 --- /dev/null +++ b/linter/lib/Logger.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export abstract class Logger { + static init(instance: Logger): void { + this.instance_ = instance; + } + + static trace(message: string): void { + this.getInstance().doTrace(message); + } + + static debug(message: string): void { + this.getInstance().doDebug(message); + } + + static info(message: string): void { + this.getInstance().doInfo(message); + } + + static warn(message: string): void { + this.getInstance().doWarn(message); + } + + static error(message: string): void { + this.getInstance().doError(message); + } + + protected abstract doTrace(message: string): void; + protected abstract doDebug(message: string): void; + protected abstract doInfo(message: string): void; + protected abstract doWarn(message: string): void; + protected abstract doError(message: string): void; + + private static getInstance(): Logger { + if (!this.instance_) { + throw new Error('Not initialized'); + } + return this.instance_; + } + + private static instance_?: Logger; +} diff --git a/linter/src/ProblemInfo.ts b/linter/lib/ProblemInfo.ts similarity index 100% rename from linter/src/ProblemInfo.ts rename to linter/lib/ProblemInfo.ts diff --git a/linter/src/ProblemSeverity.ts b/linter/lib/ProblemSeverity.ts similarity index 100% rename from linter/src/ProblemSeverity.ts rename to linter/lib/ProblemSeverity.ts diff --git a/linter/src/Problems.ts b/linter/lib/Problems.ts similarity index 100% rename from linter/src/Problems.ts rename to linter/lib/Problems.ts diff --git a/linter/src/TypeScriptLinter.ts b/linter/lib/TypeScriptLinter.ts similarity index 99% rename from linter/src/TypeScriptLinter.ts rename to linter/lib/TypeScriptLinter.ts index d2e12bef..97c357ec 100644 --- a/linter/src/TypeScriptLinter.ts +++ b/linter/lib/TypeScriptLinter.ts @@ -25,7 +25,7 @@ import type { Autofix, AutofixInfoSet } from './Autofixer'; import * as Autofixer from './Autofixer'; import type { ProblemInfo } from './ProblemInfo'; import { ProblemSeverity } from './ProblemSeverity'; -import Logger from '../utils/logger'; +import { Logger } from './Logger'; import { ARKUI_DECORATORS } from './utils/consts/ArkUIDecorators'; import { LIMITED_STD_GLOBAL_FUNC } from './utils/consts/LimitedStdGlobalFunc'; import { LIMITED_STD_OBJECT_API } from './utils/consts/LimitedStdObjectAPI'; @@ -58,8 +58,6 @@ import { } from './utils/functions/LibraryTypeCallDiagnosticChecker'; import { forEachNodeInSubtree } from './utils/functions/ForEachNodeInSubtree'; -const logger = Logger.getLogger(); - export function consoleLog(...args: unknown[]): void { if (TypeScriptLinter.ideMode) { return; @@ -68,7 +66,7 @@ export function consoleLog(...args: unknown[]): void { for (let k = 0; k < args.length; k++) { outLine += `${args[k]} `; } - logger.info(outLine); + Logger.info(outLine); } export class TypeScriptLinter { @@ -202,7 +200,7 @@ export class TypeScriptLinter { } else { const faultDescr = faultDesc[faultId]; const faultType = LinterConfig.tsSyntaxKindNames[node.kind]; - logger.info( + Logger.info( `Warning: ${this.sourceFile!.fileName} (${line}, ${character}): ${faultDescr ? faultDescr : faultType}` ); } @@ -1456,7 +1454,7 @@ export class TypeScriptLinter { private handleElementAccessExpression(node: ts.Node): void { const tsElementAccessExpr = node as ts.ElementAccessExpression; - let tsElemAccessBaseExprType = TsUtils.getNonNullableType( + const tsElemAccessBaseExprType = TsUtils.getNonNullableType( this.tsUtils.getTypeOrTypeConstraintAtLocation(tsElementAccessExpr.expression) ); const tsElemAccessBaseExprTypeNode = this.tsTypeChecker.typeToTypeNode( diff --git a/linter/src/TypeScriptLinterConfig.ts b/linter/lib/TypeScriptLinterConfig.ts similarity index 100% rename from linter/src/TypeScriptLinterConfig.ts rename to linter/lib/TypeScriptLinterConfig.ts diff --git a/linter/src/autofixes/AutofixInfo.ts b/linter/lib/autofixes/AutofixInfo.ts similarity index 100% rename from linter/src/autofixes/AutofixInfo.ts rename to linter/lib/autofixes/AutofixInfo.ts diff --git a/linter/src/autofixes/AutofixTitles.ts b/linter/lib/autofixes/AutofixTitles.ts similarity index 100% rename from linter/src/autofixes/AutofixTitles.ts rename to linter/lib/autofixes/AutofixTitles.ts diff --git a/linter/src/autofixes/ReportAutofixCallback.ts b/linter/lib/autofixes/ReportAutofixCallback.ts similarity index 100% rename from linter/src/autofixes/ReportAutofixCallback.ts rename to linter/lib/autofixes/ReportAutofixCallback.ts diff --git a/linter/src/ts-diagnostics/GetTscDiagnostics.ts b/linter/lib/ts-diagnostics/GetTscDiagnostics.ts similarity index 100% rename from linter/src/ts-diagnostics/GetTscDiagnostics.ts rename to linter/lib/ts-diagnostics/GetTscDiagnostics.ts diff --git a/linter/src/ts-diagnostics/TSCCompiledProgram.ts b/linter/lib/ts-diagnostics/TSCCompiledProgram.ts similarity index 97% rename from linter/src/ts-diagnostics/TSCCompiledProgram.ts rename to linter/lib/ts-diagnostics/TSCCompiledProgram.ts index 6e203aa3..77d28883 100644 --- a/linter/src/ts-diagnostics/TSCCompiledProgram.ts +++ b/linter/lib/ts-diagnostics/TSCCompiledProgram.ts @@ -18,7 +18,7 @@ import type { ProblemInfo } from '../ProblemInfo'; import { ProblemSeverity } from '../ProblemSeverity'; import type { LintOptions } from '../LintOptions'; import { TypeScriptDiagnosticsExtractor } from './TypeScriptDiagnosticsExtractor'; -import { compile } from '../CompilerWrapper'; +import { Compiler } from '../Compiler'; import { FaultID } from '../Problems'; import { faultsAttrs } from '../FaultAttrs'; @@ -94,7 +94,7 @@ function getTwoCompiledVersions( const wasStrict = inverseStrictOptions(compilerOptions); const inversedOptions = getStrictOptions(!wasStrict); - const withInversedOptions = compile(options, inversedOptions); + const withInversedOptions = Compiler.compile(options, inversedOptions); return { strict: wasStrict ? program : withInversedOptions, diff --git a/linter/src/ts-diagnostics/TransformTscDiagnostics.ts b/linter/lib/ts-diagnostics/TransformTscDiagnostics.ts similarity index 100% rename from linter/src/ts-diagnostics/TransformTscDiagnostics.ts rename to linter/lib/ts-diagnostics/TransformTscDiagnostics.ts diff --git a/linter/src/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts b/linter/lib/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts similarity index 100% rename from linter/src/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts rename to linter/lib/ts-diagnostics/TypeScriptDiagnosticsExtractor.ts diff --git a/linter/src/utils/TsUtils.ts b/linter/lib/utils/TsUtils.ts similarity index 99% rename from linter/src/utils/TsUtils.ts rename to linter/lib/utils/TsUtils.ts index d9de5037..e3cd75be 100644 --- a/linter/src/utils/TsUtils.ts +++ b/linter/lib/utils/TsUtils.ts @@ -858,7 +858,7 @@ export class TsUtils { return true; } - public static getNonNullableType(t: ts.Type): ts.Type { + static getNonNullableType(t: ts.Type): ts.Type { if (TsUtils.isNullableUnionType(t)) { return t.getNonNullableType(); } diff --git a/linter/src/utils/consts/AllowedStdSymbolAPI.ts b/linter/lib/utils/consts/AllowedStdSymbolAPI.ts similarity index 100% rename from linter/src/utils/consts/AllowedStdSymbolAPI.ts rename to linter/lib/utils/consts/AllowedStdSymbolAPI.ts diff --git a/linter/src/utils/consts/ArkUIDecorators.ts b/linter/lib/utils/consts/ArkUIDecorators.ts similarity index 100% rename from linter/src/utils/consts/ArkUIDecorators.ts rename to linter/lib/utils/consts/ArkUIDecorators.ts diff --git a/linter/src/utils/consts/ArktsIgnorePaths.ts b/linter/lib/utils/consts/ArktsIgnorePaths.ts similarity index 100% rename from linter/src/utils/consts/ArktsIgnorePaths.ts rename to linter/lib/utils/consts/ArktsIgnorePaths.ts diff --git a/linter/src/utils/consts/ESObject.ts b/linter/lib/utils/consts/ESObject.ts similarity index 100% rename from linter/src/utils/consts/ESObject.ts rename to linter/lib/utils/consts/ESObject.ts diff --git a/linter/src/utils/consts/FunctionHasNoReturnErrorCode.ts b/linter/lib/utils/consts/FunctionHasNoReturnErrorCode.ts similarity index 100% rename from linter/src/utils/consts/FunctionHasNoReturnErrorCode.ts rename to linter/lib/utils/consts/FunctionHasNoReturnErrorCode.ts diff --git a/linter/src/utils/consts/LimitedStandardUtilityTypes.ts b/linter/lib/utils/consts/LimitedStandardUtilityTypes.ts similarity index 100% rename from linter/src/utils/consts/LimitedStandardUtilityTypes.ts rename to linter/lib/utils/consts/LimitedStandardUtilityTypes.ts diff --git a/linter/src/utils/consts/LimitedStdGlobalFunc.ts b/linter/lib/utils/consts/LimitedStdGlobalFunc.ts similarity index 100% rename from linter/src/utils/consts/LimitedStdGlobalFunc.ts rename to linter/lib/utils/consts/LimitedStdGlobalFunc.ts diff --git a/linter/src/utils/consts/LimitedStdObjectAPI.ts b/linter/lib/utils/consts/LimitedStdObjectAPI.ts similarity index 100% rename from linter/src/utils/consts/LimitedStdObjectAPI.ts rename to linter/lib/utils/consts/LimitedStdObjectAPI.ts diff --git a/linter/src/utils/consts/LimitedStdProxyHandlerAPI.ts b/linter/lib/utils/consts/LimitedStdProxyHandlerAPI.ts similarity index 100% rename from linter/src/utils/consts/LimitedStdProxyHandlerAPI.ts rename to linter/lib/utils/consts/LimitedStdProxyHandlerAPI.ts diff --git a/linter/src/utils/consts/LimitedStdReflectAPI.ts b/linter/lib/utils/consts/LimitedStdReflectAPI.ts similarity index 100% rename from linter/src/utils/consts/LimitedStdReflectAPI.ts rename to linter/lib/utils/consts/LimitedStdReflectAPI.ts diff --git a/linter/src/utils/consts/NonInitializablePropertyDecorators.ts b/linter/lib/utils/consts/NonInitializablePropertyDecorators.ts similarity index 100% rename from linter/src/utils/consts/NonInitializablePropertyDecorators.ts rename to linter/lib/utils/consts/NonInitializablePropertyDecorators.ts diff --git a/linter/src/utils/consts/NonReturnFunctionDecorators.ts b/linter/lib/utils/consts/NonReturnFunctionDecorators.ts similarity index 100% rename from linter/src/utils/consts/NonReturnFunctionDecorators.ts rename to linter/lib/utils/consts/NonReturnFunctionDecorators.ts diff --git a/linter/src/utils/consts/PropertyHasNoInitializerErrorCode.ts b/linter/lib/utils/consts/PropertyHasNoInitializerErrorCode.ts similarity index 100% rename from linter/src/utils/consts/PropertyHasNoInitializerErrorCode.ts rename to linter/lib/utils/consts/PropertyHasNoInitializerErrorCode.ts diff --git a/linter/src/utils/consts/StandardLibraries.ts b/linter/lib/utils/consts/StandardLibraries.ts similarity index 100% rename from linter/src/utils/consts/StandardLibraries.ts rename to linter/lib/utils/consts/StandardLibraries.ts diff --git a/linter/src/utils/consts/TypedArrays.ts b/linter/lib/utils/consts/TypedArrays.ts similarity index 100% rename from linter/src/utils/consts/TypedArrays.ts rename to linter/lib/utils/consts/TypedArrays.ts diff --git a/linter/src/utils/functions/ContainsThis.ts b/linter/lib/utils/functions/ContainsThis.ts similarity index 100% rename from linter/src/utils/functions/ContainsThis.ts rename to linter/lib/utils/functions/ContainsThis.ts diff --git a/linter/src/utils/functions/DiagnosticChecker.ts b/linter/lib/utils/functions/DiagnosticChecker.ts similarity index 100% rename from linter/src/utils/functions/DiagnosticChecker.ts rename to linter/lib/utils/functions/DiagnosticChecker.ts diff --git a/linter/src/utils/functions/ForEachNodeInSubtree.ts b/linter/lib/utils/functions/ForEachNodeInSubtree.ts similarity index 100% rename from linter/src/utils/functions/ForEachNodeInSubtree.ts rename to linter/lib/utils/functions/ForEachNodeInSubtree.ts diff --git a/linter/src/utils/functions/GetScriptKind.ts b/linter/lib/utils/functions/GetScriptKind.ts similarity index 100% rename from linter/src/utils/functions/GetScriptKind.ts rename to linter/lib/utils/functions/GetScriptKind.ts diff --git a/linter/src/utils/functions/HasPredecessor.ts b/linter/lib/utils/functions/HasPredecessor.ts similarity index 100% rename from linter/src/utils/functions/HasPredecessor.ts rename to linter/lib/utils/functions/HasPredecessor.ts diff --git a/linter/src/utils/functions/IsStdLibrary.ts b/linter/lib/utils/functions/IsStdLibrary.ts similarity index 100% rename from linter/src/utils/functions/IsStdLibrary.ts rename to linter/lib/utils/functions/IsStdLibrary.ts diff --git a/linter/src/utils/functions/IsStruct.ts b/linter/lib/utils/functions/IsStruct.ts similarity index 100% rename from linter/src/utils/functions/IsStruct.ts rename to linter/lib/utils/functions/IsStruct.ts diff --git a/linter/src/utils/functions/LibraryTypeCallDiagnosticChecker.ts b/linter/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts similarity index 100% rename from linter/src/utils/functions/LibraryTypeCallDiagnosticChecker.ts rename to linter/lib/utils/functions/LibraryTypeCallDiagnosticChecker.ts diff --git a/linter/src/utils/functions/LinterInfo.ts b/linter/lib/utils/functions/LinterInfo.ts similarity index 100% rename from linter/src/utils/functions/LinterInfo.ts rename to linter/lib/utils/functions/LinterInfo.ts diff --git a/linter/src/utils/functions/LogTscDiagnostic.ts b/linter/lib/utils/functions/LogTscDiagnostic.ts similarity index 88% rename from linter/src/utils/functions/LogTscDiagnostic.ts rename to linter/lib/utils/functions/LogTscDiagnostic.ts index a12d9c4e..23a8ab16 100644 --- a/linter/src/utils/functions/LogTscDiagnostic.ts +++ b/linter/lib/utils/functions/LogTscDiagnostic.ts @@ -15,10 +15,7 @@ import * as ts from 'typescript'; -export function logTscDiagnostic( - diagnostics: readonly ts.Diagnostic[], - log: (message: unknown, ...args: unknown[]) => void -): void { +export function logTscDiagnostic(diagnostics: readonly ts.Diagnostic[], log: (message: string) => void): void { diagnostics.forEach((diagnostic) => { let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); diff --git a/linter/src/utils/functions/MergeArrayMaps.ts b/linter/lib/utils/functions/MergeArrayMaps.ts similarity index 100% rename from linter/src/utils/functions/MergeArrayMaps.ts rename to linter/lib/utils/functions/MergeArrayMaps.ts diff --git a/linter/src/utils/functions/PathHelper.ts b/linter/lib/utils/functions/PathHelper.ts similarity index 100% rename from linter/src/utils/functions/PathHelper.ts rename to linter/lib/utils/functions/PathHelper.ts diff --git a/linter/src/utils/functions/identiferUseInValueContext.ts b/linter/lib/utils/functions/identiferUseInValueContext.ts similarity index 100% rename from linter/src/utils/functions/identiferUseInValueContext.ts rename to linter/lib/utils/functions/identiferUseInValueContext.ts diff --git a/linter/src/utils/functions/isAssignmentOperator.ts b/linter/lib/utils/functions/isAssignmentOperator.ts similarity index 100% rename from linter/src/utils/functions/isAssignmentOperator.ts rename to linter/lib/utils/functions/isAssignmentOperator.ts diff --git a/linter/src/utils/functions/isIntrinsicObjectType.ts b/linter/lib/utils/functions/isIntrinsicObjectType.ts similarity index 100% rename from linter/src/utils/functions/isIntrinsicObjectType.ts rename to linter/lib/utils/functions/isIntrinsicObjectType.ts diff --git a/linter/package.json b/linter/package.json index 6acb1be1..5ac5d3df 100644 --- a/linter/package.json +++ b/linter/package.json @@ -21,9 +21,9 @@ "test_main": "npm run compile && rimraf test/results && node build/src/TestRunner.js test", "test_rules": "npm run compile && rimraf test_rules/results && node build/src/TestRunner.js test_rules", "update-tests": "node scripts/update-test-results.mjs test test_rules", - "eslint-check": "npx eslint --ext .ts src", + "eslint-check": "npx eslint --ext .ts src lib", "eslint-fix": "npm run eslint-check -- --fix", - "prettier-fix": "prettier src --write", + "prettier-fix": "prettier src lib --write", "fix": "npm run prettier-fix && npm run eslint-fix" }, "dependencies": { diff --git a/linter/src/CommandLineParser.ts b/linter/src/CommandLineParser.ts index 77c4116c..aa06dcca 100644 --- a/linter/src/CommandLineParser.ts +++ b/linter/src/CommandLineParser.ts @@ -13,11 +13,11 @@ * limitations under the License. */ -import Logger from '../utils/logger'; -import { logTscDiagnostic } from './utils/functions/LogTscDiagnostic'; -import { decodeAutofixInfo } from './utils/functions/LinterInfo'; -import type { CommandLineOptions } from './CommandLineOptions'; -import { AUTOFIX_ALL } from './Autofixer'; +import { Logger } from '../lib/Logger'; +import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic'; +import { decodeAutofixInfo } from '../lib/utils/functions/LinterInfo'; +import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import { AUTOFIX_ALL } from '../lib/Autofixer'; import { Command, Option } from 'commander'; import * as ts from 'typescript'; import * as fs from 'node:fs'; @@ -28,8 +28,6 @@ const TSX_EXT = '.tsx'; const ETS_EXT = '.ets'; const JSON_EXT = '.json'; -const logger = Logger.getLogger(); - let inputFiles: string[]; let responseFile = ''; function addSrcFile(value: string): void { @@ -132,7 +130,7 @@ export function parseCommandLine(commandLineArgs: string[]): CommandLineOptions cmdArgs.push(...commandLineArgs); program.parse(cmdArgs); } catch (error) { - logger.error('Failed to read response file: ', error); + Logger.error('Failed to read response file: ' + error); process.exit(-1); } } @@ -146,7 +144,7 @@ function doProjectFolderArg(prjFolders: string[], opts: CommandLineOptions): voi try { opts.inputFiles.push(...getFiles(prjFolderPath)); } catch (error) { - logger.error('Failed to read folder: ', error); + Logger.error('Failed to read folder: ' + error); process.exit(-1); } } @@ -174,12 +172,12 @@ function doProjectArg(cfgPath: string, opts: CommandLineOptions): void { if (diagnostics.length > 0) { // Log all diagnostic messages and exit program. - logger.error('Failed to read config file.'); - logTscDiagnostic(diagnostics, logger.info); + Logger.error('Failed to read config file.'); + logTscDiagnostic(diagnostics, Logger.info); process.exit(-1); } } catch (error) { - logger.error('Failed to read config file: ', error); + Logger.error('Failed to read config file: ' + error); process.exit(-1); } } diff --git a/linter/src/CompilerWrapper.ts b/linter/src/CompilerImpl.ts similarity index 36% rename from linter/src/CompilerWrapper.ts rename to linter/src/CompilerImpl.ts index 7bbd5327..2a8c8512 100644 --- a/linter/src/CompilerWrapper.ts +++ b/linter/src/CompilerImpl.ts @@ -13,28 +13,33 @@ * limitations under the License. */ +import { Compiler as CompilerInterface } from '../lib/Compiler'; import * as ts from 'typescript'; -import { logTscDiagnostic } from './utils/functions/LogTscDiagnostic'; -import { consoleLog } from './TypeScriptLinter'; +import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic'; +import { consoleLog } from '../lib/TypeScriptLinter'; import { formTscOptions } from './ts-compiler/FormTscOptions'; -import type { LintOptions } from './LintOptions'; +import type { LintOptions } from '../lib/LintOptions'; -export function compile(options: LintOptions, extraOptions?: unknown): ts.Program { - const createProgramOptions = formTscOptions(options.cmdOptions, extraOptions); - const program = ts.createProgram(createProgramOptions); - // Log Tsc errors if needed - if (options.cmdOptions.logTscErrors) { - const diagnostics = ts.getPreEmitDiagnostics(program); - logTscDiagnostic(diagnostics, consoleLog); - diagnostics.forEach((diagnostic) => { - if (diagnostic.file && diagnostic.start) { - const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); - const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); - consoleLog(`${diagnostic.file.fileName} (${line + 1}, ${character + 1}): ${message}`); - } else { - consoleLog(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); - } - }); +export class CompilerImpl extends CompilerInterface { + doCompile(options: LintOptions, extraOptions?: unknown): ts.Program { + void this; + + const createProgramOptions = formTscOptions(options.cmdOptions, extraOptions); + const program = ts.createProgram(createProgramOptions); + // Log Tsc errors if needed + if (options.cmdOptions.logTscErrors) { + const diagnostics = ts.getPreEmitDiagnostics(program); + logTscDiagnostic(diagnostics, consoleLog); + diagnostics.forEach((diagnostic) => { + if (diagnostic.file && diagnostic.start) { + const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + consoleLog(`${diagnostic.file.fileName} (${line + 1}, ${character + 1}): ${message}`); + } else { + consoleLog(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + } + }); + } + return program; } - return program; } diff --git a/linter/src/LinterCLI.ts b/linter/src/LinterCLI.ts index ae6ad55a..4dc1cc79 100644 --- a/linter/src/LinterCLI.ts +++ b/linter/src/LinterCLI.ts @@ -13,22 +13,20 @@ * limitations under the License. */ -import { TypeScriptLinter } from './TypeScriptLinter'; +import { TypeScriptLinter } from '../lib/TypeScriptLinter'; import { parseCommandLine } from './CommandLineParser'; -import Logger from '../utils/logger'; +import { Logger } from '../lib/Logger'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as readline from 'node:readline'; import * as path from 'node:path'; -import type { CommandLineOptions } from './CommandLineOptions'; -import { lint } from './LinterRunner'; - -const logger = Logger.getLogger(); +import type { CommandLineOptions } from '../lib/CommandLineOptions'; +import { lint } from '../lib/LinterRunner'; export function run(): void { const commandLineArgs = process.argv.slice(2); if (commandLineArgs.length === 0) { - logger.info('Command line error: no arguments'); + Logger.info('Command line error: no arguments'); process.exit(-1); } @@ -90,9 +88,9 @@ function runIDEMode(cmdOptions: CommandLineOptions): void { autofix: x.autofix }; }); - logger.info(`{"linter messages":${JSON.stringify(jsonMessage)}}`); + Logger.info(`{"linter messages":${JSON.stringify(jsonMessage)}}`); } else { - logger.error('Unexpected error: could not lint file'); + Logger.error('Unexpected error: could not lint file'); } fs.unlinkSync(tmpFileName); }); diff --git a/linter/src/LoggerImpl.ts b/linter/src/LoggerImpl.ts new file mode 100644 index 00000000..2ea17592 --- /dev/null +++ b/linter/src/LoggerImpl.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Logger as LoggerInterface } from '../lib/Logger'; +import Logger from '../utils/logger'; + +export class LoggerImpl extends LoggerInterface { + doTrace(message: string): void { + void this; + Logger.getLogger().trace(message); + } + + doDebug(message: string): void { + void this; + Logger.getLogger().debug(message); + } + + doInfo(message: string): void { + void this; + Logger.getLogger().info(message); + } + + doWarn(message: string): void { + void this; + Logger.getLogger().warn(message); + } + + doError(message: string): void { + void this; + Logger.getLogger().error(message); + } +} diff --git a/linter/src/TestRunner.ts b/linter/src/TestRunner.ts index d2fbb0ca..563194ee 100644 --- a/linter/src/TestRunner.ts +++ b/linter/src/TestRunner.ts @@ -13,21 +13,26 @@ * limitations under the License. */ -import { TypeScriptLinter } from './TypeScriptLinter'; -import { lint } from './LinterRunner'; +import { Logger } from '../lib/Logger'; +import { LoggerImpl } from './LoggerImpl'; +Logger.init(new LoggerImpl()); + +import { Compiler } from '../lib/Compiler'; +import { CompilerImpl } from './CompilerImpl'; +Compiler.init(new CompilerImpl()); + +import { TypeScriptLinter } from '../lib/TypeScriptLinter'; +import { lint } from '../lib/LinterRunner'; import { parseCommandLine } from './CommandLineParser'; -import type { Autofix } from './Autofixer'; -import Logger from '../utils/logger'; +import type { Autofix } from '../lib/Autofixer'; import * as fs from 'node:fs'; import * as path from 'node:path'; import * as ts from 'typescript'; -import type { CommandLineOptions } from './CommandLineOptions'; +import type { CommandLineOptions } from '../lib/CommandLineOptions'; const TEST_DIR = 'test'; const TAB = ' '; -const logger = Logger.getLogger(); - interface TestNodeInfo { line: number; column: number; @@ -76,7 +81,7 @@ function runTests(testDirs: string[]): number { x.trimEnd().endsWith(ts.Extension.Tsx) ); }); - logger.info(`\nProcessing "${testDir}" directory:\n`); + Logger.info(`\nProcessing "${testDir}" directory:\n`); // Run each test in Strict, Autofix, and Relax mode: for (const testFile of testFiles) { if (runTest(testDir, testFile, Mode.STRICT)) { @@ -99,8 +104,8 @@ function runTests(testDirs: string[]): number { } } } - logger.info(`\nSUMMARY: ${passed + failed} total, ${passed} passed or skipped, ${failed} failed.`); - logger.info(failed > 0 ? '\nTEST FAILED' : '\nTEST SUCCESSFUL'); + Logger.info(`\nSUMMARY: ${passed + failed} total, ${passed} passed or skipped, ${failed} failed.`); + Logger.info(failed > 0 ? '\nTEST FAILED' : '\nTEST SUCCESSFUL'); process.exit(hasComparisonFailures ? -1 : 0); } @@ -143,16 +148,16 @@ function compareExpectedAndActual(testDir: string, testFile: string, mode: Mode, if (!expectedResult?.nodes || expectedResult.nodes.length !== resultNodes.length) { const expectedResultCount = expectedResult?.nodes ? expectedResult.nodes.length : 0; diff = `Expected count: ${expectedResultCount} vs actual count: ${resultNodes.length}`; - logger.info(`${TAB}${diff}`); + Logger.info(`${TAB}${diff}`); } else { diff = expectedAndActualMatch(expectedResult.nodes, resultNodes); } if (diff) { - logger.info(`${TAB}Test failed. Expected and actual results differ.`); + Logger.info(`${TAB}Test failed. Expected and actual results differ.`); } } catch (error) { - logger.info(`${TAB}Test failed. `, error); + Logger.info(`${TAB}Test failed. ` + error); } return diff; @@ -160,10 +165,10 @@ function compareExpectedAndActual(testDir: string, testFile: string, mode: Mode, function runTest(testDir: string, testFile: string, mode: Mode): boolean { if (mode === Mode.AUTOFIX && fs.existsSync(path.join(testDir, testFile + AUTOFIX_SKIP_EXT))) { - logger.info(`Skipping test ${testFile} (${Mode[mode]} mode)`); + Logger.info(`Skipping test ${testFile} (${Mode[mode]} mode)`); return false; } - logger.info(`Running test ${testFile} (${Mode[mode]} mode)`); + Logger.info(`Running test ${testFile} (${Mode[mode]} mode)`); TypeScriptLinter.initGlobals(); @@ -271,7 +276,7 @@ ${expectedNode} Actual: ${actualNode}`; - logger.info(diff); + Logger.info(diff); return diff; } diff --git a/linter/src/main.ts b/linter/src/main.ts index e1b7ecf9..6ffe1703 100644 --- a/linter/src/main.ts +++ b/linter/src/main.ts @@ -13,6 +13,14 @@ * limitations under the License. */ +import { Logger } from '../lib/Logger'; +import { LoggerImpl } from './LoggerImpl'; +Logger.init(new LoggerImpl()); + +import { Compiler } from '../lib/Compiler'; +import { CompilerImpl } from './CompilerImpl'; +Compiler.init(new CompilerImpl()); + import { run } from './LinterCLI'; run(); diff --git a/linter/src/ts-compiler/FormTscOptions.ts b/linter/src/ts-compiler/FormTscOptions.ts index 19fce66c..de293100 100644 --- a/linter/src/ts-compiler/FormTscOptions.ts +++ b/linter/src/ts-compiler/FormTscOptions.ts @@ -14,7 +14,7 @@ */ import * as ts from 'typescript'; -import type { CommandLineOptions } from '../CommandLineOptions'; +import type { CommandLineOptions } from '../../lib/CommandLineOptions'; export function formTscOptions(cmdOptions: CommandLineOptions, extraOptions?: unknown): ts.CreateProgramOptions { if (cmdOptions.parsedConfigFile) { diff --git a/linter/tsconfig.json b/linter/tsconfig.json index 38bce99f..5e1d00ae 100644 --- a/linter/tsconfig.json +++ b/linter/tsconfig.json @@ -12,5 +12,5 @@ "strict": true }, - "include": ["src/**/*", "utils/*"] -} \ No newline at end of file + "include": ["src/**/*", "lib/**/*", "utils/*"] +} -- Gitee