From d9ac2573a3fabc912f0cde420f9f10d254b1bd5f Mon Sep 17 00:00:00 2001 From: Igor Rossinski Date: Mon, 20 Nov 2023 13:55:45 +0300 Subject: [PATCH] [ArkTS Linter] additional code style fixes issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/I8I006 test: CI build Signed-off-by: Igor Rossinski --- .../src/cookbook_convertor.ts | 298 +++++++++--------- ets2panda/linter-4.2/src/Autofixer.ts | 20 +- ets2panda/linter-4.2/src/CommandLineParser.ts | 18 +- ets2panda/linter-4.2/src/LinterRunner.ts | 16 +- ets2panda/linter-4.2/src/Problems.ts | 180 +++++------ ets2panda/linter-4.2/src/TestRunner.ts | 13 +- ets2panda/linter-4.2/src/TypeScriptLinter.ts | 202 ++++++------ .../linter-4.2/src/TypeScriptLinterConfig.ts | 4 +- ets2panda/linter-4.2/src/Utils.ts | 103 +++--- .../src/ts-diagnostics/TSCCompiledProgram.ts | 8 +- .../stats_calculator/src/calculate-stats.ts | 8 +- 11 files changed, 440 insertions(+), 430 deletions(-) diff --git a/ets2panda/linter-4.2/cookbook_convertor/src/cookbook_convertor.ts b/ets2panda/linter-4.2/cookbook_convertor/src/cookbook_convertor.ts index d6e672ebff..3ed43bbbb8 100644 --- a/ets2panda/linter-4.2/cookbook_convertor/src/cookbook_convertor.ts +++ b/ets2panda/linter-4.2/cookbook_convertor/src/cookbook_convertor.ts @@ -17,7 +17,7 @@ import { readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; -const COPYRIGHT_HEADER = "/* \n\ +const COPYRIGHT_HEADER = '/* \n\ * Copyright (c) 2022-2023 Huawei Device Co., Ltd. \n\ * Licensed under the Apache License, Version 2.0 (the \"License\"); \n\ * you may not use this file except in compliance with the License. \n\ @@ -31,45 +31,45 @@ const COPYRIGHT_HEADER = "/* \n\ * See the License for the specific language governing permissions and \n\ * limitations under the License. \n\ */ \n\ -"; +'; -const CODE_PROLOGUE = "export const cookBookMsg: string[] = [];\n\ +const CODE_PROLOGUE = 'export const cookBookMsg: string[] = [];\n\ export const cookBookTag: string[] = [];\n\ \n\ -for( let i = 0; i < 148; i++) {\n\ +for ( let i = 0; i < 148; i++) {\n\ cookBookMsg[ i ] = '';\n\ }\n\ -"; +'; // HTML tegs -const T_BR = "
"; -const T_UNDERLINE = ""; -const T_END_UNDERLINE = ""; -const T_BOLD = ""; -const T_END_BOLD = ""; -const T_ITALIC = ""; -const T_END_ITALIC = ""; -const T_CODE = ""; -const T_END_CODE = ""; -const T_NBSP = " "; -const T_HR = '
'; +const T_BR = '
'; +const T_UNDERLINE = ''; +const T_END_UNDERLINE = ''; +const T_BOLD = ''; +const T_END_BOLD = ''; +const T_ITALIC = ''; +const T_END_ITALIC = ''; +const T_CODE = ''; +const T_END_CODE = ''; +const T_NBSP = ' '; +const T_HR = '
'; // RST substititions -const CB_ = "|CB_"; -const CB_R = "|CB_R|"; -const CB_RULE = "|CB_RULE|"; -const CB_BAD = "|CB_BAD|"; -const CB_OK = "|CB_OK|"; -const CB_ERROR = "|CB_ERROR|"; //replace:: **Severity: error** -const CB_WARNING = "|CB_WARNING|"; //replace:: **Severity: warning** -const CB_SEE = "|CB_SEE|"; -const CB_REF = ":ref:"; -const CB_META = ".. meta"; - -const NEW_REC_HEADER = ".. _R"; -const CODE_BLOCK = ".. code"; // should be ".. code-block" but in some places there is error in doc file - -let MAKE_MD = false; // flag to generate .md files +const CB_ = '|CB_'; +const CB_R = '|CB_R|'; +const CB_RULE = '|CB_RULE|'; +const CB_BAD = '|CB_BAD|'; +const CB_OK = '|CB_OK|'; +const CB_ERROR = '|CB_ERROR|'; //replace:: **Severity: error** +const CB_WARNING = '|CB_WARNING|'; //replace:: **Severity: warning** +const CB_SEE = '|CB_SEE|'; +const CB_REF = ':ref:'; +const CB_META = '.. meta'; + +const NEW_REC_HEADER = '.. _R'; +const CODE_BLOCK = '.. code'; // should be ".. code-block" but in some places there is error in doc file + +let MAKE_MD = false; // flag to generate .md files let doc_lines: string[]; let _line:number @@ -82,11 +82,11 @@ let mdText: string[] = []; -const CL = " \\"; // continue line -const STR_DLMTR = "\'"; +const CL = ' \\'; // continue line +const STR_DLMTR = '\''; -function syncReadFile(filename: string) { +function syncReadFile(filename: string): number { const contents = readFileSync(filename, 'utf-8'); doc_lines = contents.split(/\r?\n/); @@ -94,20 +94,20 @@ function syncReadFile(filename: string) { // make table of rule names _line = 0; let ruleNum = -1; - while( _line < doc_lines.length ) { - if(doc_lines[ _line ].startsWith( NEW_REC_HEADER ) ) { -console.log(">>>>>>> START RULE " + doc_lines[ _line ].split( NEW_REC_HEADER )[1]) - ruleNum = Number((doc_lines[ _line ].split( NEW_REC_HEADER )[1]).split(":")[0]); -console.log(" NUMBER: " + ruleNum) + while ( _line < doc_lines.length ) { + if (doc_lines[ _line ].startsWith( NEW_REC_HEADER ) ) { +console.log('>>>>>>> START RULE ' + doc_lines[ _line ].split( NEW_REC_HEADER )[1]) + ruleNum = Number((doc_lines[ _line ].split( NEW_REC_HEADER )[1]).split(':')[0]); +console.log(' NUMBER: ' + ruleNum) } - if( doc_lines[ _line ].startsWith( CB_R ) ) { + if ( doc_lines[ _line ].startsWith( CB_R ) ) { let line = doc_lines[ _line ].split( CB_R )[1]; ruleNames[ ruleNum ] = line; //line.split(':')[1]; _line++; needHeader(); - if( doc_lines[ _line ].startsWith( CB_RULE ) ) { - line = doc_lines[ _line ].trim().replace( CB_RULE, "").trim(); - ruleNames[ ruleNum ] = ruleNames[ ruleNum ] + " (" + line + ")"; + if ( doc_lines[ _line ].startsWith( CB_RULE ) ) { + line = doc_lines[ _line ].trim().replace( CB_RULE, '').trim(); + ruleNames[ ruleNum ] = ruleNames[ ruleNum ] + ' (' + line + ')'; } } _line ++; @@ -115,11 +115,11 @@ console.log(" NUMBER: " + ruleNum) // scan text _line = 0; - while( _line < doc_lines.length ) { - skipEmptyLines(); - if( doc_lines[_line].startsWith(NEW_REC_HEADER)) { + while ( _line < doc_lines.length ) { + skipEmptyLines(); + if ( doc_lines[_line].startsWith(NEW_REC_HEADER)) { makeRecept(); - } + } else _line++; } @@ -134,44 +134,45 @@ console.log(" NUMBER: " + ruleNum) function replaceAll( s: string, from: string, to: string): string { let ss = s.split(from); - let outStr = ""; + let outStr = ''; ss.forEach( (line) => { outStr += to + line; }); - return outStr.replace( to, ""); // remove 1st 'to' substring + return outStr.replace( to, ''); // remove 1st 'to' substring } function translateLine( s: string ) : string { let line = s; + line = line.replace( CB_BAD, "TypeScript"); line = line.replace( CB_OK, "ArkTS"); //.. |CB_RULE| replace:: Rule - line = line.replace( CB_ERROR, "**Severity: error**" ); - line = line.replace( CB_WARNING, "**Severity: warning**" ); - line = line.replace(CB_SEE, "## See also" ); + line = line.replace( CB_ERROR, '**Severity: error**' ); + line = line.replace( CB_WARNING, '**Severity: warning**' ); + line = line.replace(CB_SEE, '## See also' ); - line = line.replace( "|JS|", "JavaScript"); - line = line.replace( "|LANG|", "ArkTS"); //.. |LANG| replace:: {lang} - line = line.replace( "|TS|", "TypeScript"); + line = line.replace( '|JS|', 'JavaScript'); + line = line.replace( '|LANG|', 'ArkTS'); //.. |LANG| replace:: {lang} + line = line.replace( '|TS|', 'TypeScript'); return line; } function translateTeg( s: string) :string { - return replaceAll( s, "\`\`", '"' ).trim(); + return replaceAll( s, '\`\`', '"' ).trim(); } function makeHdr( s: string) :string { - return replaceAll( s, "\`\`", "\'" ); + return replaceAll( s, '\`\`', '\'' ); } function highlightCode( s: string ): string { - let ss = s.split("\`\`"); + let ss = s.split('\`\`'); let line = ss[0]; - for( let i = 1; i < ss.length; i++ ) { - if( (i % 2) === 0 ) + for ( let i = 1; i < ss.length; i++ ) { + if ( (i % 2) === 0 ) line += T_END_CODE; else line += T_CODE; @@ -181,41 +182,41 @@ function highlightCode( s: string ): string { } function escapeSym( s: string ): string { - let ss = replaceAll(s, "\'", "\\\'"); - return replaceAll(ss, "\"", "\\\""); + let ss = replaceAll(s, '\'', '\\\''); + return replaceAll(ss, '\"', '\\\"'); } function setNBSP( s: string ): string { - let ss = ""; + let ss = ''; let flag = true; - for( let ch of s ) { - if( ch !== " " && ch !== "\t" ) + for ( let ch of s ) { + if ( ch !== ' ' && ch !== '\t' ) flag = false; - if( flag && ch === " " ) + if ( flag && ch === ' ' ) ss += T_NBSP; - else if( flag && ch ==="\t" ) - ss += T_NBSP + T_NBSP + T_NBSP + T_NBSP + T_NBSP + T_NBSP + T_NBSP + T_NBSP ; + else if ( flag && ch === '\t' ) + ss += T_NBSP + T_NBSP + T_NBSP + T_NBSP + T_NBSP + T_NBSP + T_NBSP + T_NBSP; else - ss += ch; + ss += ch; } return ss; } -function skipEmptyLines() { - while( _line < doc_lines.length ) { +function skipEmptyLines(): void { + while ( _line < doc_lines.length ) { let s = doc_lines[_line]; s = s.trim(); - if( s !== "") + if ( s !== '') break; _line++; } } function isHeader(): boolean { - return doc_lines[ _line ].startsWith( CB_ ) || doc_lines[ _line ].startsWith( ".." ) ; + return doc_lines[ _line ].startsWith( CB_ ) || doc_lines[ _line ].startsWith( '..' ); } -function needHeader() { +function needHeader(): void { while ( _line < doc_lines.length && !isHeader() ) _line++; } @@ -225,9 +226,9 @@ function needHeader() { // parsing functions // -function makeRecept() { - recNum = Number(doc_lines[_line].slice(NEW_REC_HEADER.length, NEW_REC_HEADER.length+3)) - console.log("cookBookMsg[ " + recNum + " ] = " + STR_DLMTR + CL); +function makeRecept(): void { + recNum = Number(doc_lines[_line].slice(NEW_REC_HEADER.length, NEW_REC_HEADER.length + 3)) + console.log('cookBookMsg[ ' + recNum + ' ] = ' + STR_DLMTR + CL); _line++; mdText = []; makeTeg(); @@ -237,27 +238,27 @@ function makeRecept() { makeSee(); // emit .md file - let mdFileName = join("./md", "recipe" + recNum + ".md" ); - writeFileSync( mdFileName, "", { flag: 'w', }); + let mdFileName = join('./md', 'recipe' + recNum + '.md' ); + writeFileSync( mdFileName, '', { flag: 'w', }); mdText.forEach((mdLine) => { -console.error("MD> " + mdLine); - writeFileSync(mdFileName, mdLine + '\n', { flag: "a+"} ) +console.error('MD> ' + mdLine); + writeFileSync(mdFileName, mdLine + '\n', { flag: 'a+'} ) }); - console.log(STR_DLMTR + ";"); - console.log(""); + console.log(STR_DLMTR + ';'); + console.log(''); } -function makeTeg() { +function makeTeg(): void { needHeader(); -console.error(">>>TEG>>>: " + _line + " -> " + doc_lines[_line]); - if( ! doc_lines[ _line ].startsWith( CB_R ) ) +console.error('>>>TEG>>>: ' + _line + ' -> ' + doc_lines[_line]); + if ( ! doc_lines[ _line ].startsWith( CB_R ) ) return; let line = doc_lines[ _line ].split( CB_R )[1]; - mdText.push("# " + line); //.split(':')[1] ); - mdText.push(""); + mdText.push('# ' + line); //.split(':')[1] ); + mdText.push(''); line = escapeSym( translateLine(line) ); let teg = translateTeg( line ); @@ -269,34 +270,36 @@ console.error(">>>TEG>>>: " + _line + " -> " + doc_lines[_line]); function makeBody(): string { - let body = ""; + let body = ''; needHeader(); -console.error(">>>BODY HDR>>>: " + + _line + " -> " + doc_lines[_line]); - if( !doc_lines[ _line ].startsWith( CB_RULE ) ) - return ""; +console.error('>>>BODY HDR>>>: ' + + _line + ' -> ' + doc_lines[_line]); + if ( !doc_lines[ _line ].startsWith( CB_RULE ) ) + return ''; let line = doc_lines[ _line ].trim(); let md_line = line; - line = line.replace( CB_RULE, ""); + line = line.replace( CB_RULE, ''); line = escapeSym( translateLine(line) ); - tegs[ recNum ] = tegs[ recNum ].trim() + " (" + replaceAll(translateTeg(line), '"', '') + ")"; + tegs[ recNum ] = tegs[ recNum ].trim() + ' (' + replaceAll(translateTeg(line), '"', '') + ')'; _line++; _line++; // skip underline - console.log( T_HR + T_BOLD + "Rule" + T_END_BOLD + T_BR + CL ); + console.log( T_HR + T_BOLD + 'Rule' + T_END_BOLD + T_BR + CL ); - mdText.push( md_line.replace( CB_RULE, "Rule" ) ); //("## Rule"); - mdText.push(""); + mdText.push( md_line.replace( CB_RULE, 'Rule' ) ); //('## Rule'); + mdText.push(''); needHeader(); -console.error(">>>BODY 2 HDR>>>: " + + _line + " -> " + doc_lines[_line]); - if( doc_lines[ _line ].startsWith(CB_META) ) { +console.error('>>>BODY 2 HDR>>>: ' + + _line + ' -> ' + doc_lines[_line]); + if ( doc_lines[ _line ].startsWith(CB_META) ) { _line++; needHeader(); -console.error(">>>BODY 3 HDR>>>: " + + _line + " -> " + doc_lines[_line]); +console.error('>>>BODY 3 HDR>>>: ' + + _line + ' -> ' + doc_lines[_line]); } //_line++; - while( !isHeader() || doc_lines[ _line ].startsWith( CB_ERROR ) || doc_lines[ _line ].startsWith( CB_WARNING ) ) { + + while ( !isHeader() || doc_lines[ _line ].startsWith( CB_ERROR ) || doc_lines[ _line ].startsWith( CB_WARNING ) ) { + //skipEmptyLines(); let s = translateLine( doc_lines[_line] ); mdText.push(s); @@ -304,13 +307,13 @@ console.error(">>>BODY 3 HDR>>>: " + + _line + " -> " + doc_lines[_line]); s = highlightCode( s ); s = escapeSym( s ); console.log(s + CL); - + body += s; _line++; } console.log(T_BR + CL); - mdText.push(""); + mdText.push(''); return body; } @@ -318,21 +321,21 @@ console.error(">>>BODY 3 HDR>>>: " + + _line + " -> " + doc_lines[_line]); function makeBad(): string { - let badCode =""; - + let badCode = ''; + needHeader(); -console.error(">>>makeBAD HDR>>>: " + doc_lines[_line]); - if( ! doc_lines[_line].startsWith( CB_BAD ) ) { - return ""; +console.error('>>>makeBAD HDR>>>: ' + doc_lines[_line]); + if ( ! doc_lines[_line].startsWith( CB_BAD ) ) { + return ''; } _line++; _line++; // skip underline - console.log( T_HR + T_BOLD + "TypeScript" + T_END_BOLD + T_BR + CL ); + console.log( T_HR + T_BOLD + 'TypeScript' + T_END_BOLD + T_BR + CL ); - mdText.push("## TypeScript"); - mdText.push(""); + mdText.push('## TypeScript'); + mdText.push(''); - while( _line < doc_lines.length && !isHeader() ) { + while ( _line < doc_lines.length && !isHeader() ) { let s = translateLine( doc_lines[_line] ); mdText.push( s ); @@ -344,39 +347,39 @@ console.error(">>>makeBAD HDR>>>: " + doc_lines[_line]); } skipEmptyLines(); - if( doc_lines[_line++].startsWith( CODE_BLOCK ) ) { - mdText.push("```"); + if ( doc_lines[_line++].startsWith( CODE_BLOCK ) ) { + mdText.push('```'); console.log( T_CODE + CL ); - while( _line < doc_lines.length && !isHeader() ) { + while ( _line < doc_lines.length && !isHeader() ) { mdText.push( doc_lines[_line] ); console.log( setNBSP( escapeSym(doc_lines[_line]) ) + T_BR + CL ); _line++; } console.log( T_END_CODE + T_BR + CL ); - mdText.push("```"); + mdText.push('```'); } - mdText.push(""); + mdText.push(''); return badCode; } function makeOk(): string { - let goodCode = ""; + let goodCode = ''; needHeader(); -console.error( ">>>makeOK HDR>>>: " + doc_lines[ _line ] ); - if( _line >= doc_lines.length || !doc_lines[_line].startsWith(CB_OK) ) { - return ""; +console.error( '>>>makeOK HDR>>>: ' + doc_lines[ _line ] ); + if ( _line >= doc_lines.length || !doc_lines[_line].startsWith(CB_OK) ) { + return ''; } _line++; _line++; // skip underline - console.log( T_HR + T_BOLD + "ArkTS" + T_END_BOLD + T_BR + CL ); + console.log( T_HR + T_BOLD + 'ArkTS' + T_END_BOLD + T_BR + CL ); - mdText.push("## ArkTS"); - mdText.push(""); - - while( _line < doc_lines.length && !isHeader() ) { + mdText.push('## ArkTS'); + mdText.push(''); + + while ( _line < doc_lines.length && !isHeader() ) { let s = translateLine( doc_lines[ _line ] ); mdText.push( s ); @@ -389,54 +392,54 @@ console.error( ">>>makeOK HDR>>>: " + doc_lines[ _line ] ); } skipEmptyLines(); - if( doc_lines[ _line++ ].startsWith( CODE_BLOCK ) ) { + if ( doc_lines[ _line++ ].startsWith( CODE_BLOCK ) ) { console.log( T_CODE + CL ); - mdText.push("```"); + mdText.push('```'); - while( _line < doc_lines.length && !isHeader() ) { + while ( _line < doc_lines.length && !isHeader() ) { mdText.push( doc_lines[_line] ); console.log( setNBSP( escapeSym(doc_lines[ _line ]) ) + T_BR + CL ); _line++; } console.log( T_END_CODE + T_BR + CL); - mdText.push("```"); + mdText.push('```'); } - mdText.push(""); + mdText.push(''); return goodCode; } function makeSee( ): string { - const RECIPE = "Recipe "; -console.error(">>> #" + recNum + " PASSED: " + doc_lines[_line]); - while( _line < doc_lines.length && !doc_lines[ _line ].startsWith( ".." ) ) { + const RECIPE = 'Recipe '; +console.error('>>> #' + recNum + ' PASSED: ' + doc_lines[_line]); + while ( _line < doc_lines.length && !doc_lines[ _line ].startsWith( '..' ) ) { let s = translateLine( doc_lines[_line] ); - if( s.split(CB_REF)[1] ) { - s = s.replace("*", "-") + if ( s.split(CB_REF)[1] ) { + s = s.replace('*', '-') s = s.replace( CB_REF, RECIPE); - s = s.replace("`R", ""); - let ruleNum = Number( s.replace("`", "").split(RECIPE)[1]); -console.error(">>>RULE in SEE " + ruleNum + " " + s.replace("`", "") + " -> " + ruleNames[ruleNum] ); - s = s.replace("`", ":"); + s = s.replace('`R', ''); + let ruleNum = Number( s.replace('`', '').split(RECIPE)[1]); +console.error('>>>RULE in SEE ' + ruleNum + ' ' + s.replace('`', '') + ' -> ' + ruleNames[ruleNum] ); + s = s.replace('`', ':'); s += ' ' + ruleNames[ruleNum]; } mdText.push( s ); - if( doc_lines[_line].startsWith(CB_SEE) ) + if ( doc_lines[_line].startsWith(CB_SEE) ) _line++; _line++; } - mdText.push(""); + mdText.push(''); - return ""; + return ''; } @@ -445,19 +448,20 @@ console.error(">>>RULE in SEE " + ruleNum + " " + s.replace("`", "") + " -> " + // let commandLineArgs = process.argv.slice(2); if (commandLineArgs.length === 0) { - console.error(">>> Command line error: no arguments"); + console.error('>>> Command line error: no arguments'); process.exit(-1); } -if( commandLineArgs[0] == '-md') { +if ( commandLineArgs[0] === '-md') { commandLineArgs = process.argv.slice(3); MAKE_MD = true; } let inFileName = commandLineArgs[0]; console.log(COPYRIGHT_HEADER); + console.log( CODE_PROLOGUE ); syncReadFile( inFileName); -for( recNum = 1; recNum < tegs.length; recNum++ ) { - console.log( "cookBookTag[ " + recNum + " ] = " + STR_DLMTR + ( tegs[ recNum ] ? tegs[ recNum ] : "" ) + STR_DLMTR + ";" ); +for ( recNum = 1; recNum < tegs.length; recNum++ ) { + console.log( 'cookBookTag[ ' + recNum + ' ] = ' + STR_DLMTR + ( tegs[ recNum ] ? tegs[ recNum ] : '' ) + STR_DLMTR + ';' ); } diff --git a/ets2panda/linter-4.2/src/Autofixer.ts b/ets2panda/linter-4.2/src/Autofixer.ts index d082f5ade8..d25e956ae5 100644 --- a/ets2panda/linter-4.2/src/Autofixer.ts +++ b/ets2panda/linter-4.2/src/Autofixer.ts @@ -27,7 +27,7 @@ export const AUTOFIX_ALL: AutofixInfo = { // Temporary solution is to disable all risky autofixes, until the // algorithm is improved to guarantee that fixes can be applied // safely and won't break program code. -const UNSAFE_FIXES: FaultID[] = [ FaultID.LiteralAsPropertyName, FaultID.PropertyAccessByIndex ]; +const UNSAFE_FIXES: FaultID[] = [FaultID.LiteralAsPropertyName, FaultID.PropertyAccessByIndex]; export interface Autofix { replacementText: string; @@ -45,9 +45,7 @@ export class AutofixInfoSet { public shouldAutofix(node: ts.Node, faultID: FaultID): boolean { if (UNSAFE_FIXES.includes(faultID)) return false; if (this.autofixInfo.length === 0) return false; - if (this.autofixInfo.length === 1 && this.autofixInfo[0] === AUTOFIX_ALL) { - return true; - } + if (this.autofixInfo.length === 1 && this.autofixInfo[0] === AUTOFIX_ALL) { return true; } return this.autofixInfo.findIndex( value => value.start === node.getStart() && value.end === node.getEnd() && value.problemID === FaultID[faultID] ) !== -1; @@ -136,13 +134,13 @@ export function fixTypeAssertion(typeAssertion: ts.TypeAssertion): Autofix { const printer: ts.Printer = ts.createPrinter(); -function numericLiteral2IdentifierName(numeric: ts.NumericLiteral) { +function numericLiteral2IdentifierName(numeric: ts.NumericLiteral): string { return '__' + numeric.getText(); } -function stringLiteral2IdentifierName(str: ts.StringLiteral) { +function stringLiteral2IdentifierName(str: ts.StringLiteral): string { let text = (str as ts.StringLiteral).getText(); - return text.substring(1, text.length-1); // cut out starting and ending quoters. + return text.substring(1, text.length - 1); // cut out starting and ending quoters. } function propertyName2IdentifierName(name: ts.PropertyName): string { @@ -155,7 +153,7 @@ function propertyName2IdentifierName(name: ts.PropertyName): string { return ''; } -function indexExpr2IdentifierName(index: ts.Expression) { +function indexExpr2IdentifierName(index: ts.Expression): string { if (index.kind === ts.SyntaxKind.NumericLiteral) return numericLiteral2IdentifierName(index as ts.NumericLiteral); @@ -170,9 +168,9 @@ function getReturnTypePosition(funcLikeDecl: ts.FunctionLikeDeclaration): number // Find position of the first node or token that follows parameters. // After that, iterate over child nodes in reverse order, until found // first closing parenthesis. - let postParametersPosition = ts.isArrowFunction(funcLikeDecl) - ? funcLikeDecl.equalsGreaterThanToken.getStart() - : funcLikeDecl.body.getStart(); + let postParametersPosition = ts.isArrowFunction(funcLikeDecl) ? + funcLikeDecl.equalsGreaterThanToken.getStart() : + funcLikeDecl.body.getStart(); const children = funcLikeDecl.getChildren(); for (let i = children.length - 1; i >= 0; i--) { diff --git a/ets2panda/linter-4.2/src/CommandLineParser.ts b/ets2panda/linter-4.2/src/CommandLineParser.ts index 9544757307..f8cba29508 100644 --- a/ets2panda/linter-4.2/src/CommandLineParser.ts +++ b/ets2panda/linter-4.2/src/CommandLineParser.ts @@ -31,8 +31,8 @@ const logger = Logger.getLogger(); let inputFiles: string[]; let responseFile = ''; -function addSrcFile(value: string, dummy: string) { - if(value.startsWith('@')) +function addSrcFile(value: string, dummy: string): void { + if (value.startsWith('@')) responseFile = value; else inputFiles.push(value); @@ -56,7 +56,7 @@ const getFiles = (dir: string): string[] => { return resultFiles; }; -function addProjectFolder(projectFolder: string, previous: any ) { +function addProjectFolder(projectFolder: string, previous: any ): any { return previous.concat([projectFolder]); } @@ -76,7 +76,7 @@ export function parseCommandLine(commandLineArgs: string[]): CommandLineOptions .option('-p, --project ', 'path to TS project config file') .option('--project-folder ', 'path to folder containig TS files to verify', addProjectFolder, []) .option('--autofix [autofix.json]', 'fix errors specified by JSON file (all if file is omitted)', - (val: string, prev: string|boolean) => { return val.endsWith(JSON_EXT) ? val : true; }) + (val: string, prev: string | boolean) => { return val.endsWith(JSON_EXT) ? val : true; }) .addOption(new Option('--warnings-as-errors', 'treat warnings as errors').hideHelp(true)); program .argument('[srcFile...]', 'files to be verified', addSrcFile); @@ -104,16 +104,16 @@ export function parseCommandLine(commandLineArgs: string[]): CommandLineOptions if (options.TSC_Errors) opts.logTscErrors = true; if (options.devecoPluginMode) opts.ideMode = true; if (options.testMode) opts.testMode = true; - if (options.projectFolder) doProjectFolderArg(options.projectFolder, opts); + if (options.projectFolder) doProjectFolderArg(options.projectFolder, opts); if (options.project) doProjectArg(options.project, opts); if (options.autofix) doAutofixArg(options.autofix, opts); if (options.warningsAsErrors) opts.warningsAsErrors = true; return opts; } -function doProjectFolderArg(prjFolders: string[], opts: CommandLineOptions) { - for( let i = 0; i < prjFolders.length; i++ ) { - var prjFolderPath = prjFolders[ i ]; +function doProjectFolderArg(prjFolders: string[], opts: CommandLineOptions): void { + for ( let i = 0; i < prjFolders.length; i++ ) { + let prjFolderPath = prjFolders[ i ]; try { opts.inputFiles.push(...getFiles(prjFolderPath)); } catch (error: any) { @@ -152,7 +152,7 @@ function doProjectArg(cfgPath: string, opts: CommandLineOptions) { } } -function doAutofixArg(autofixOptVal: string|boolean, opts: CommandLineOptions) { +function doAutofixArg(autofixOptVal: string | boolean, opts: CommandLineOptions): void { if (typeof autofixOptVal === 'string') { let autofixInfoStr = fs.readFileSync(autofixOptVal).toString(); let autofixInfos = JSON.parse(autofixInfoStr); diff --git a/ets2panda/linter-4.2/src/LinterRunner.ts b/ets2panda/linter-4.2/src/LinterRunner.ts index 466e245285..d6bd82d49e 100644 --- a/ets2panda/linter-4.2/src/LinterRunner.ts +++ b/ets2panda/linter-4.2/src/LinterRunner.ts @@ -81,7 +81,8 @@ export function lint(options: LintOptions): LintRunResult { consoleLog('\n\n\nFiles scanned: ', srcFiles.length); consoleLog('\nFiles with problems: ', errorNodes); - let errorNodesTotal = 0, warningNodes = 0; + let errorNodesTotal = 0; + let warningNodes = 0; for (let i = 0; i < FaultID.LAST_ID; i++) { // if Strict mode - count all cases if (!linter.strictMode && faultsAttrs[i].migratable) // In relax mode skip migratable @@ -176,8 +177,9 @@ function transformTscDiagnostics( function countProblemFiles( nodeCounters: number[], filesNumber: number, tsSrcFile: ts.SourceFile, fileNodes: number, fileErrorLines: number, fileWarningLines: number, linter: TypeScriptLinter, -) { - let errorNodes = 0, warningNodes = 0; +): number { + let errorNodes = 0; + let warningNodes = 0; for (let i = 0; i < FaultID.LAST_ID; i++) { let nodeCounterDiff = linter.nodeCounters[i] - nodeCounters[i]; if (faultsAttrs[i].warning) warningNodes += nodeCounterDiff; @@ -197,7 +199,7 @@ function countProblemFiles( return filesNumber; } -function logTotalProblemsInfo(errorNodes: number, warningNodes: number, linter: TypeScriptLinter) { +function logTotalProblemsInfo(errorNodes: number, warningNodes: number, linter: TypeScriptLinter): void { let errorRate = ((errorNodes / linter.totalVisitedNodes) * 100).toFixed(2); let warningRate = ((warningNodes / linter.totalVisitedNodes) * 100).toFixed(2); consoleLog('\nTotal error constructs (%): ', errorRate); @@ -206,7 +208,7 @@ function logTotalProblemsInfo(errorNodes: number, warningNodes: number, linter: consoleLog('\nTotal warning lines:', linter.totalWarningLines, ' lines\n'); } -function logProblemsPercentageByFeatures(linter: TypeScriptLinter) { +function logProblemsPercentageByFeatures(linter: TypeScriptLinter): void { consoleLog('\nPercent by features: '); for (let i = 0; i < FaultID.LAST_ID; i++) { // if Strict mode - count all cases @@ -221,7 +223,7 @@ function logProblemsPercentageByFeatures(linter: TypeScriptLinter) { } } -export function run() { +export function run(): void { const commandLineArgs = process.argv.slice(2); if (commandLineArgs.length === 0) { logger.info('Command line error: no arguments'); @@ -248,7 +250,7 @@ function getTempFileName() { return path.join(os.tmpdir(), Math.floor(Math.random() * 10000000).toString() + '_linter_tmp_file.ts'); } -function runIDEMode(cmdOptions: CommandLineOptions) { +function runIDEMode(cmdOptions: CommandLineOptions): void { TypeScriptLinter.ideMode = true; const tmpFileName = getTempFileName(); // read data from stdin diff --git a/ets2panda/linter-4.2/src/Problems.ts b/ets2panda/linter-4.2/src/Problems.ts index 98bd4701b9..61c4aa3b5d 100644 --- a/ets2panda/linter-4.2/src/Problems.ts +++ b/ets2panda/linter-4.2/src/Problems.ts @@ -14,12 +14,12 @@ */ export enum FaultID { - AnyType, SymbolType, ObjectLiteralNoContextType, ArrayLiteralNoContextType, + AnyType, SymbolType, ObjectLiteralNoContextType, ArrayLiteralNoContextType, ComputedPropertyName, LiteralAsPropertyName, TypeQuery, RegexLiteral, IsOperator, DestructuringParameter, YieldExpression, InterfaceMerging, EnumMerging, InterfaceExtendsClass, IndexMember, WithStatement, - ThrowStatement, IndexedAccessType, UnknownType, ForInStatement, InOperator, + ThrowStatement, IndexedAccessType, UnknownType, ForInStatement, InOperator, ImportFromPath, FunctionExpression, IntersectionType, - ObjectTypeLiteral, CommaOperator, LimitedReturnTypeInference, + ObjectTypeLiteral, CommaOperator, LimitedReturnTypeInference, LambdaWithTypeParameters, ClassExpression, DestructuringAssignment, DestructuringDeclaration, VarDeclaration, CatchWithUnsupportedType, DeleteOperator, DeclWithDuplicateName, UnaryArithmNotNumber, ConstructorType, ConstructorIface, ConstructorFuncs, CallSignature, @@ -27,12 +27,12 @@ export enum FaultID { ConditionalType, MappedType, NamespaceAsObject, ClassAsObject, NonDeclarationInNamespace, GeneratorFunction, FunctionContainsThis, PropertyAccessByIndex, JsxElement, EnumMemberNonConstInit, ImplementsClass, MethodReassignment, MultipleStaticBlocks, ThisType, - IntefaceExtendDifProps, StructuralIdentity, TypeOnlyImport, TypeOnlyExport, DefaultImport, + IntefaceExtendDifProps, StructuralIdentity, TypeOnlyImport, TypeOnlyExport, DefaultImport, ExportAssignment, ImportAssignment, GenericCallNoTypeArgs, ParameterProperties, InstanceofUnsupported, ShorthandAmbientModuleDecl, WildcardsInModuleName, UMDModuleDefinition, NewTarget, DefiniteAssignment, Prototype, GlobalThis, - UtilityType, PropertyDeclOnFunction, FunctionApplyBindCall, ConstAssertion, ImportAssertion, + UtilityType, PropertyDeclOnFunction, FunctionApplyBindCall, ConstAssertion, ImportAssertion, SpreadOperator, LimitedStdLibApi, ErrorSuppression, StrictDiagnostic, UnsupportedDecorators, ImportAfterStatement, EsObjectType, LAST_ID, // this should always be last enum } @@ -45,89 +45,89 @@ export class FaultAttributs { export const faultsAttrs: FaultAttributs[] = []; -faultsAttrs[FaultID.LiteralAsPropertyName] = {migratable: true, cookBookRef: '1',}; -faultsAttrs[FaultID.ComputedPropertyName] = {cookBookRef: '1',}; -faultsAttrs[FaultID.SymbolType] = {cookBookRef: '2',}; -faultsAttrs[FaultID.PrivateIdentifier] = {migratable: true, cookBookRef: '3',}; -faultsAttrs[FaultID.DeclWithDuplicateName] = {migratable: true, cookBookRef: '4',}; -faultsAttrs[FaultID.VarDeclaration] = {migratable: true, cookBookRef: '5',}; +faultsAttrs[FaultID.LiteralAsPropertyName] = {migratable: true, cookBookRef: '1', }; +faultsAttrs[FaultID.ComputedPropertyName] = {cookBookRef: '1', }; +faultsAttrs[FaultID.SymbolType] = {cookBookRef: '2', }; +faultsAttrs[FaultID.PrivateIdentifier] = {migratable: true, cookBookRef: '3', }; +faultsAttrs[FaultID.DeclWithDuplicateName] = {migratable: true, cookBookRef: '4', }; +faultsAttrs[FaultID.VarDeclaration] = {migratable: true, cookBookRef: '5', }; faultsAttrs[FaultID.AnyType] = {cookBookRef: '8'}; -faultsAttrs[FaultID.UnknownType] = {cookBookRef: '8',}; -faultsAttrs[FaultID.CallSignature] = {cookBookRef: '14',}; -faultsAttrs[FaultID.ConstructorType] = {cookBookRef: '15',}; -faultsAttrs[FaultID.MultipleStaticBlocks] = {cookBookRef: '16',}; -faultsAttrs[FaultID.IndexMember] = {cookBookRef: '17',}; -faultsAttrs[FaultID.IntersectionType] = {cookBookRef: '19',}; -faultsAttrs[FaultID.ThisType] = {cookBookRef: '21',}; -faultsAttrs[FaultID.ConditionalType] = {cookBookRef: '22',}; -faultsAttrs[FaultID.ParameterProperties] = {migratable: true, cookBookRef: '25',}; -faultsAttrs[FaultID.ConstructorIface] = {cookBookRef: '27',}; -faultsAttrs[FaultID.IndexedAccessType] = {cookBookRef: '28',}; -faultsAttrs[FaultID.PropertyAccessByIndex] = {migratable: true, cookBookRef: '29',}; -faultsAttrs[FaultID.StructuralIdentity] = {cookBookRef: '30',}; -faultsAttrs[FaultID.GenericCallNoTypeArgs] = {cookBookRef: '34',}; -faultsAttrs[FaultID.RegexLiteral] = {cookBookRef: '37',}; -faultsAttrs[FaultID.ObjectLiteralNoContextType] = {cookBookRef: '38',}; -faultsAttrs[FaultID.ObjectTypeLiteral] = {cookBookRef: '40',}; -faultsAttrs[FaultID.ArrayLiteralNoContextType] = {cookBookRef: '43',}; -faultsAttrs[FaultID.FunctionExpression] = {migratable: true, cookBookRef: '46',}; -faultsAttrs[FaultID.LambdaWithTypeParameters] = {migratable: true, cookBookRef: '49',}; -faultsAttrs[FaultID.ClassExpression] = {migratable: true, cookBookRef: '50',}; -faultsAttrs[FaultID.ImplementsClass] = {cookBookRef: '51',}; -faultsAttrs[FaultID.MethodReassignment] = {cookBookRef: '52',}; -faultsAttrs[FaultID.TypeAssertion] = {migratable: true, cookBookRef: '53',}; -faultsAttrs[FaultID.JsxElement] = {cookBookRef: '54',}; -faultsAttrs[FaultID.UnaryArithmNotNumber] = {cookBookRef: '55',}; -faultsAttrs[FaultID.DeleteOperator] = {cookBookRef: '59',}; -faultsAttrs[FaultID.TypeQuery] = {cookBookRef: '60',}; -faultsAttrs[FaultID.InstanceofUnsupported] = {cookBookRef: '65',}; -faultsAttrs[FaultID.InOperator] = {cookBookRef: '66',}; -faultsAttrs[FaultID.DestructuringAssignment] = {migratable: true, cookBookRef: '69',}; -faultsAttrs[FaultID.CommaOperator] = {cookBookRef: '71',}; -faultsAttrs[FaultID.DestructuringDeclaration] = {migratable: true, cookBookRef: '74',}; -faultsAttrs[FaultID.CatchWithUnsupportedType] = {migratable: true, cookBookRef: '79',}; -faultsAttrs[FaultID.ForInStatement] = {cookBookRef: '80',}; -faultsAttrs[FaultID.MappedType] = {cookBookRef: '83',}; -faultsAttrs[FaultID.WithStatement] = {cookBookRef: '84',}; -faultsAttrs[FaultID.ThrowStatement] = {migratable: true, cookBookRef: '87',}; -faultsAttrs[FaultID.LimitedReturnTypeInference] = {migratable: true, cookBookRef: '90',}; -faultsAttrs[FaultID.DestructuringParameter] = {cookBookRef: '91',}; -faultsAttrs[FaultID.LocalFunction] = {migratable: true, cookBookRef: '92',}; -faultsAttrs[FaultID.FunctionContainsThis] = {cookBookRef: '93',}; -faultsAttrs[FaultID.GeneratorFunction] = {cookBookRef: '94',}; -faultsAttrs[FaultID.YieldExpression] = {cookBookRef: '94',}; -faultsAttrs[FaultID.IsOperator] = {cookBookRef: '96',}; -faultsAttrs[FaultID.SpreadOperator] = {cookBookRef: '99',}; -faultsAttrs[FaultID.IntefaceExtendDifProps] = {cookBookRef: '102',}; -faultsAttrs[FaultID.InterfaceMerging] = {cookBookRef: '103',}; -faultsAttrs[FaultID.InterfaceExtendsClass] = {cookBookRef: '104',}; -faultsAttrs[FaultID.ConstructorFuncs] = {cookBookRef: '106',}; -faultsAttrs[FaultID.EnumMemberNonConstInit] = {cookBookRef: '111',}; -faultsAttrs[FaultID.EnumMerging] = {cookBookRef: '113',}; -faultsAttrs[FaultID.NamespaceAsObject] = {cookBookRef: '114',}; -faultsAttrs[FaultID.NonDeclarationInNamespace] = {cookBookRef: '116',}; -faultsAttrs[FaultID.ImportFromPath] = {cookBookRef: '119',}; -faultsAttrs[FaultID.TypeOnlyImport] = {migratable: true, cookBookRef: '118',}; -faultsAttrs[FaultID.DefaultImport] = {migratable: true, cookBookRef: '120',}; -faultsAttrs[FaultID.ImportAssignment] = {cookBookRef: '121',}; -faultsAttrs[FaultID.ExportAssignment] = {cookBookRef: '126',}; -faultsAttrs[FaultID.TypeOnlyExport] = {migratable: true, cookBookRef: '127',}; -faultsAttrs[FaultID.ShorthandAmbientModuleDecl] = {cookBookRef: '128',}; -faultsAttrs[FaultID.WildcardsInModuleName] = {cookBookRef: '129',}; -faultsAttrs[FaultID.UMDModuleDefinition] = {cookBookRef: '130',}; -faultsAttrs[FaultID.NewTarget] = {cookBookRef: '132',}; -faultsAttrs[FaultID.DefiniteAssignment] = {warning: true, cookBookRef: '134',}; -faultsAttrs[FaultID.Prototype] = {cookBookRef: '136',}; -faultsAttrs[FaultID.GlobalThis] = {cookBookRef: '137',}; -faultsAttrs[FaultID.UtilityType] = {cookBookRef: '138',}; -faultsAttrs[FaultID.PropertyDeclOnFunction] = {cookBookRef: '139',}; -faultsAttrs[FaultID.FunctionApplyBindCall] = {cookBookRef: '140',}; -faultsAttrs[FaultID.ConstAssertion] = {cookBookRef: '142',}; -faultsAttrs[FaultID.ImportAssertion] = {cookBookRef: '143',}; -faultsAttrs[FaultID.LimitedStdLibApi] = {cookBookRef: '144',}; -faultsAttrs[FaultID.StrictDiagnostic] = {cookBookRef: '145',}; -faultsAttrs[FaultID.ErrorSuppression] = {cookBookRef: '146',}; -faultsAttrs[FaultID.UnsupportedDecorators] = {warning: true, cookBookRef: '148',}; -faultsAttrs[FaultID.ClassAsObject] = {cookBookRef: '149',}; -faultsAttrs[FaultID.ImportAfterStatement] = {cookBookRef: '150',}; -faultsAttrs[FaultID.EsObjectType] = {warning: true, cookBookRef: '151',}; +faultsAttrs[FaultID.UnknownType] = {cookBookRef: '8', }; +faultsAttrs[FaultID.CallSignature] = {cookBookRef: '14', }; +faultsAttrs[FaultID.ConstructorType] = {cookBookRef: '15', }; +faultsAttrs[FaultID.MultipleStaticBlocks] = {cookBookRef: '16', }; +faultsAttrs[FaultID.IndexMember] = {cookBookRef: '17', }; +faultsAttrs[FaultID.IntersectionType] = {cookBookRef: '19', }; +faultsAttrs[FaultID.ThisType] = {cookBookRef: '21', }; +faultsAttrs[FaultID.ConditionalType] = {cookBookRef: '22', }; +faultsAttrs[FaultID.ParameterProperties] = {migratable: true, cookBookRef: '25', }; +faultsAttrs[FaultID.ConstructorIface] = {cookBookRef: '27', }; +faultsAttrs[FaultID.IndexedAccessType] = {cookBookRef: '28', }; +faultsAttrs[FaultID.PropertyAccessByIndex] = {migratable: true, cookBookRef: '29', }; +faultsAttrs[FaultID.StructuralIdentity] = {cookBookRef: '30', }; +faultsAttrs[FaultID.GenericCallNoTypeArgs] = {cookBookRef: '34', }; +faultsAttrs[FaultID.RegexLiteral] = {cookBookRef: '37', }; +faultsAttrs[FaultID.ObjectLiteralNoContextType] = {cookBookRef: '38', }; +faultsAttrs[FaultID.ObjectTypeLiteral] = {cookBookRef: '40', }; +faultsAttrs[FaultID.ArrayLiteralNoContextType] = {cookBookRef: '43', }; +faultsAttrs[FaultID.FunctionExpression] = {migratable: true, cookBookRef: '46', }; +faultsAttrs[FaultID.LambdaWithTypeParameters] = {migratable: true, cookBookRef: '49', }; +faultsAttrs[FaultID.ClassExpression] = {migratable: true, cookBookRef: '50', }; +faultsAttrs[FaultID.ImplementsClass] = {cookBookRef: '51', }; +faultsAttrs[FaultID.MethodReassignment] = {cookBookRef: '52', }; +faultsAttrs[FaultID.TypeAssertion] = {migratable: true, cookBookRef: '53', }; +faultsAttrs[FaultID.JsxElement] = {cookBookRef: '54', }; +faultsAttrs[FaultID.UnaryArithmNotNumber] = {cookBookRef: '55', }; +faultsAttrs[FaultID.DeleteOperator] = {cookBookRef: '59', }; +faultsAttrs[FaultID.TypeQuery] = {cookBookRef: '60', }; +faultsAttrs[FaultID.InstanceofUnsupported] = {cookBookRef: '65', }; +faultsAttrs[FaultID.InOperator] = {cookBookRef: '66', }; +faultsAttrs[FaultID.DestructuringAssignment] = {migratable: true, cookBookRef: '69', }; +faultsAttrs[FaultID.CommaOperator] = {cookBookRef: '71', }; +faultsAttrs[FaultID.DestructuringDeclaration] = {migratable: true, cookBookRef: '74', }; +faultsAttrs[FaultID.CatchWithUnsupportedType] = {migratable: true, cookBookRef: '79', }; +faultsAttrs[FaultID.ForInStatement] = {cookBookRef: '80', }; +faultsAttrs[FaultID.MappedType] = {cookBookRef: '83', }; +faultsAttrs[FaultID.WithStatement] = {cookBookRef: '84', }; +faultsAttrs[FaultID.ThrowStatement] = {migratable: true, cookBookRef: '87', }; +faultsAttrs[FaultID.LimitedReturnTypeInference] = {migratable: true, cookBookRef: '90', }; +faultsAttrs[FaultID.DestructuringParameter] = {cookBookRef: '91', }; +faultsAttrs[FaultID.LocalFunction] = {migratable: true, cookBookRef: '92', }; +faultsAttrs[FaultID.FunctionContainsThis] = {cookBookRef: '93', }; +faultsAttrs[FaultID.GeneratorFunction] = {cookBookRef: '94', }; +faultsAttrs[FaultID.YieldExpression] = {cookBookRef: '94', }; +faultsAttrs[FaultID.IsOperator] = {cookBookRef: '96', }; +faultsAttrs[FaultID.SpreadOperator] = {cookBookRef: '99', }; +faultsAttrs[FaultID.IntefaceExtendDifProps] = {cookBookRef: '102', }; +faultsAttrs[FaultID.InterfaceMerging] = {cookBookRef: '103', }; +faultsAttrs[FaultID.InterfaceExtendsClass] = {cookBookRef: '104', }; +faultsAttrs[FaultID.ConstructorFuncs] = {cookBookRef: '106', }; +faultsAttrs[FaultID.EnumMemberNonConstInit] = {cookBookRef: '111', }; +faultsAttrs[FaultID.EnumMerging] = {cookBookRef: '113', }; +faultsAttrs[FaultID.NamespaceAsObject] = {cookBookRef: '114', }; +faultsAttrs[FaultID.NonDeclarationInNamespace] = {cookBookRef: '116', }; +faultsAttrs[FaultID.ImportFromPath] = {cookBookRef: '119', }; +faultsAttrs[FaultID.TypeOnlyImport] = {migratable: true, cookBookRef: '118', }; +faultsAttrs[FaultID.DefaultImport] = {migratable: true, cookBookRef: '120', }; +faultsAttrs[FaultID.ImportAssignment] = {cookBookRef: '121', }; +faultsAttrs[FaultID.ExportAssignment] = {cookBookRef: '126', }; +faultsAttrs[FaultID.TypeOnlyExport] = {migratable: true, cookBookRef: '127', }; +faultsAttrs[FaultID.ShorthandAmbientModuleDecl] = {cookBookRef: '128', }; +faultsAttrs[FaultID.WildcardsInModuleName] = {cookBookRef: '129', }; +faultsAttrs[FaultID.UMDModuleDefinition] = {cookBookRef: '130', }; +faultsAttrs[FaultID.NewTarget] = {cookBookRef: '132', }; +faultsAttrs[FaultID.DefiniteAssignment] = {warning: true, cookBookRef: '134', }; +faultsAttrs[FaultID.Prototype] = {cookBookRef: '136', }; +faultsAttrs[FaultID.GlobalThis] = {cookBookRef: '137', }; +faultsAttrs[FaultID.UtilityType] = {cookBookRef: '138', }; +faultsAttrs[FaultID.PropertyDeclOnFunction] = {cookBookRef: '139', }; +faultsAttrs[FaultID.FunctionApplyBindCall] = {cookBookRef: '140', }; +faultsAttrs[FaultID.ConstAssertion] = {cookBookRef: '142', }; +faultsAttrs[FaultID.ImportAssertion] = {cookBookRef: '143', }; +faultsAttrs[FaultID.LimitedStdLibApi] = {cookBookRef: '144', }; +faultsAttrs[FaultID.StrictDiagnostic] = {cookBookRef: '145', }; +faultsAttrs[FaultID.ErrorSuppression] = {cookBookRef: '146', }; +faultsAttrs[FaultID.UnsupportedDecorators] = {warning: true, cookBookRef: '148', }; +faultsAttrs[FaultID.ClassAsObject] = {cookBookRef: '149', }; +faultsAttrs[FaultID.ImportAfterStatement] = {cookBookRef: '150', }; +faultsAttrs[FaultID.EsObjectType] = {warning: true, cookBookRef: '151', }; diff --git a/ets2panda/linter-4.2/src/TestRunner.ts b/ets2panda/linter-4.2/src/TestRunner.ts index 48bba00889..73ad1f9b7b 100644 --- a/ets2panda/linter-4.2/src/TestRunner.ts +++ b/ets2panda/linter-4.2/src/TestRunner.ts @@ -60,10 +60,11 @@ function runTests(testDirs: string[]): number { TypeScriptLinter.ideMode = true; TypeScriptLinter.testMode = true; - let passed = 0, failed = 0; + let passed = 0; + let failed = 0; // Get tests from test directory - if (!testDirs?.length) testDirs = [ TEST_DIR ]; + if (!testDirs?.length) testDirs = [TEST_DIR]; for (const testDir of testDirs) { let testFiles: string[] = fs.readdirSync(testDir) .filter((x) => (x.trimEnd().endsWith(ts.Extension.Ts) && !x.trimEnd().endsWith(ts.Extension.Dts)) || x.trimEnd().endsWith(ts.Extension.Tsx)); @@ -143,8 +144,8 @@ function runTest(testDir: string, testFile: string, mode: Mode): boolean { const resultNodes: TestNodeInfo[] = fileProblems.map( (x) => ({ - line: x.line, column: x.column, problem: x.problem, - autofixable: mode === Mode.AUTOFIX ? x.autofixable : undefined, + line: x.line, column: x.column, problem: x.problem, + autofixable: mode === Mode.AUTOFIX ? x.autofixable : undefined, autofix: mode === Mode.AUTOFIX ? x.autofix : undefined, suggest: x.suggest, rule: x.rule @@ -209,14 +210,14 @@ function autofixArraysMatch(expected: Autofix[] | undefined, actual: Autofix[] | if (!(expected && actual) || expected.length !== actual.length) return false; for (let i = 0; i < actual.length; ++i) { if ( - actual[i].start !== expected[i].start || actual[i].end !== expected[i].end || + actual[i].start !== expected[i].start || actual[i].end !== expected[i].end || actual[i].replacementText.replace(/\r\n/g, '\n') !== expected[i].replacementText.replace(/\r\n/g, '\n') ) return false; } return true; } -function writeActualResultFile(testDir: string, testFile: string, resultExt: string, resultNodes: TestNodeInfo[], diff: string) { +function writeActualResultFile(testDir: string, testFile: string, resultExt: string, resultNodes: TestNodeInfo[], diff: string): void { const actualResultsDir = path.join(testDir, 'results'); if (!fs.existsSync(actualResultsDir)) fs.mkdirSync(actualResultsDir); diff --git a/ets2panda/linter-4.2/src/TypeScriptLinter.ts b/ets2panda/linter-4.2/src/TypeScriptLinter.ts index 7e11b132f4..5f1a6bba91 100644 --- a/ets2panda/linter-4.2/src/TypeScriptLinter.ts +++ b/ets2panda/linter-4.2/src/TypeScriptLinter.ts @@ -36,7 +36,7 @@ const logger = Logger.getLogger(); export function consoleLog(...args: any[]): void { if (TypeScriptLinter.ideMode) return; - let outLine = ""; + let outLine = ''; for (let k = 0; k < args.length; k++) { outLine += `${args[k]} `; } @@ -50,9 +50,9 @@ export class TypeScriptLinter { lineCounters: number[] = []; totalErrorLines: number = 0; - errorLineNumbersString: string = ""; + errorLineNumbersString: string = ''; totalWarningLines: number = 0; - warningLineNumbersString: string = ""; + warningLineNumbersString: string = ''; problemsInfos: ProblemInfo[] = []; @@ -155,7 +155,7 @@ export class TypeScriptLinter { faultId: number, autofixable: boolean = false, autofix?: Autofix[] - ) { + ): void { if (!this.strictMode && faultsAttrs[faultId].migratable) // In relax mode skip migratable return; @@ -174,9 +174,9 @@ export class TypeScriptLinter { let faultType = LinterConfig.tsSyntaxKindNames[node.kind]; if (TypeScriptLinter.ideMode) { - const cookBookMsgNum = faultsAttrs[faultId] - ? Number(faultsAttrs[faultId].cookBookRef) - : 0; + const cookBookMsgNum = faultsAttrs[faultId] ? + Number(faultsAttrs[faultId].cookBookRef) : + 0; const cookBookTg = cookBookTag[cookBookMsgNum]; let severity = ProblemSeverity.ERROR; if (faultsAttrs[faultId] && faultsAttrs[faultId].warning) @@ -191,13 +191,13 @@ export class TypeScriptLinter { type: faultType, severity: severity, problem: FaultID[faultId], - suggest: cookBookMsgNum > 0 ? cookBookMsg[cookBookMsgNum] : "", + suggest: cookBookMsgNum > 0 ? cookBookMsg[cookBookMsgNum] : '', rule: - cookBookMsgNum > 0 && cookBookTg !== "" - ? cookBookTg - : faultDescr - ? faultDescr - : faultType, + cookBookMsgNum > 0 && cookBookTg !== '' ? + cookBookTg : + faultDescr ? + faultDescr : + faultType, ruleTag: cookBookMsgNum, autofixable: autofixable, autofix: autofix, @@ -218,12 +218,12 @@ export class TypeScriptLinter { if (line !== this.currentWarningLine) { this.currentWarningLine = line; ++this.totalWarningLines; - this.warningLineNumbersString += line + ", "; + this.warningLineNumbersString += line + ', '; } } else if (line !== this.currentErrorLine) { this.currentErrorLine = line; ++this.totalErrorLines; - this.errorLineNumbersString += line + ", "; + this.errorLineNumbersString += line + ', '; } } @@ -263,7 +263,7 @@ export class TypeScriptLinter { prop2type: Map, propName: string, type: ts.TypeNode | undefined - ) { + ): void { if (type) { const methodType = type.getText(); const propType = prop2type.get(propName); @@ -340,7 +340,7 @@ export class TypeScriptLinter { private scopeContainsThis(tsNode: ts.Node): boolean { let found = false; - function visitNode(tsNode: ts.Node) { + function visitNode(tsNode: ts.Node): void { // Stop visiting child nodes if finished searching. if (found) return; @@ -371,7 +371,7 @@ export class TypeScriptLinter { if ( !( ts.isIdentifier(tsPropertyAccess.name) && - tsPropertyAccess.name.text === "prototype" + tsPropertyAccess.name.text === 'prototype' ) ) return false; @@ -485,7 +485,7 @@ export class TypeScriptLinter { } } - private handleObjectLiteralExpression(node: ts.Node) { + private handleObjectLiteralExpression(node: ts.Node): void { let objectLiteralExpr = node as ts.ObjectLiteralExpression; // If object literal is a part of destructuring assignment, then don't process it further. @@ -501,7 +501,7 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.ObjectLiteralNoContextType); } - private handleArrayLiteralExpression(node: ts.Node) { + private handleArrayLiteralExpression(node: ts.Node): void { // If array literal is a part of destructuring assignment, then // don't process it further. if ( @@ -512,7 +512,7 @@ export class TypeScriptLinter { return; let arrayLitNode = node as ts.ArrayLiteralExpression; - let noContextTypeForArrayLiteral = false; + let absentContextTypeForArrayLiteral = false; // check that array literal consists of inferrable types // e.g. there is no element which is untyped object literals @@ -524,17 +524,17 @@ export class TypeScriptLinter { !this.tsUtils.isDynamicLiteralInitializer(arrayLitNode) && !this.tsUtils.isObjectLiteralAssignable(objectLiteralType, element) ) { - noContextTypeForArrayLiteral = true; + absentContextTypeForArrayLiteral = true; break; } } } - if (noContextTypeForArrayLiteral) + if (absentContextTypeForArrayLiteral) this.incrementCounters(node, FaultID.ArrayLiteralNoContextType); } - private handleParameter(node: ts.Node) { + private handleParameter(node: ts.Node): void { let tsParam = node as ts.ParameterDeclaration; if ( ts.isArrayBindingPattern(tsParam.name) || @@ -556,7 +556,7 @@ export class TypeScriptLinter { this.handleDeclarationInferredType(tsParam); } - private handleEnumDeclaration(node: ts.Node) { + private handleEnumDeclaration(node: ts.Node): void { let enumNode = node as ts.EnumDeclaration; this.countDeclarationsWithDuplicateName(enumNode.name, enumNode); @@ -579,7 +579,7 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.EnumMerging); } - private handleInterfaceDeclaration(node: ts.Node) { + private handleInterfaceDeclaration(node: ts.Node): void { let interfaceNode = node as ts.InterfaceDeclaration; let iSymbol = this.tsUtils.trueSymbolAtLocation(interfaceNode.name); let iDecls = iSymbol ? iSymbol.getDeclarations() : null; @@ -604,7 +604,7 @@ export class TypeScriptLinter { this.countDeclarationsWithDuplicateName(interfaceNode.name, interfaceNode); } - private handleThrowStatement(node: ts.Node) { + private handleThrowStatement(node: ts.Node): void { let throwStmt = node as ts.ThrowStatement; let throwExprType = this.tsTypeChecker.getTypeAtLocation( throwStmt.expression @@ -617,7 +617,7 @@ export class TypeScriptLinter { } } - private handleForStatement(node: ts.Node) { + private handleForStatement(node: ts.Node): void { let tsForStmt = node as ts.ForStatement; let tsForInit = tsForStmt.initializer; if ( @@ -628,7 +628,7 @@ export class TypeScriptLinter { this.incrementCounters(tsForInit, FaultID.DestructuringAssignment); } - private handleForInStatement(node: ts.Node) { + private handleForInStatement(node: ts.Node): void { let tsForInStmt = node as ts.ForInStatement; let tsForInInit = tsForInStmt.initializer; if ( @@ -639,7 +639,7 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.ForInStatement); } - private handleForOfStatement(node: ts.Node) { + private handleForOfStatement(node: ts.Node): void { let tsForOfStmt = node as ts.ForOfStatement; let tsForOfInit = tsForOfStmt.initializer; if ( @@ -650,7 +650,7 @@ export class TypeScriptLinter { } } - private handleImportDeclaration(node: ts.Node) { + private handleImportDeclaration(node: ts.Node): void { let importDeclNode = node as ts.ImportDeclaration; for (const stmt of importDeclNode.parent.statements) { if (stmt === importDeclNode) { @@ -668,7 +668,7 @@ export class TypeScriptLinter { } } - private handlePropertyAccessExpression(node: ts.Node) { + private handlePropertyAccessExpression(node: ts.Node): void { let propertyAccessNode = node as ts.PropertyAccessExpression; const exprSym = this.tsUtils.trueSymbolAtLocation(propertyAccessNode); @@ -683,7 +683,7 @@ export class TypeScriptLinter { } } - private handlePropertyAssignmentOrDeclaration(node: ts.Node) { + private handlePropertyAssignmentOrDeclaration(node: ts.Node): void { let propName = (node as ts.PropertyAssignment | ts.PropertyDeclaration) .name; @@ -753,7 +753,7 @@ export class TypeScriptLinter { if (this.tscStrictDiagnostics && this.sourceFile) { if ( decorators?.some((x) => { - let decoratorName = ""; + let decoratorName = ''; if (ts.isIdentifier(x.expression)) decoratorName = x.expression.text; else if ( ts.isCallExpression(x.expression) && @@ -763,7 +763,7 @@ export class TypeScriptLinter { // special case for property of type CustomDialogController of the @CustomDialog-decorated class if (expectedDecorators.includes(TsUtils.NON_INITIALIZABLE_PROPERTY_CLASS_DECORATORS[0])) { - return expectedDecorators.includes(decoratorName) && propType === 'CustomDialogController' + return expectedDecorators.includes(decoratorName) && propType === 'CustomDialogController'; } return expectedDecorators.includes( decoratorName @@ -815,7 +815,7 @@ export class TypeScriptLinter { return false; } let file = path.normalize(this.sourceFile.fileName); - let tscDiagnostics = this.tscStrictDiagnostics.get(file) + let tscDiagnostics = this.tscStrictDiagnostics.get(file); if (!tscDiagnostics) { return false; } @@ -838,7 +838,7 @@ export class TypeScriptLinter { return true; } - private handleFunctionExpression(node: ts.Node) { + private handleFunctionExpression(node: ts.Node): void { const funcExpr = node as ts.FunctionExpression; const isGenerator = funcExpr.asteriskToken !== undefined; const containsThis = this.scopeContainsThis(funcExpr.body); @@ -887,7 +887,7 @@ export class TypeScriptLinter { } } - private handleArrowFunction(node: ts.Node) { + private handleArrowFunction(node: ts.Node): void { const arrowFunc = node as ts.ArrowFunction; const containsThis = this.scopeContainsThis(arrowFunc.body); const hasValidContext = @@ -907,13 +907,13 @@ export class TypeScriptLinter { } } - private handleClassExpression(node: ts.Node) { + private handleClassExpression(node: ts.Node): void { let tsClassExpr = node as ts.ClassExpression; this.incrementCounters(node, FaultID.ClassExpression); this.handleDecorators(tsClassExpr.decorators); } - private handleFunctionDeclaration(node: ts.Node) { + private handleFunctionDeclaration(node: ts.Node): void { let tsFunctionDeclaration = node as ts.FunctionDeclaration; if (!tsFunctionDeclaration.type) this.handleMissingReturnType(tsFunctionDeclaration); @@ -1040,7 +1040,7 @@ export class TypeScriptLinter { return hasLimitedTypeInference; } - private handlePrefixUnaryExpression(node: ts.Node) { + private handlePrefixUnaryExpression(node: ts.Node): void { let tsUnaryArithm = node as ts.PrefixUnaryExpression; let tsUnaryOp = tsUnaryArithm.operator; if ( @@ -1066,7 +1066,7 @@ export class TypeScriptLinter { } } - private handleBinaryExpression(node: ts.Node) { + private handleBinaryExpression(node: ts.Node): void { let tsBinaryExpr = node as ts.BinaryExpression; let tsLhsExpr = tsBinaryExpr.left; let tsRhsExpr = tsBinaryExpr.right; @@ -1192,7 +1192,7 @@ export class TypeScriptLinter { } } - private handleVariableDeclarationList(node: ts.Node) { + private handleVariableDeclarationList(node: ts.Node): void { let varDeclFlags = ts.getCombinedNodeFlags(node); if (!(varDeclFlags & (ts.NodeFlags.Let | ts.NodeFlags.Const))) this.incrementCounters(node, FaultID.VarDeclaration); @@ -1268,7 +1268,7 @@ export class TypeScriptLinter { } } - private handleCatchClause(node: ts.Node) { + private handleCatchClause(node: ts.Node): void { let tsCatch = node as ts.CatchClause; // In TS catch clause doesn't permit specification of the exception varible type except 'any' or 'unknown'. // It is not compatible with STS 'catch' where the exception variable has to be of type @@ -1292,7 +1292,7 @@ export class TypeScriptLinter { } } - private handleClassDeclaration(node: ts.Node) { + private handleClassDeclaration(node: ts.Node): void { let tsClassDecl = node as ts.ClassDeclaration; this.staticBlocks.clear(); @@ -1323,7 +1323,7 @@ export class TypeScriptLinter { this.handleDecorators(tsClassDecl.decorators); } - private handleModuleDeclaration(node: ts.Node) { + private handleModuleDeclaration(node: ts.Node): void { let tsModuleDecl = node as ts.ModuleDeclaration; this.countDeclarationsWithDuplicateName(tsModuleDecl.name, tsModuleDecl); @@ -1366,17 +1366,17 @@ export class TypeScriptLinter { if ( ts.isStringLiteral(tsModuleDecl.name) && - tsModuleDecl.name.text.includes("*") + tsModuleDecl.name.text.includes('*') ) this.incrementCounters(tsModuleDecl, FaultID.WildcardsInModuleName); } - private handleTypeAliasDeclaration(node: ts.Node) { + private handleTypeAliasDeclaration(node: ts.Node): void { let tsTypeAlias = node as ts.TypeAliasDeclaration; this.countDeclarationsWithDuplicateName(tsTypeAlias.name, tsTypeAlias); } - private handleImportClause(node: ts.Node) { + private handleImportClause(node: ts.Node): void { let tsImportClause = node as ts.ImportClause; if (tsImportClause.name) { this.countDeclarationsWithDuplicateName(tsImportClause.name, tsImportClause); @@ -1421,19 +1421,19 @@ export class TypeScriptLinter { } } - private handleImportSpecifier(node: ts.Node) { + private handleImportSpecifier(node: ts.Node): void { let importSpec = node as ts.ImportSpecifier; this.countDeclarationsWithDuplicateName(importSpec.name, importSpec); } - private handleNamespaceImport(node: ts.Node) { + private handleNamespaceImport(node: ts.Node): void { let tsNamespaceImport = node as ts.NamespaceImport; this.countDeclarationsWithDuplicateName(tsNamespaceImport.name, tsNamespaceImport); } - private handleTypeAssertionExpression(node: ts.Node) { + private handleTypeAssertionExpression(node: ts.Node): void { let tsTypeAssertion = node as ts.TypeAssertion; - if (tsTypeAssertion.type.getText() === "const") + if (tsTypeAssertion.type.getText() === 'const') this.incrementCounters(tsTypeAssertion, FaultID.ConstAssertion); else this.incrementCounters(node, FaultID.TypeAssertion, true, [ @@ -1477,7 +1477,7 @@ export class TypeScriptLinter { } } - private handleIdentifier(node: ts.Node) { + private handleIdentifier(node: ts.Node): void { let tsIdentifier = node as ts.Identifier; let tsIdentSym = this.tsUtils.trueSymbolAtLocation(tsIdentifier); if (!tsIdentSym) { @@ -1516,7 +1516,7 @@ export class TypeScriptLinter { return false; } - private handleRestrictedValues(tsIdentifier: ts.Identifier, tsIdentSym: ts.Symbol) { + private handleRestrictedValues(tsIdentifier: ts.Identifier, tsIdentSym: ts.Symbol): void { const illegalValues = ts.SymbolFlags.ConstEnum | ts.SymbolFlags.RegularEnum | ts.SymbolFlags.ValueModule | ts.SymbolFlags.Class; // If module name is duplicated by another declaration, this increases the possibility @@ -1585,7 +1585,7 @@ export class TypeScriptLinter { ); } - private handleElementAccessExpression(node: ts.Node) { + private handleElementAccessExpression(node: ts.Node): void { const tsElementAccessExpr = node as ts.ElementAccessExpression; const tsElemAccessBaseExprType = this.tsTypeChecker.getTypeAtLocation( tsElementAccessExpr.expression @@ -1627,7 +1627,7 @@ export class TypeScriptLinter { } } - private handleEnumMember(node: ts.Node) { + private handleEnumMember(node: ts.Node): void { let tsEnumMember = node as ts.EnumMember; let tsEnumMemberType = this.tsTypeChecker.getTypeAtLocation(tsEnumMember); let constVal = this.tsTypeChecker.getConstantValue(tsEnumMember); @@ -1648,16 +1648,16 @@ export class TypeScriptLinter { // so check that value type is string if ( constVal !== undefined && - typeof constVal === "string" && + typeof constVal === 'string' && firstElewmVal !== undefined && - typeof firstElewmVal === "string" + typeof firstElewmVal === 'string' ) return; if ( constVal !== undefined && - typeof constVal === "number" && + typeof constVal === 'number' && firstElewmVal !== undefined && - typeof firstElewmVal === "number" + typeof firstElewmVal === 'number' ) return; if (firstEnumMemberType !== tsEnumMemberType) { @@ -1665,7 +1665,7 @@ export class TypeScriptLinter { } } - private handleExportDeclaration(node: ts.Node) { + private handleExportDeclaration(node: ts.Node): void { let tsExportDecl = node as ts.ExportDeclaration; if (tsExportDecl.isTypeOnly) { let autofix: Autofix[] | undefined; @@ -1675,14 +1675,14 @@ export class TypeScriptLinter { } } - private handleExportAssignment(node: ts.Node) { + private handleExportAssignment(node: ts.Node): void { const exportAssignment = node as ts.ExportAssignment; if (exportAssignment.isExportEquals) { this.incrementCounters(node, FaultID.ExportAssignment); } } - private handleCallExpression(node: ts.Node) { + private handleCallExpression(node: ts.Node): void { let tsCallExpr = node as ts.CallExpression; const calleeSym = this.tsUtils.trueSymbolAtLocation(tsCallExpr.expression); @@ -1709,9 +1709,12 @@ export class TypeScriptLinter { this.handleLibraryTypeCall(tsCallExpr, calleeType); } - private handleImportCall(tsCallExpr: ts.CallExpression) { + private handleImportCall(tsCallExpr: ts.CallExpression): void { if (tsCallExpr.expression.kind === ts.SyntaxKind.ImportKeyword) { - // relax rule#133 "arkts-no-runtime-import" + + // relax rule#133 'arkts-no-runtime-import' + // this.incrementCounters(tsCallExpr, FaultID.DynamicImport); + const tsArgs = tsCallExpr.arguments; if (tsArgs.length > 1 && ts.isObjectLiteralExpression(tsArgs[1])) { let objLitExpr = tsArgs[1] as ts.ObjectLiteralExpression; @@ -1720,7 +1723,7 @@ export class TypeScriptLinter { ts.isPropertyAssignment(tsProp) || ts.isShorthandPropertyAssignment(tsProp) ) { - if (tsProp.name.getText() === "assert") { + if (tsProp.name.getText() === 'assert') { this.incrementCounters(tsProp, FaultID.ImportAssertion); break; } @@ -1733,22 +1736,22 @@ export class TypeScriptLinter { private handleRequireCall(tsCallExpr: ts.CallExpression): void { if ( ts.isIdentifier(tsCallExpr.expression) && - tsCallExpr.expression.text === "require" && + tsCallExpr.expression.text === 'require' && ts.isVariableDeclaration(tsCallExpr.parent) ) { let tsType = this.tsTypeChecker.getTypeAtLocation(tsCallExpr.expression); if ( this.tsUtils.isInterfaceType(tsType) && - tsType.symbol.name === "NodeRequire" + tsType.symbol.name === 'NodeRequire' ) this.incrementCounters(tsCallExpr.parent, FaultID.ImportAssignment); } } private handleGenericCallWithNoTypeArgs(callLikeExpr: ts.CallExpression | ts.NewExpression, callSignature: ts.Signature): void { - let tsSyntaxKind = ts.isNewExpression(callLikeExpr) - ? ts.SyntaxKind.Constructor - : ts.SyntaxKind.FunctionDeclaration; + let tsSyntaxKind = ts.isNewExpression(callLikeExpr) ? + ts.SyntaxKind.Constructor : + ts.SyntaxKind.FunctionDeclaration; let signDecl = this.tsTypeChecker.signatureToSignatureDeclaration( callSignature, tsSyntaxKind, @@ -1873,11 +1876,11 @@ export class TypeScriptLinter { ); for (const msgChain of diagnosticMessages) { - TypeScriptLinter.filteredDiagnosticMessages.add(msgChain) + TypeScriptLinter.filteredDiagnosticMessages.add(msgChain); } } - private handleNewExpression(node: ts.Node) { + private handleNewExpression(node: ts.Node): void { let tsNewExpr = node as ts.NewExpression; let callSignature = this.tsTypeChecker.getResolvedSignature(tsNewExpr); if (callSignature !== undefined) { @@ -1886,9 +1889,9 @@ export class TypeScriptLinter { } } - private handleAsExpression(node: ts.Node) { + private handleAsExpression(node: ts.Node): void { let tsAsExpr = node as ts.AsExpression; - if (tsAsExpr.type.getText() === "const") + if (tsAsExpr.type.getText() === 'const') this.incrementCounters(node, FaultID.ConstAssertion); let targetType = this.tsTypeChecker.getTypeAtLocation(tsAsExpr.type).getNonNullableType(); @@ -1899,14 +1902,14 @@ export class TypeScriptLinter { // check for rule#65: 'number as Number' and 'boolean as Boolean' are disabled if ( (this.tsUtils.isNumberType(exprType) && - targetType.getSymbol()?.getName() === "Number") || + targetType.getSymbol()?.getName() === 'Number') || (this.tsUtils.isBooleanType(exprType) && - targetType.getSymbol()?.getName() === "Boolean") + targetType.getSymbol()?.getName() === 'Boolean') ) this.incrementCounters(node, FaultID.TypeAssertion); } - private handleTypeReference(node: ts.Node) { + private handleTypeReference(node: ts.Node): void { const typeRef = node as ts.TypeReferenceNode; const isESObject = this.tsUtils.isEsObjectType(typeRef); @@ -1934,21 +1937,21 @@ export class TypeScriptLinter { } } - private handleMetaProperty(node: ts.Node) { + private handleMetaProperty(node: ts.Node): void { let tsMetaProperty = node as ts.MetaProperty; if (tsMetaProperty.name.text === 'target') { this.incrementCounters(node, FaultID.NewTarget); } } - private handleStructDeclaration(node: ts.Node) { + private handleStructDeclaration(node: ts.Node): void { node.forEachChild((child) => { // Skip synthetic constructor in Struct declaration. if (!ts.isConstructorDeclaration(child)) this.visitTSNode(child); }); } - private handleSpreadOp(node: ts.Node) { + private handleSpreadOp(node: ts.Node): void { // spread assignment is disabled // spread element is allowed only for arrays as rest parameter if (ts.isSpreadElement(node)) { @@ -1980,7 +1983,7 @@ export class TypeScriptLinter { this.incrementCounters(node, FaultID.SpreadOperator); } - private handleConstructSignature(node: ts.Node) { + private handleConstructSignature(node: ts.Node): void { switch (node.parent.kind) { case ts.SyntaxKind.TypeLiteral: this.incrementCounters(node, FaultID.ConstructorType); @@ -1993,7 +1996,7 @@ export class TypeScriptLinter { } } - private handleComments(node: ts.Node) { + private handleComments(node: ts.Node): void { // Note: Same comment may be owned by several nodes if their // start/end position matches. Thus, look for the most parental // owner of the specific comment (by the node's position). @@ -2025,7 +2028,7 @@ export class TypeScriptLinter { } } - private handleExpressionWithTypeArguments(node: ts.Node) { + private handleExpressionWithTypeArguments(node: ts.Node): void { let tsTypeExpr = node as ts.ExpressionWithTypeArguments; let symbol = this.tsUtils.trueSymbolAtLocation(tsTypeExpr.expression); if (!!symbol && this.tsUtils.isEsObjectSymbol(symbol)) { @@ -2036,17 +2039,18 @@ export class TypeScriptLinter { private checkErrorSuppressingAnnotation( comment: ts.CommentRange, srcText: string - ) { + ): void { + const CMNT_SHIFT = 2; const commentContent = - comment.kind === ts.SyntaxKind.MultiLineCommentTrivia - ? srcText.slice(comment.pos + 2, comment.end - 2) - : srcText.slice(comment.pos + 2, comment.end); + comment.kind === ts.SyntaxKind.MultiLineCommentTrivia ? + srcText.slice(comment.pos + CMNT_SHIFT, comment.end - CMNT_SHIFT) : + srcText.slice(comment.pos + CMNT_SHIFT, comment.end); let trimmedContent = commentContent.trim(); if ( - trimmedContent.startsWith("@ts-ignore") || - trimmedContent.startsWith("@ts-nocheck") || - trimmedContent.startsWith("@ts-expect-error") + trimmedContent.startsWith('@ts-ignore') || + trimmedContent.startsWith('@ts-nocheck') || + trimmedContent.startsWith('@ts-expect-error') ) this.incrementCounters(comment, FaultID.ErrorSuppression); } @@ -2057,7 +2061,7 @@ export class TypeScriptLinter { if (!decorators) return; for (const decorator of decorators) { - let decoratorName = ""; + let decoratorName = ''; if (ts.isIdentifier(decorator.expression)) decoratorName = decorator.expression.text; else if ( @@ -2075,7 +2079,7 @@ export class TypeScriptLinter { this.handleDecorators((node as ts.GetAccessorDeclaration).decorators); } - private handleSetAccessor(node: ts.Node) { + private handleSetAccessor(node: ts.Node): void { this.handleDecorators((node as ts.SetAccessorDeclaration).decorators); } @@ -2084,7 +2088,7 @@ export class TypeScriptLinter { | ts.VariableDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration - ) { + ): void { // The type is explicitly specified, no need to check inferred type. if (decl.type) return; @@ -2119,7 +2123,7 @@ export class TypeScriptLinter { private handleDefiniteAssignmentAssertion( decl: ts.VariableDeclaration | ts.PropertyDeclaration - ) { + ): void { if (decl.exclamationToken !== undefined) { this.incrementCounters(decl, FaultID.DefiniteAssignment); } @@ -2143,7 +2147,7 @@ export class TypeScriptLinter { private handleInferredObjectreference( type: ts.Type, decl: ts.VariableDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration - ) { + ): void { const typeArgs = this.tsTypeChecker.getTypeArguments(type as ts.TypeReference); if (typeArgs) { const haveAnyOrUnknownNodes = this.checkAnyOrUnknownChildNode(decl); @@ -2177,7 +2181,7 @@ export class TypeScriptLinter { if (type.isUnion()) { this.validatedTypesSet.add(type); for (let unionElem of type.types) { - this.validateDeclInferredType(unionElem, decl) + this.validateDeclInferredType(unionElem, decl); } } @@ -2187,7 +2191,7 @@ export class TypeScriptLinter { this.incrementCounters(decl, FaultID.UnknownType); } - public lint(sourceFile: ts.SourceFile) { + public lint(sourceFile: ts.SourceFile): void { this.sourceFile = sourceFile; this.visitTSNode(this.sourceFile); } diff --git a/ets2panda/linter-4.2/src/TypeScriptLinterConfig.ts b/ets2panda/linter-4.2/src/TypeScriptLinterConfig.ts index 1639e5664f..45a12e740a 100644 --- a/ets2panda/linter-4.2/src/TypeScriptLinterConfig.ts +++ b/ets2panda/linter-4.2/src/TypeScriptLinterConfig.ts @@ -138,7 +138,7 @@ export class LinterConfig { // must detect terminals during parsing static terminalTokens: Set = new Set([ - ts.SyntaxKind.OpenBraceToken, ts.SyntaxKind.CloseBraceToken, ts.SyntaxKind.OpenParenToken, + ts.SyntaxKind.OpenBraceToken, ts.SyntaxKind.CloseBraceToken, ts.SyntaxKind.OpenParenToken, ts.SyntaxKind.CloseParenToken, ts.SyntaxKind.OpenBracketToken, ts.SyntaxKind.CloseBracketToken, ts.SyntaxKind.DotToken, ts.SyntaxKind.DotDotDotToken, ts.SyntaxKind.SemicolonToken, ts.SyntaxKind.CommaToken, ts.SyntaxKind.QuestionDotToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanSlashToken, @@ -172,7 +172,7 @@ export class LinterConfig { [ts.SyntaxKind.RegularExpressionLiteral, FaultID.RegexLiteral], [ts.SyntaxKind.TypePredicate, FaultID.IsOperator], [ts.SyntaxKind.YieldExpression, FaultID.YieldExpression], [ts.SyntaxKind.IndexSignature, FaultID.IndexMember], [ts.SyntaxKind.WithStatement, FaultID.WithStatement], - [ts.SyntaxKind.IndexedAccessType, FaultID.IndexedAccessType],[ts.SyntaxKind.UnknownKeyword, FaultID.UnknownType], + [ts.SyntaxKind.IndexedAccessType, FaultID.IndexedAccessType], [ts.SyntaxKind.UnknownKeyword, FaultID.UnknownType], [ts.SyntaxKind.InKeyword, FaultID.InOperator], [ts.SyntaxKind.CallSignature, FaultID.CallSignature], [ts.SyntaxKind.IntersectionType, FaultID.IntersectionType], [ts.SyntaxKind.TypeLiteral, FaultID.ObjectTypeLiteral], [ts.SyntaxKind.ConstructorType, FaultID.ConstructorFuncs], diff --git a/ets2panda/linter-4.2/src/Utils.ts b/ets2panda/linter-4.2/src/Utils.ts index fa383a3e68..0bf3ffb3d5 100644 --- a/ets2panda/linter-4.2/src/Utils.ts +++ b/ets2panda/linter-4.2/src/Utils.ts @@ -20,14 +20,14 @@ import { AutofixInfo } from './AutofixInfo'; import { LinterConfig } from './TypeScriptLinterConfig' import { FaultID } from './Problems'; -export function logTscDiagnostic(diagnostics: readonly ts.Diagnostic[], log: (message: any, ...args: any[]) => void) { +export function logTscDiagnostic(diagnostics: readonly ts.Diagnostic[], log: (message: any, ...args: any[]) => void): void { diagnostics.forEach((diagnostic) => { let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); if (diagnostic.file && diagnostic.start) { const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); message = `${diagnostic.file.fileName} (${line + 1}, ${character + 1}): ${message}`; - } + }; log(message); }); @@ -57,9 +57,9 @@ export function getNodeOrLineEnd( ): number { const pos = sourceFile.getLineAndCharacterOfPosition(nodeEndPos); // TSC counts lines and columns from zero - return (pos.line + 1) === nodeStartLine - ? pos.character - : sourceFile.getLineEndOfPosition(nodeStartPos); + return (pos.line + 1) === nodeStartLine ? + pos.character : + sourceFile.getLineEndOfPosition(nodeStartPos); } export function mergeArrayMaps(lhs: Map, rhs: Map): Map { @@ -97,10 +97,10 @@ export function isAssignmentOperator(tsBinOp: ts.BinaryOperatorToken): boolean { export enum CheckType { Array, - String = "String", - Set = "Set", - Map = "Map", - Error = "Error", + String = 'String', + Set = 'Set', + Map = 'Map', + Error = 'Error', }; export class TsUtils { @@ -267,20 +267,20 @@ export class TsUtils { ]; static readonly STANDARD_LIBRARIES = [ - "lib.dom.d.ts", "lib.dom.iterable.d.ts", "lib.webworker.d.ts", "lib.webworker.importscripts.d.ts", - "lib.webworker.iterable.d.ts", "lib.scripthost.d.ts", "lib.decorators.d.ts", "lib.decorators.legacy.d.ts", - "lib.es5.d.ts", "lib.es2015.core.d.ts", "lib.es2015.collection.d.ts", "lib.es2015.generator.d.ts", - "lib.es2015.iterable.d.ts", "lib.es2015.promise.d.ts", "lib.es2015.proxy.d.ts", "lib.es2015.reflect.d.ts", - "lib.es2015.symbol.d.ts", "lib.es2015.symbol.wellknown.d.ts", "lib.es2016.array.include.d.ts", - "lib.es2017.object.d.ts", "lib.es2017.sharedmemory.d.ts", "lib.es2017.string.d.ts", "lib.es2017.intl.d.ts", - "lib.es2017.typedarrays.d.ts", "lib.es2018.asyncgenerator.d.ts", "lib.es2018.asynciterable.d.ts", - "lib.es2018.intl.d.ts", "lib.es2018.promise.d.ts", "lib.es2018.regexp.d.ts", "lib.es2019.array.d.ts", - "lib.es2019.object.d.ts", "lib.es2019.string.d.ts", "lib.es2019.symbol.d.ts", "lib.es2019.intl.d.ts", - "lib.es2020.bigint.d.ts", "lib.es2020.date.d.ts", "lib.es2020.promise.d.ts", "lib.es2020.sharedmemory.d.ts", - "lib.es2020.string.d.ts", "lib.es2020.symbol.wellknown.d.ts", "lib.es2020.intl.d.ts", "lib.es2020.number.d.ts", - "lib.es2021.promise.d.ts", "lib.es2021.string.d.ts", "lib.es2021.weakref.d.ts", "lib.es2021.intl.d.ts", - "lib.es2022.array.d.ts", "lib.es2022.error.d.ts", "lib.es2022.intl.d.ts", "lib.es2022.object.d.ts", - "lib.es2022.sharedmemory.d.ts", "lib.es2022.string.d.ts", "lib.es2022.regexp.d.ts", "lib.es2023.array.d.ts", + 'lib.dom.d.ts', 'lib.dom.iterable.d.ts', 'lib.webworker.d.ts', 'lib.webworker.importscripts.d.ts', + 'lib.webworker.iterable.d.ts', 'lib.scripthost.d.ts', 'lib.decorators.d.ts', 'lib.decorators.legacy.d.ts', + 'lib.es5.d.ts', 'lib.es2015.core.d.ts', 'lib.es2015.collection.d.ts', 'lib.es2015.generator.d.ts', + 'lib.es2015.iterable.d.ts', 'lib.es2015.promise.d.ts', 'lib.es2015.proxy.d.ts', 'lib.es2015.reflect.d.ts', + 'lib.es2015.symbol.d.ts', 'lib.es2015.symbol.wellknown.d.ts', 'lib.es2016.array.include.d.ts', + 'lib.es2017.object.d.ts', 'lib.es2017.sharedmemory.d.ts', 'lib.es2017.string.d.ts', 'lib.es2017.intl.d.ts', + 'lib.es2017.typedarrays.d.ts', 'lib.es2018.asyncgenerator.d.ts', 'lib.es2018.asynciterable.d.ts', + 'lib.es2018.intl.d.ts', 'lib.es2018.promise.d.ts', 'lib.es2018.regexp.d.ts', 'lib.es2019.array.d.ts', + 'lib.es2019.object.d.ts', 'lib.es2019.string.d.ts', 'lib.es2019.symbol.d.ts', 'lib.es2019.intl.d.ts', + 'lib.es2020.bigint.d.ts', 'lib.es2020.date.d.ts', 'lib.es2020.promise.d.ts', 'lib.es2020.sharedmemory.d.ts', + 'lib.es2020.string.d.ts', 'lib.es2020.symbol.wellknown.d.ts', 'lib.es2020.intl.d.ts', 'lib.es2020.number.d.ts', + 'lib.es2021.promise.d.ts', 'lib.es2021.string.d.ts', 'lib.es2021.weakref.d.ts', 'lib.es2021.intl.d.ts', + 'lib.es2022.array.d.ts', 'lib.es2022.error.d.ts', 'lib.es2022.intl.d.ts', 'lib.es2022.object.d.ts', + 'lib.es2022.sharedmemory.d.ts', 'lib.es2022.string.d.ts', 'lib.es2022.regexp.d.ts', 'lib.es2023.array.d.ts', ]; static readonly TYPED_ARRAYS = [ @@ -295,7 +295,7 @@ export class TsUtils { 'Float64Array', 'BigInt64Array', 'BigUint64Array', - ] + ]; static readonly ARKTS_IGNORE_DIRS = ['node_modules', 'oh_modules', 'build', '.preview']; static readonly ARKTS_IGNORE_FILES = ['hvigorfile.ts']; @@ -484,7 +484,7 @@ export class TsUtils { return sym; } - private isTypeDeclSyntaxKind(kind: ts.SyntaxKind) { + private isTypeDeclSyntaxKind(kind: ts.SyntaxKind): boolean { return this.isStructDeclarationKind(kind) || kind === ts.SyntaxKind.EnumDeclaration || kind === ts.SyntaxKind.ClassDeclaration || @@ -503,7 +503,7 @@ export class TsUtils { // we relax arkts-unique-names for namespace collision with class/interface/enum/type/struct const isNamespaceTypeCollision = (this.isTypeDeclSyntaxKind(declKind) && tsDeclKind === ts.SyntaxKind.ModuleDeclaration) || - (this.isTypeDeclSyntaxKind(tsDeclKind) && declKind === ts.SyntaxKind.ModuleDeclaration) + (this.isTypeDeclSyntaxKind(tsDeclKind) && declKind === ts.SyntaxKind.ModuleDeclaration); // Don't count declarations with 'Identifier' syntax kind as those // usually depict declaring an object's property through assignment. @@ -757,7 +757,7 @@ export class TsUtils { Number(tsExpr.getText()) : this.tsTypeChecker.getConstantValue(tsExpr); - return tsConstValue !== undefined && typeof tsConstValue === 'number'; + return tsConstValue !== undefined && typeof tsConstValue === 'number'; } public isIntegerConstantValue( @@ -863,9 +863,10 @@ export class TsUtils { return false; } - private processParentTypes(parentTypes: ts.NodeArray, typeB: ts.Type, processInterfaces: boolean): boolean { + private processParentTypes(parentTypes: ts.NodeArray, typeB: ts.Type, processInterfaces: boolean): boolean | undefined { for (let baseTypeExpr of parentTypes) { let baseType = this.tsTypeChecker.getTypeAtLocation(baseTypeExpr); + if (this.isTypeReference(baseType) && baseType.target !== baseType) baseType = baseType.target; if (baseType && (baseType.isClass() !== processInterfaces) && this.relatedByInheritanceOrIdentical(baseType, typeB)) { return true; @@ -1062,9 +1063,9 @@ export class TsUtils { private isDynamicObjectAssignedToStdType(lhsType: ts.Type, rhsExpr: ts.Expression): boolean { if (this.isStdLibraryType(lhsType) || this.isPrimitiveType(lhsType)) { - let rhsSym = ts.isCallExpression(rhsExpr) - ? this.getSymbolOfCallExpression(rhsExpr) - : this.tsTypeChecker.getSymbolAtLocation(rhsExpr); + let rhsSym = ts.isCallExpression(rhsExpr) ? + this.getSymbolOfCallExpression(rhsExpr) : + this.tsTypeChecker.getSymbolAtLocation(rhsExpr); if (rhsSym && this.isLibrarySymbol(rhsSym)) return true; @@ -1164,7 +1165,7 @@ export class TsUtils { !ts.isIntersectionTypeNode(typeNode) && this.isSupportedTypeNodeKind(typeNode.kind); } - public isStruct(symbol: ts.Symbol) { + public isStruct(symbol: ts.Symbol): boolean { if (!symbol.declarations) { return false; } @@ -1176,11 +1177,11 @@ export class TsUtils { return false; } - public isStructDeclarationKind(kind: ts.SyntaxKind) { + public isStructDeclarationKind(kind: ts.SyntaxKind): boolean { return LinterConfig.tsSyntaxKindNames[kind] === 'StructDeclaration'; } - public isStructDeclaration(node: ts.Node) { + public isStructDeclaration(node: ts.Node): boolean { return this.isStructDeclarationKind(node.kind); } @@ -1244,15 +1245,15 @@ export class TsUtils { } public getStartPos(nodeOrComment: ts.Node | ts.CommentRange): number { - return (nodeOrComment.kind === ts.SyntaxKind.SingleLineCommentTrivia || nodeOrComment.kind === ts.SyntaxKind.MultiLineCommentTrivia) - ? (nodeOrComment as ts.CommentRange).pos - : (nodeOrComment as ts.Node).getStart(); + return (nodeOrComment.kind === ts.SyntaxKind.SingleLineCommentTrivia || nodeOrComment.kind === ts.SyntaxKind.MultiLineCommentTrivia) ? + (nodeOrComment as ts.CommentRange).pos : + (nodeOrComment as ts.Node).getStart(); } public getEndPos(nodeOrComment: ts.Node | ts.CommentRange): number { - return (nodeOrComment.kind === ts.SyntaxKind.SingleLineCommentTrivia || nodeOrComment.kind === ts.SyntaxKind.MultiLineCommentTrivia) - ? (nodeOrComment as ts.CommentRange).end - : (nodeOrComment as ts.Node).getEnd(); + return (nodeOrComment.kind === ts.SyntaxKind.SingleLineCommentTrivia || nodeOrComment.kind === ts.SyntaxKind.MultiLineCommentTrivia) ? + (nodeOrComment as ts.CommentRange).end : + (nodeOrComment as ts.Node).getEnd(); } public isStdRecordType(type: ts.Type): boolean { @@ -1302,14 +1303,14 @@ export class TsUtils { return this.isLibraryType(this.tsTypeChecker.getTypeAtLocation(node)); } - public isLibrarySymbol(sym: ts.Symbol | undefined) { + public isLibrarySymbol(sym: ts.Symbol | undefined): boolean { if (sym && sym.declarations && sym.declarations.length > 0) { const srcFile = sym.declarations[0].getSourceFile(); if (!srcFile) { return false; } - const fileName = srcFile.fileName + const fileName = srcFile.fileName; // Symbols from both *.ts and *.d.ts files should obey interop rules. // We disable such behavior for *.ts files in the test mode due to lack of 'ets' // extension support. @@ -1330,14 +1331,14 @@ export class TsUtils { return false; } - public isStdFunctionType(type: ts.Type) { + public isStdFunctionType(type: ts.Type): boolean | undefined { const sym = type.getSymbol(); return sym && sym.getName() === 'Function' && this.isGlobalSymbol(sym); } public getScriptKind(srcFile: ts.SourceFile): ts.ScriptKind { - const fileName = srcFile.fileName - const ext = path.extname(fileName) + const fileName = srcFile.fileName; + const ext = path.extname(fileName); switch (ext.toLowerCase()) { case ts.Extension.Js: return ts.ScriptKind.JS; @@ -1358,7 +1359,7 @@ export class TsUtils { return this.isStdLibrarySymbol(type.aliasSymbol ?? type.getSymbol()); } - public isStdLibrarySymbol(sym: ts.Symbol | undefined) { + public isStdLibrarySymbol(sym: ts.Symbol | undefined): boolean { if (sym && sym.declarations && sym.declarations.length > 0) { const srcFile = sym.declarations[0].getSourceFile(); return srcFile && @@ -1428,7 +1429,7 @@ export class TsUtils { while (ts.isObjectLiteralExpression(curNode) || ts.isArrayLiteralExpression(curNode)) { const exprType = this.tsTypeChecker.getContextualType(curNode); if (exprType !== undefined && !this.isAnonymous(exprType)) { - const res = this.isDynamicType(exprType) + const res = this.isDynamicType(exprType); if (res !== undefined) { return res; } @@ -1444,14 +1445,14 @@ export class TsUtils { // foo({ ... }) if (ts.isCallExpression(curNode)) { const callExpr = curNode as ts.CallExpression; - const type = this.tsTypeChecker.getTypeAtLocation(callExpr.expression) + const type = this.tsTypeChecker.getTypeAtLocation(callExpr.expression); if (this.isAnyType(type)) { return true; } let sym: ts.Symbol | undefined = type.symbol; - if(this.isLibrarySymbol(sym)) { + if (this.isLibrarySymbol(sym)) { return true; } @@ -1527,7 +1528,7 @@ export class TsUtils { } public hasEsObjectType(node: ts.Node): boolean { - const typeNode = this.getVariableDeclarationTypeNode(node) + const typeNode = this.getVariableDeclarationTypeNode(node); return typeNode !== undefined && this.isEsObjectType(typeNode); } @@ -1603,7 +1604,7 @@ export class TsUtils { let found = false; const self = this; - function visitNode(tsNode: ts.Node) { + function visitNode(tsNode: ts.Node): void { // Stop visiting child nodes if finished searching. if (found) { return; diff --git a/ets2panda/linter-4.2/src/ts-diagnostics/TSCCompiledProgram.ts b/ets2panda/linter-4.2/src/ts-diagnostics/TSCCompiledProgram.ts index 29548ef9d8..f059be21f8 100644 --- a/ets2panda/linter-4.2/src/ts-diagnostics/TSCCompiledProgram.ts +++ b/ets2panda/linter-4.2/src/ts-diagnostics/TSCCompiledProgram.ts @@ -33,9 +33,9 @@ export class TSCCompiledProgram { } public getOriginalProgram(): ts.Program { - return this.wasStrict - ? this.diagnosticsExtractor.strictProgram - : this.diagnosticsExtractor.nonStrictProgram; + return this.wasStrict ? + this.diagnosticsExtractor.strictProgram : + this.diagnosticsExtractor.nonStrictProgram; } public getStrictDiagnostics(fileName: string): ts.Diagnostic[] { @@ -96,7 +96,7 @@ export function transformDiagnostic(diagnostic: ts.Diagnostic): ProblemInfo { start: startPos, end: endPos, type: 'StrictModeError', - severity: ProblemSeverity.ERROR, // expect strict options to always present + severity: ProblemSeverity.ERROR, // expect strict options to always present problem: FaultID[faultId], suggest: messageText, rule: messageText, diff --git a/ets2panda/linter-4.2/stats_calculator/src/calculate-stats.ts b/ets2panda/linter-4.2/stats_calculator/src/calculate-stats.ts index bd0f5a4bff..efb70a27eb 100644 --- a/ets2panda/linter-4.2/stats_calculator/src/calculate-stats.ts +++ b/ets2panda/linter-4.2/stats_calculator/src/calculate-stats.ts @@ -58,7 +58,7 @@ function isError(defectInfo: DefectInfo): boolean { return defectInfo.category === ARK_TS_ISSUES_ERROR_CATEGORY; } -function fillIssueInfo(statistics: Statistics, defectInfo: DefectInfo) { +function fillIssueInfo(statistics: Statistics, defectInfo: DefectInfo): void { const recipeNo = parseInt(defectInfo.ruleDocPath!!.substring( 'docs/recipe'.length, defectInfo.ruleDocPath!!.length - '.md'.length)); @@ -93,7 +93,7 @@ function parse(reportJson: ReportJson): Statistics { continue; } - fillIssueInfo(statistics, defectInfo) + fillIssueInfo(statistics, defectInfo); if (isError(defectInfo)) { statistics.totalErrors += 1; @@ -114,7 +114,7 @@ function read(filePath: string): ReportJson { return JSON.parse(fs.readFileSync(filePath, { encoding: 'utf8', flag: 'r' })); } -function main() { +function main(): void { if (process.argv.length < 3) { console.error('Path to input json was not provided, exiting'); process.exit(1); @@ -124,4 +124,4 @@ function main() { // file is stored in project's directory under the following path: // /.idea/code-linter/eslintAgent/output.json -main() +main(); -- Gitee