Skip to content

Commit

Permalink
fix(quality): sonar fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
prb28 committed Nov 13, 2023
1 parent eeb665d commit c2c2661
Show file tree
Hide file tree
Showing 26 changed files with 218 additions and 253 deletions.
26 changes: 11 additions & 15 deletions src/adf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,12 @@ export class ADFTools {
let pFile = new FileProxy(bUri);
if (await pFile.exists()) {
sourceFullPath = bUri;
} else {
} else if (workspaceRootDir) {
// file not exists
if (workspaceRootDir) {
sourceFullPath = Uri.file(path.join(workspaceRootDir.fsPath, bootBlockSourceFilename));
pFile = new FileProxy(sourceFullPath);
if (!pFile.exists()) {
sourceFullPath = null;
}
sourceFullPath = Uri.file(path.join(workspaceRootDir.fsPath, bootBlockSourceFilename));
pFile = new FileProxy(sourceFullPath);
if (!await pFile.exists()) {
sourceFullPath = null;
}
}
if (sourceFullPath) {
Expand All @@ -127,7 +125,7 @@ export class ADFTools {
const vasmBuildProperties = { ...VASMCompiler.DEFAULT_BUILD_CONFIGURATION };
vasmBuildProperties.args = ["-m68000", "-Fbin"];
const results = await compiler.buildFile(vasmBuildProperties, sourceFullPath, true);
if (results && results[0]) {
if (results?.[0]) {
const bootBlockDataFilename = results[0];
bootBlockFilename = bootBlockDataFilename.replace(".o", ".bb");
const bootBlockDataFilenameUri = Uri.file(bootBlockDataFilename);
Expand Down Expand Up @@ -156,13 +154,11 @@ export class ADFTools {
let rootSourceDirUri: Uri;
if (!path.isAbsolute(rootSourceDir) && workspace.workspaceFolders) {
rootSourceDirUri = Uri.file(path.join(workspace.workspaceFolders[0].uri.fsPath, rootSourceDir));
} else if (workspace.workspaceFolders) {
const relativePath = path.relative(workspace.workspaceFolders[0].uri.fsPath, rootSourceDir);
rootSourceDirUri = Uri.file(path.join(workspace.workspaceFolders[0].uri.fsPath, relativePath));
} else {
if (workspace.workspaceFolders) {
const relativePath = path.relative(workspace.workspaceFolders[0].uri.fsPath, rootSourceDir);
rootSourceDirUri = Uri.file(path.join(workspace.workspaceFolders[0].uri.fsPath, relativePath));
} else {
rootSourceDirUri = Uri.file(rootSourceDir);
}
rootSourceDirUri = Uri.file(rootSourceDir);
}
const sourceRootFileProxy = new FileProxy(rootSourceDirUri, true);
files = await sourceRootFileProxy.findFiles(includes, excludes);
Expand Down Expand Up @@ -275,7 +271,7 @@ export class ADFTools {
if (workspaceRootDir) {
rootPath = workspaceRootDir.fsPath;
}
const stdout = await this.executor.runToolRetrieveStdout(args, rootPath, commandFilename, null, cancellationToken);
const stdout = await this.executor.runToolRetrieveStdout(args, rootPath, commandFilename, undefined, cancellationToken);
if (stdout.indexOf("Done.") < 0) {
throw new Error(stdout);
}
Expand Down
18 changes: 9 additions & 9 deletions src/asmONE.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class AsmONE {
rxAuto: RegExp;

constructor() {
this.rxAuto = RegExp(".*AUTO.*", "gi");
this.rxAuto = /.*AUTO.*/gi;
}

/**
Expand All @@ -25,8 +25,8 @@ export class AsmONE {
public async Auto(filesURI: Uri[], exeFile: Uri): Promise<void> {
try {
let symbols = new Array<SourceSymbol>();
for (let i = 0; i < filesURI.length; i++) {
const src = filesURI[i].fsPath;
for (const element of filesURI) {
const src = element.fsPath;
const autos = this.findAutos(src);
if (0 === autos.length) {
continue;
Expand Down Expand Up @@ -58,7 +58,7 @@ export class AsmONE {
for (const err of errToFilter) {
if (err.severity.toUpperCase() === "WARNING") {
// remove auto warning message
if (err.msgData.match(this.rxAuto)) {
if (RegExp(this.rxAuto).exec(err.msgData)) {
continue;
}
}
Expand Down Expand Up @@ -105,8 +105,8 @@ export class AsmONE {
private async loadExeSymbols(exeFile: Uri): Promise<SourceSymbol[]> {
const symbols = new Array<SourceSymbol>();
const hunks = await parseHunksFromFile(exeFile.fsPath);
for (let i = 0; i < hunks.length; i++) {
const hunk: Hunk = hunks[i];
for (const element of hunks) {
const hunk: Hunk = element;
if (!hunk.symbols) {
continue;
}
Expand All @@ -129,9 +129,9 @@ export class AsmONE {

private findExeOffset(dest: string, symbols: SourceSymbol[]): number {
const offset = -1;
for (let i = 0; i < symbols.length; i++) {
if (dest === symbols[i].name) {
return symbols[i].offset;
for (const element of symbols) {
if (dest === element.name) {
return element.offset;
}
}
return offset;
Expand Down
4 changes: 2 additions & 2 deletions src/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class M86kColorProvider implements DocumentColorProvider {
* @param token Cancellation token
*/
public provideColorPresentations(
color: Color, context: { document: TextDocument, range: Range }, token: CancellationToken):
color: Color, context: { document: TextDocument, range: Range }):
ProviderResult<ColorPresentation[]> {
return [new ColorPresentation(this.formatColor(color, context.document.getText(context.range)))];
}
Expand Down Expand Up @@ -82,6 +82,6 @@ export class M86kColorProvider implements DocumentColorProvider {
* @param value Number to format
*/
private formatColorComponent(value: number): string {
return Math.round(value).toString(16).substr(0, 1);
return Math.round(value).toString(16).substring(0, 2);
}
}
41 changes: 21 additions & 20 deletions src/completion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class M68kCompletionItemProvider implements vscode.CompletionItemProvider
this.definitionHandler = definitionHandler;
this.language = language;
}
public async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.CompletionItem[]> {
public async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.CompletionItem[]> {
let completions = new Array<vscode.CompletionItem>();
let range = document.getWordRangeAtPosition(position);
const line = document.lineAt(position.line);
Expand All @@ -38,7 +38,7 @@ export class M68kCompletionItemProvider implements vscode.CompletionItemProvider
);
// Find previous global label
for (let i = range.start.line; i >= 0; i--) {
const match = document.lineAt(i).text.match(/^(\w+)\b/);
const match = RegExp(/^(\w+)\b/).exec(document.lineAt(i).text);
if (match) {
prefix = match[0];
break;
Expand All @@ -61,21 +61,19 @@ export class M68kCompletionItemProvider implements vscode.CompletionItemProvider
if (isInData) {
if (isMnemonic) {
continue;
} else {
if (value.type === DocumentationType.REGISTER || value.type === DocumentationType.CPU_REGISTER) {
if (word[0] === word[0].toLowerCase()) {
label = label.toLowerCase()
}
kind = vscode.CompletionItemKind.Variable;
} else if (word.startsWith("_LVO")) {
label = "_LVO" + label;
} else if (value.type === DocumentationType.REGISTER || value.type === DocumentationType.CPU_REGISTER) {
if (word.startsWith(word[0].toLowerCase())) {
label = label.toLowerCase()
}
kind = vscode.CompletionItemKind.Variable;
} else if (word.startsWith("_LVO")) {
label = "_LVO" + label;
}
} else {
if (!isMnemonic) {
continue;
}
if (word[0] === word[0].toUpperCase()) {
if (word[0].startsWith(word[0].toUpperCase())) {
label = label.toUpperCase()
}
}
Expand All @@ -98,7 +96,7 @@ export class M68kCompletionItemProvider implements vscode.CompletionItemProvider
const labels = this.definitionHandler.findLabelStartingWith(word);
for (const [label, symbol] of labels.entries()) {
const unPrefixed = label.substring(prefix.length);
const isLocalFQ = unPrefixed.match(/.\./);
const isLocalFQ = RegExp(/.\./).exec(unPrefixed);
if (!labelsAdded.includes(label) && !isLocalFQ) {
const kind = vscode.CompletionItemKind.Function;
const completion = new vscode.CompletionItem(unPrefixed, kind);
Expand Down Expand Up @@ -175,7 +173,7 @@ export class M68kCompletionItemProvider implements vscode.CompletionItemProvider
let start = 0;
if (range) {
start = range.start.character;
while (start > 0 && !line.text.charAt(start - 1).match(/[\s'"/]/)) {
while (start > 0 && !RegExp(/[\s'"/]/).exec(line.text.charAt(start - 1))) {
start--;
}
range = new vscode.Range(
Expand All @@ -195,7 +193,7 @@ export class M68kCompletionItemProvider implements vscode.CompletionItemProvider
let prefix = "";
let filter: string | undefined;
if (length > 0) {
const typedPath = asmLine.data.substr(start, length);
const typedPath = asmLine.data.substring(start, start + length);

// Get absolute or relative path
let newParent = incDir.getRelativeFile(typedPath);
Expand All @@ -212,12 +210,12 @@ export class M68kCompletionItemProvider implements vscode.CompletionItemProvider
const pos = normalizedTypedPath.lastIndexOf("/");
if (pos !== -1) {
// Typed path is a partial filename in a containing directory
const subPath = normalizedTypedPath.substr(0, Math.max(pos, 1));
const subPath = normalizedTypedPath.substring(0, Math.max(pos, 1) + 1);
// Get containing directory
newParent = incDir.getRelativeFile(subPath);
if (await newParent.exists() && await newParent.isDirectory()) {
incDir = newParent;
filter = normalizedTypedPath.substr(pos + 1);
filter = normalizedTypedPath.substring(pos + 1);
} else {
// containing directory doesn't exist
return [];
Expand Down Expand Up @@ -257,11 +255,14 @@ export class M68kCompletionItemProvider implements vscode.CompletionItemProvider
}

private cleanAndReorder(completions: vscode.CompletionItem[]): vscode.CompletionItem[] {
const fileMap = new Map<string, vscode.CompletionItem>();
for (const c of completions) {
fileMap.set(c.label.toString(), c);
const labelMap = new Map<string, vscode.CompletionItem>();

for (const completion of completions) {
const label = typeof completion.label === "string"
? completion.label : completion.label.label
labelMap.set(label, completion);
}
return Array.from(fileMap.values());
return Array.from(labelMap.values());
}

private async provideCompletionForIncludes(asmLine: ASMLine, document: vscode.TextDocument, position: vscode.Position): Promise<vscode.CompletionItem[]> {
Expand Down
22 changes: 10 additions & 12 deletions src/configVariables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ interface Context {
* The built-in logic in vscode only applies to specific properties and is not currently exposed in the public API
* https://github.com/Microsoft/vscode/issues/46471
*
* For now we need to re-create the behaviour in order to apply it to custom properties.
* For now we need to re-create the behavior in order to apply it to custom properties.
*
* Supported variables:
* - ${env:Name} - environment variable
Expand Down Expand Up @@ -118,36 +118,34 @@ export function substituteVariables(

// Environment variables:
str = str.replace(/\${env:(.*?)}/g, (variable) => {
const varName = variable.match(/\${env:(.*?)}/)?.[1];
const varName = RegExp(/\${env:(.*?)}/).exec(variable)?.[1];
return varName ? environmentVariables[varName] ?? "" : "";
});

// Config keys:
str = str.replace(/\${config:(.*?)}/g, (variable) => {
const varName = variable.match(/\${config:(.*?)}/)?.[1];
const varName = RegExp(/\${config:(.*?)}/).exec(variable)?.[1];
return varName ? configuration.get(varName, "") : "";
});

// Custom variables
// extensionResourcesFolder
if (extensionState) {
const pattern = new RegExp("\\${extensionResourcesFolder}", "g");
const pattern = /\${extensionResourcesFolder}/g;
str = str.replace(pattern, extensionState.getResourcesPath() ?? "");
}
// platformName
const pattern = new RegExp("\\${platformName}", "g");
const pattern = /\${platformName}/g;
str = str.replace(pattern, process.platform ?? "");

// Apply recursive replacements if enabled and string still contains any variables
if (
recursive &&
str.match(
new RegExp(
"\\${(" +
Object.keys(replacements).join("|") +
"|env:(.*?)|config:(.*?))}"
)
)
RegExp(new RegExp(
"\\${(" +
Object.keys(replacements).join("|") +
"|env:(.*?)|config:(.*?))}"
)).exec(str)
) {
str = substituteVariables(str, recursive, ctx);
}
Expand Down
2 changes: 1 addition & 1 deletion src/configurationHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class ConfigurationHelper {
* @return New value
*/
public static retrieveStringProperty(configuration: vscode.WorkspaceConfiguration, key: string, defaultValue: string): string {
const confValue = configuration.get(key);
const confValue = configuration.get<string>(key);
if (confValue) {
return `${confValue}`;
}
Expand Down
12 changes: 6 additions & 6 deletions src/definitionHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/ban-types */
import { Definition, SymbolInformation, DocumentSymbolProvider, DefinitionProvider, TextDocument, Position, CancellationToken, Location, Uri, ReferenceProvider, ReferenceContext, Range, window } from 'vscode';
import { Definition, SymbolInformation, DocumentSymbolProvider, DefinitionProvider, TextDocument, Position, Location, Uri, ReferenceProvider, Range, window } from 'vscode';
import * as vscode from 'vscode';
import { SymbolFile, Symbol } from './symbols';
import { Calc } from './calc';
Expand All @@ -20,7 +20,7 @@ export class M68kDefinitionHandler implements DefinitionProvider, ReferenceProvi
private xrefs = new Map<string, Symbol>();
private sortedVariablesNames = new Array<string>();

public async provideDocumentSymbols(document: TextDocument, token: CancellationToken): Promise<SymbolInformation[]> {
public async provideDocumentSymbols(document: TextDocument): Promise<SymbolInformation[]> {
const symbolFile: void | SymbolFile = await this.scanFile(document.uri, document);
const results = new Array<SymbolInformation>();
if (symbolFile) {
Expand Down Expand Up @@ -73,7 +73,7 @@ export class M68kDefinitionHandler implements DefinitionProvider, ReferenceProvi
return results;
}

public async provideDefinition(document: TextDocument, position: Position, token: CancellationToken): Promise<Definition> {
public async provideDefinition(document: TextDocument, position: Position): Promise<Definition> {
const rg = document.getWordRangeAtPosition(position);
if (rg) {
await this.scanFile(document.uri, document);
Expand All @@ -99,7 +99,7 @@ export class M68kDefinitionHandler implements DefinitionProvider, ReferenceProvi
throw new Error("Definition not found");
}

public async provideReferences(document: TextDocument, position: Position, context: ReferenceContext, token: CancellationToken): Promise<Location[]> {
public async provideReferences(document: TextDocument, position: Position): Promise<Location[]> {
const rg = document.getWordRangeAtPosition(position);
if (rg) {
await this.scanFile(document.uri, document);
Expand Down Expand Up @@ -140,7 +140,7 @@ export class M68kDefinitionHandler implements DefinitionProvider, ReferenceProvi
}
}
}
foundRegisters.sort();
foundRegisters.sort((a: string, b: string) => a.localeCompare(b));
return foundRegisters;
}

Expand Down Expand Up @@ -367,7 +367,7 @@ export class M68kDefinitionHandler implements DefinitionProvider, ReferenceProvi
if (v !== undefined) {
let value = v.getValue();
if ((value !== undefined) && (value.length > 0)) {
if (value.match(/[A-Za-z_]*/)) {
if (RegExp(/[A-Za-z_]*/).exec(value)) {
value = this.replaceVariablesInFormula(value);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/documentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export interface DocumentationLazy {
loadDescription(): Promise<void>;
}

export function isDocumentationLazy(el: any): el is DocumentationLazy {
export function isDocumentationLazy(el: unknown): el is DocumentationLazy {
return (el as DocumentationLazy).loadDescription !== undefined;
}

Expand Down
Loading

0 comments on commit c2c2661

Please sign in to comment.