diff --git a/app.ts b/app.ts index 3e1543c94..be01ef16c 100755 --- a/app.ts +++ b/app.ts @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import child_process from 'child_process'; -import os from 'os'; -import path from 'path'; -import process from 'process'; -import url from 'url'; +import child_process from 'node:child_process'; +import os from 'node:os'; +import path from 'node:path'; +import process from 'node:process'; +import url from 'node:url'; import * as Sentry from '@sentry/node'; import bodyParser from 'body-parser'; @@ -64,7 +64,7 @@ import {RouteAPI, ShortLinkMetaData} from './lib/handlers/route-api.js'; import {loadSiteTemplates} from './lib/handlers/site-templates.js'; import {SourceHandler} from './lib/handlers/source.js'; import {languages as allLanguages} from './lib/languages.js'; -import {logger, logToLoki, logToPapertrail, makeLogStream, suppressConsoleLog} from './lib/logger.js'; +import {logToLoki, logToPapertrail, logger, makeLogStream, suppressConsoleLog} from './lib/logger.js'; import {setupMetricsServer} from './lib/metrics-server.js'; import {ClientOptionsHandler} from './lib/options-handler.js'; import * as props from './lib/properties.js'; @@ -258,13 +258,14 @@ const isDevMode = () => process.env.NODE_ENV !== 'production'; function getFaviconFilename() { if (isDevMode()) { return 'favicon-dev.ico'; - } else if (opts.env && opts.env.includes('beta')) { - return 'favicon-beta.ico'; - } else if (opts.env && opts.env.includes('staging')) { - return 'favicon-staging.ico'; - } else { - return 'favicon.ico'; } + if (opts.env?.includes('beta')) { + return 'favicon-beta.ico'; + } + if (opts.env?.includes('staging')) { + return 'favicon-staging.ico'; + } + return 'favicon.ico'; } const propHierarchy = [ @@ -304,9 +305,8 @@ const languages = (() => { // Always keep cmake for IDE mode, just in case filteredLangs[allLanguages.cmake.id] = allLanguages.cmake; return filteredLangs; - } else { - return allLanguages; } + return allLanguages; })(); if (Object.keys(languages).length === 0) { @@ -327,7 +327,7 @@ const staticRoot = urljoin(staticUrl || urljoin(httpRoot, 'static'), '/'); function staticHeaders(res: express.Response) { if (staticMaxAgeSecs) { - res.setHeader('Cache-Control', 'public, max-age=' + staticMaxAgeSecs + ', must-revalidate'); + res.setHeader('Cache-Control', `public, max-age=${staticMaxAgeSecs}, must-revalidate`); } } @@ -425,10 +425,9 @@ async function setupStaticMiddleware(router: express.Router) { pugRequireHandler = path => { if (Object.prototype.hasOwnProperty.call(staticManifest, path)) { return urljoin(staticRoot, staticManifest[path]); - } else { - logger.error(`failed to locate static asset '${path}' in manifest`); - return ''; } + logger.error(`failed to locate static asset '${path}' in manifest`); + return ''; }; } @@ -470,7 +469,7 @@ function startListening(server: express.Express) { if (ss) { // ms (5 min default) const idleTimeout = process.env.IDLE_TIMEOUT; - const timeout = (idleTimeout === undefined ? 300 : parseInt(idleTimeout)) * 1000; + const timeout = (idleTimeout === undefined ? 300 : Number.parseInt(idleTimeout)) * 1000; if (idleTimeout) { const exit = () => { logger.info('Inactivity timeout reached, exiting.'); @@ -495,7 +494,7 @@ function startListening(server: express.Express) { }); startupGauge.set(process.uptime()); const startupDurationMs = Math.floor(process.uptime() * 1000); - if (isNaN(parseInt(_port))) { + if (Number.isNaN(Number.parseInt(_port))) { // unix socket, not a port number... logger.info(` Listening on socket: //${_port}/`); logger.info(` Startup duration: ${startupDurationMs}ms`); @@ -521,8 +520,8 @@ const awsProps = props.propsFor('aws'); async function main() { await aws.initConfig(awsProps); // Initialise express and then sentry. Sentry as early as possible to catch errors during startup. - const webServer = express(), - router = express.Router(); + const webServer = express(); + const router = express.Router(); SetupSentry(aws.getConfig('sentryDsn'), ceProps, releaseBuildNumber, gitReleaseName, defArgs); startWineInit(); @@ -570,9 +569,8 @@ async function main() { if (initialFindResults.foundClash) { // If we are forced to have no clashes, throw an error with some explanation throw new Error('Clashing compilers in the current environment found!'); - } else { - logger.info('No clashing ids found, continuing normally...'); } + logger.info('No clashing ids found, continuing normally...'); } } @@ -678,8 +676,7 @@ async function main() { .use(Sentry.Handlers.errorHandler) // eslint-disable-next-line no-unused-vars .use((err: any, req: express.Request, res: express.Response, _next: express.NextFunction) => { - const status = - err.status || err.statusCode || err.status_code || (err.output && err.output.statusCode) || 500; + const status = err.status || err.statusCode || err.status_code || err.output?.statusCode || 500; const message = err.message || 'Internal Server Error'; res.status(status); res.render('error', renderConfig({error: {code: status, message: message}})); @@ -688,7 +685,7 @@ async function main() { } }); - const sponsorConfig = loadSponsorsFromString(fs.readFileSync(configDir + '/sponsors.yaml', 'utf8')); + const sponsorConfig = loadSponsorsFromString(fs.readFileSync(`${configDir}/sponsors.yaml`, 'utf8')); loadSiteTemplates(configDir); @@ -731,7 +728,7 @@ async function main() { staticHeaders(res); contentPolicyHeader(res); - const embedded = req.query.embedded === 'true' ? true : false; + const embedded = req.query.embedded === 'true'; res.render( embedded ? 'embed' : 'index', @@ -748,7 +745,7 @@ async function main() { ); } - const embeddedHandler = function (req: express.Request, res: express.Response) { + const embeddedHandler = (req: express.Request, res: express.Response) => { staticHeaders(res); contentPolicyHeader(res); res.render( diff --git a/compiler-args-app.ts b/compiler-args-app.ts index 5f2517955..afe4e2724 100644 --- a/compiler-args-app.ts +++ b/compiler-args-app.ts @@ -109,10 +109,9 @@ class CompilerArgsApp { getParser() { if (compilerParsers[this.parserName as keyof typeof compilerParsers]) { return compilerParsers[this.parserName as keyof typeof compilerParsers]; - } else { - console.error('Unknown parser type'); - process.exit(1); } + console.error('Unknown parser type'); + process.exit(1); } async doTheParsing() { diff --git a/cypress/e2e/frontend.cy.ts b/cypress/e2e/frontend.cy.ts index d5ef04c7d..2c389e724 100644 --- a/cypress/e2e/frontend.cy.ts +++ b/cypress/e2e/frontend.cy.ts @@ -44,7 +44,7 @@ describe('Individual pane testing', () => { }); function addPaneOpenTest(paneData) { - it(paneData.name + ' pane', () => { + it(`${paneData.name} pane`, () => { cy.get(`[data-cy="new-${paneData.selector}-btn"]:visible`).click(); // Not the most consistent way, but the easiest one! cy.get('span.lm_title:visible').contains(paneData.name); diff --git a/cypress/support/utils.ts b/cypress/support/utils.ts index d72e50cc5..85eabcc76 100644 --- a/cypress/support/utils.ts +++ b/cypress/support/utils.ts @@ -2,7 +2,7 @@ import '../../static/global'; export function runFrontendTest(name: string) { it(name, () => { - return cy.window().then(win => { + return cy.window().then(win => { return win.compilerExplorerFrontendTesting.run(name); }); }); diff --git a/lib/artifact-utils.ts b/lib/artifact-utils.ts index 06585837c..761f368a0 100644 --- a/lib/artifact-utils.ts +++ b/lib/artifact-utils.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -56,10 +56,10 @@ export async function addArtifactToResult( } export async function addHeaptrackResults(result: CompilationResult, dirPath?: string): Promise { - let dirPathToUse: string = ''; + let dirPathToUse = ''; if (dirPath) { dirPathToUse = dirPath; - } else if (result.buildResult && result.buildResult.dirPath) { + } else if (result.buildResult?.dirPath) { dirPathToUse = result.buildResult.dirPath; } diff --git a/lib/assert.ts b/lib/assert.ts index 4530d73d4..dd890a81c 100644 --- a/lib/assert.ts +++ b/lib/assert.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import * as fs from 'fs'; -import path from 'path'; +import * as fs from 'node:fs'; +import path from 'node:path'; import {isString} from '../shared/common-utils.js'; import {parse} from '../shared/stacktrace.js'; @@ -33,9 +33,8 @@ const filePrefix = 'file://'; function removeFileProtocol(path: string) { if (path.startsWith(filePrefix)) { return path.slice(filePrefix.length); - } else { - return path; } + return path; } function check_path(parent: URL, directory: string) { @@ -43,9 +42,8 @@ function check_path(parent: URL, directory: string) { const relative = path.relative(parent.pathname, directory); if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) { return relative; - } else { - return false; } + return false; } function get_diagnostic() { @@ -83,16 +81,15 @@ function fail(fail_message: string, user_message: string | undefined, args: any[ } if (args.length > 0) { try { - assert_line += ', ' + JSON.stringify(args); + assert_line += `, ${JSON.stringify(args)}`; } catch (e) {} } const diagnostic = get_diagnostic(); if (diagnostic) { - throw new Error(assert_line + `, at ${diagnostic.file}:${diagnostic.line} \`${diagnostic.src}\``); - } else { - throw new Error(assert_line); + throw new Error(`${assert_line}, at ${diagnostic.file}:${diagnostic.line} \`${diagnostic.src}\``); } + throw new Error(assert_line); } // Using `unknown` instead of generic implementation due to: diff --git a/lib/aws.ts b/lib/aws.ts index 0028cb2ca..b66d1a884 100644 --- a/lib/aws.ts +++ b/lib/aws.ts @@ -100,7 +100,7 @@ async function loadAwsConfig(properties: PropertyGetter) { const ssm = new SSM({region: region, credentials: awsCredentials()}); const path = '/compiler-explorer/'; try { - const response = await ssm.getParameters({Names: [path + 'sentryDsn']}); + const response = await ssm.getParameters({Names: [`${path}sentryDsn`]}); const map: Record = {}; for (const param of unwrap(response.Parameters)) { map[unwrap(param.Name).substring(path.length)] = param.Value; diff --git a/lib/base-compiler.ts b/lib/base-compiler.ts index 0a91b5285..2fdb00333 100644 --- a/lib/base-compiler.ts +++ b/lib/base-compiler.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import os from 'os'; -import path from 'path'; +import os from 'node:os'; +import path from 'node:path'; import fs from 'fs-extra'; import * as PromClient from 'prom-client'; @@ -39,8 +39,6 @@ import { BuildResult, BuildStep, BypassCache, - bypassCompilationCache, - bypassExecutionCache, CacheKey, CmakeCacheKey, CompilationCacheKey, @@ -52,6 +50,8 @@ import { FiledataPair, GccDumpOptions, LibsAndOptions, + bypassCompilationCache, + bypassExecutionCache, } from '../types/compilation/compilation.interfaces.js'; import { CompilerOverrideOption, @@ -88,8 +88,8 @@ import {CompilerArguments} from './compiler-arguments.js'; import { BaseParser, ClangCParser, - ClangirParser, ClangParser, + ClangirParser, GCCCParser, GCCParser, ICCParser, @@ -208,7 +208,7 @@ export class BaseCompiler implements ICompiler { protected packager: Packager; protected executionType: string; protected sandboxType: string; - protected defaultRpathFlag: string = '-Wl,-rpath,'; + protected defaultRpathFlag = '-Wl,-rpath,'; private static objdumpAndParseCounter = new PromClient.Counter({ name: 'ce_objdumpandparsetime_total', help: 'Time spent on objdump and parsing of objdumps', @@ -318,12 +318,11 @@ export class BaseCompiler implements ICompiler { id: match[1], version: match[2], }; - } else { - return { - id: lib, - version: false, - }; } + return { + id: lib, + version: false, + }; }); const filterLibIds = new Set(); @@ -369,13 +368,13 @@ export class BaseCompiler implements ICompiler { env.CXX = this.compiler.exe; if (this.compiler.exe.endsWith('clang++.exe')) { - env.CC = this.compiler.exe.substring(0, this.compiler.exe.length - 6) + '.exe'; + env.CC = `${this.compiler.exe.substring(0, this.compiler.exe.length - 6)}.exe`; } else if (this.compiler.exe.endsWith('g++.exe')) { - env.CC = this.compiler.exe.substring(0, this.compiler.exe.length - 6) + 'cc.exe'; + env.CC = `${this.compiler.exe.substring(0, this.compiler.exe.length - 6)}cc.exe`; } else if (this.compiler.exe.endsWith('clang++')) { env.CC = this.compiler.exe.substring(0, this.compiler.exe.length - 2); } else if (this.compiler.exe.endsWith('g++')) { - env.CC = this.compiler.exe.substring(0, this.compiler.exe.length - 2) + 'cc'; + env.CC = `${this.compiler.exe.substring(0, this.compiler.exe.length - 2)}cc`; } } else if (this.lang.id === 'fortran') { env.FC = this.compiler.exe; @@ -558,9 +557,8 @@ export class BaseCompiler implements ICompiler { if (this.compiler.instructionSet) { return this.compiler.instructionSet; - } else { - return 'amd64'; } + return 'amd64'; } async runCompiler( @@ -632,7 +630,7 @@ export class BaseCompiler implements ICompiler { outputFilename = this.getObjdumpOutputFilename(outputFilename); if (!(await utils.fileExists(outputFilename))) { - result.asm = ''; + result.asm = ``; return result; } @@ -649,7 +647,7 @@ export class BaseCompiler implements ICompiler { if (this.externalparser) { const objResult = await this.externalparser.objdumpAndParseAssembly(result.dirPath, args, filters); if (objResult.parsingTime !== undefined) { - objResult.objdumpTime = parseInt(result.execTime) - parseInt(result.parsingTime); + objResult.objdumpTime = Number.parseInt(result.execTime) - Number.parseInt(result.parsingTime); delete objResult.execTime; } @@ -739,20 +737,20 @@ export class BaseCompiler implements ICompiler { // files outside of the tempdir created on the fly. if (this.compiler.removeEmptyGccDump) { if (gccDumpOptions.treeDump !== false) { - addOpts.push('-fdump-tree-all' + flags); + addOpts.push(`-fdump-tree-all${flags}`); } if (gccDumpOptions.rtlDump !== false) { - addOpts.push('-fdump-rtl-all' + flags); + addOpts.push(`-fdump-rtl-all${flags}`); } if (gccDumpOptions.ipaDump !== false) { - addOpts.push('-fdump-ipa-all' + flags); + addOpts.push(`-fdump-ipa-all${flags}`); } } else { // If not dumping everything, create a specific command like // -fdump-tree-fixup_cfg1-some-flags=somefilename if (gccDumpOptions.pass) { const dumpFile = this.getGccDumpFileName(outputFilename); - const dumpCmd = gccDumpOptions.pass.command_prefix + flags + `=${dumpFile}`; + const dumpCmd = `${gccDumpOptions.pass.command_prefix + flags}=${dumpFile}`; addOpts.push(dumpCmd); } } @@ -765,7 +763,7 @@ export class BaseCompiler implements ICompiler { optionsForBackend(backendOptions: Record, outputFilename: string): string[] { let addOpts: string[] = []; - if (backendOptions.produceGccDump && backendOptions.produceGccDump.opened && this.compiler.supportsGccDump) { + if (backendOptions.produceGccDump?.opened && this.compiler.supportsGccDump) { addOpts = addOpts.concat(this.getGccDumpOptions(backendOptions.produceGccDump, outputFilename)); } @@ -800,7 +798,7 @@ export class BaseCompiler implements ICompiler { foundLib.versions, (o: VersionInfo, versionId: string): boolean => { if (versionId === selectedLib.version) return true; - return !!(o.alias && o.alias.includes(selectedLib.version)); + return !!o.alias?.includes(selectedLib.version); }, ); @@ -816,11 +814,7 @@ export class BaseCompiler implements ICompiler { findAutodetectStaticLibLink(linkname: string): SelectedLibraryVersion | false { const foundLib = _.findKey(this.supportedLibraries!, lib => { - return ( - lib.versions.autodetect && - lib.versions.autodetect.staticliblink && - lib.versions.autodetect.staticliblink.includes(linkname) - ); + return lib.versions.autodetect?.staticliblink?.includes(linkname); }); if (!foundLib) return false; @@ -842,9 +836,8 @@ export class BaseCompiler implements ICompiler { if (lib) { dictionary[lib] = foundVersion; return [lib, foundVersion.dependencies]; - } else { - return false; } + return false; }); }) .flat(3), @@ -867,14 +860,14 @@ export class BaseCompiler implements ICompiler { ) { idxToInsert = idx; break; - } else if (libToInsertObj && libToInsertObj.dependencies.includes(libCompareName)) { + } + if (libToInsertObj?.dependencies.includes(libCompareName)) { idxToInsert = idx; break; - } else if (libCompareObj && libCompareObj.dependencies.includes(libToInsertName)) { - continue; + } + if (libCompareObj?.dependencies.includes(libToInsertName)) { } else if ( - libToInsertObj && - libToInsertObj.staticliblink.includes(libToInsertName) && + libToInsertObj?.staticliblink.includes(libToInsertName) && libToInsertObj.staticliblink.includes(libCompareName) ) { if ( @@ -882,13 +875,11 @@ export class BaseCompiler implements ICompiler { libToInsertObj.staticliblink.indexOf(libCompareName) ) { continue; - } else { - idxToInsert = idx; } + idxToInsert = idx; break; } else if ( - libCompareObj && - libCompareObj.staticliblink.includes(libToInsertName) && + libCompareObj?.staticliblink.includes(libToInsertName) && libCompareObj.staticliblink.includes(libCompareName) ) { if ( @@ -896,9 +887,8 @@ export class BaseCompiler implements ICompiler { libCompareObj.staticliblink.indexOf(libCompareName) ) { continue; - } else { - idxToInsert = idx; } + idxToInsert = idx; break; } } @@ -933,9 +923,8 @@ export class BaseCompiler implements ICompiler { return foundVersion.liblink.map(lib => { if (lib) { return linkFlag + lib; - } else { - return false; } + return false; }); }) .filter(Boolean) as string[]; @@ -1329,12 +1318,12 @@ export class BaseCompiler implements ICompiler { try { const [stdout, stderr] = await this.env.formatHandler.internalFormat('clangformat', 'LLVM', output); if (stderr) { - return stdout + '\n/* clang-format stderr:\n' + stderr.trim() + '\n*/'; + return `${stdout}\n/* clang-format stderr:\n${stderr.trim()}\n*/`; } return stdout; } catch (err) { logger.error('Internal formatter error', {err}); - return '/* */\n\n' + output; + return `/* */\n\n${output}`; } } @@ -1509,13 +1498,12 @@ export class BaseCompiler implements ICompiler { compileTime: compileEnd - compileStart, parseTime: parseEnd - parseStart, }; - } else { - return { - results: optPipeline, - compileTime: compileEnd - compileStart, - parseTime: parseEnd - parseStart, - }; } + return { + results: optPipeline, + compileTime: compileEnd - compileStart, + parseTime: parseEnd - parseStart, + }; } catch (e: any) { return { error: e.toString(), @@ -1643,7 +1631,7 @@ export class BaseCompiler implements ICompiler { getOutputFilename(dirPath: string, outputFilebase: string, key?: any): string { let filename; - if (key && key.backendOptions && key.backendOptions.customOutputFilename) { + if (key?.backendOptions?.customOutputFilename) { filename = key.backendOptions.customOutputFilename; } else { filename = `${outputFilebase}.s`; @@ -1651,9 +1639,8 @@ export class BaseCompiler implements ICompiler { if (dirPath) { return path.join(dirPath, filename); - } else { - return filename; } + return filename; } getExecutableFilename(dirPath: string, outputFilebase: string, key?: CacheKey | CompilationCacheKey) { @@ -1742,15 +1729,15 @@ export class BaseCompiler implements ICompiler { fromInternalGccDumpName(internalDumpName: string, selectedPasses: string[]) { if (!selectedPasses) selectedPasses = ['ipa', 'tree', 'rtl']; - const internalNameRe = new RegExp('^\\s*(' + selectedPasses.join('|') + ')-([\\w_-]+).*ON$'); + const internalNameRe = new RegExp(`^\\s*(${selectedPasses.join('|')})-([\\w_-]+).*ON$`); const match = internalDumpName.match(internalNameRe); if (match) return { filename_suffix: `${match[1][0]}.${match[2]}`, - name: match[2] + ' (' + match[1] + ')', + name: `${match[2]} (${match[1]})`, command_prefix: `-fdump-${match[1]}-${match[2]}`, }; - else return null; + return null; } async checkOutputFileAndDoPostProcess( @@ -1817,9 +1804,8 @@ export class BaseCompiler implements ICompiler { if (this.buildenvsetup) { const libraryDetails = await this.getRequiredLibraryVersions(key.libraries); return this.buildenvsetup.setup(key, dirPath, libraryDetails, binary); - } else { - return []; } + return []; } protected async writeMultipleFiles(files: FiledataPair[], dirPath: string) { @@ -2138,17 +2124,16 @@ export class BaseCompiler implements ICompiler { didExecute: true, buildResult: buildResult, }); - } else { - return { - code: -1, - didExecute: false, - buildResult, - stderr: [{text: `No execution available for ${execTriple.toString()}`}], - stdout: [], - execTime: 0, - timedOut: false, - }; } + return { + code: -1, + didExecute: false, + buildResult, + stderr: [{text: `No execution available for ${execTriple.toString()}`}], + stdout: [], + execTime: 0, + timedOut: false, + }; } const result = await this.runExecutable( @@ -2264,9 +2249,8 @@ export class BaseCompiler implements ICompiler { libsAndOptions.libraries = _.union(libsAndOptions.libraries, detectedLibs); return true; - } else { - return false; } + return false; } sanitizeCompilerOverrides(overrides: ConfiguredOverrides): ConfiguredOverrides { @@ -2343,8 +2327,7 @@ export class BaseCompiler implements ICompiler { const makeHaskellCore = backendOptions.produceHaskellCore && this.compiler.supportsHaskellCoreView; const makeHaskellStg = backendOptions.produceHaskellStg && this.compiler.supportsHaskellStgView; const makeHaskellCmm = backendOptions.produceHaskellCmm && this.compiler.supportsHaskellCmmView; - const makeGccDump = - backendOptions.produceGccDump && backendOptions.produceGccDump.opened && this.compiler.supportsGccDump; + const makeGccDump = backendOptions.produceGccDump?.opened && this.compiler.supportsGccDump; const [ asmResult, @@ -2365,7 +2348,7 @@ export class BaseCompiler implements ICompiler { inputFilename, options, backendOptions.produceIr, - backendOptions.produceCfg && backendOptions.produceCfg.ir, + backendOptions.produceCfg?.ir, filters, ) : undefined, @@ -2475,13 +2458,14 @@ export class BaseCompiler implements ICompiler { getCompilerEnvironmentVariables(compilerflags: string) { if (this.lang.id === 'c++') { return {...this.cmakeBaseEnv, CXXFLAGS: compilerflags}; - } else if (this.lang.id === 'fortran') { - return {...this.cmakeBaseEnv, FFLAGS: compilerflags}; - } else if (this.lang.id === 'cuda') { - return {...this.cmakeBaseEnv, CUDAFLAGS: compilerflags}; - } else { - return {...this.cmakeBaseEnv, CFLAGS: compilerflags}; } + if (this.lang.id === 'fortran') { + return {...this.cmakeBaseEnv, FFLAGS: compilerflags}; + } + if (this.lang.id === 'cuda') { + return {...this.cmakeBaseEnv, CUDAFLAGS: compilerflags}; + } + return {...this.cmakeBaseEnv, CFLAGS: compilerflags}; } async doBuildstep(command: string, args: string[], execParams: ExecutionOptions) { @@ -2591,13 +2575,14 @@ export class BaseCompiler implements ICompiler { getUsedEnvironmentVariableFlags(makeExecParams: ExecutionOptionsWithEnv) { if (this.lang.id === 'c++') { return utils.splitArguments(makeExecParams.env.CXXFLAGS); - } else if (this.lang.id === 'fortran') { - return utils.splitArguments(makeExecParams.env.FFLAGS); - } else if (this.lang.id === 'cuda') { - return utils.splitArguments(makeExecParams.env.CUDAFLAGS); - } else { - return utils.splitArguments(makeExecParams.env.CFLAGS); } + if (this.lang.id === 'fortran') { + return utils.splitArguments(makeExecParams.env.FFLAGS); + } + if (this.lang.id === 'cuda') { + return utils.splitArguments(makeExecParams.env.CUDAFLAGS); + } + return utils.splitArguments(makeExecParams.env.CFLAGS); } async cmake( @@ -2762,7 +2747,7 @@ export class BaseCompiler implements ICompiler { fullResult.code = 0; if (fullResult.buildsteps) { - _.each(fullResult.buildsteps, function (step) { + _.each(fullResult.buildsteps, step => { fullResult.code += step.code; }); } @@ -2931,7 +2916,7 @@ export class BaseCompiler implements ICompiler { {abandonIfStale: true}, ); - if (result.execResult && result.execResult.buildResult) { + if (result.execResult?.buildResult) { this.doTempfolderCleanup(result.execResult.buildResult); } } @@ -2948,7 +2933,7 @@ export class BaseCompiler implements ICompiler { if (backendOptions.executorRequest) { const execResult = await this.handleExecution(key, executeOptions, bypassCache); - if (execResult && execResult.buildResult) { + if (execResult?.buildResult) { this.doTempfolderCleanup(execResult.buildResult); } return execResult; @@ -3050,7 +3035,8 @@ export class BaseCompiler implements ICompiler { result.filteredCount = res.filteredCount; if (res.languageId) result.languageId = res.languageId; if (result.objdumpTime) { - const dumpAndParseTime = parseInt(result.objdumpTime) + parseInt(result.parsingTime); + const dumpAndParseTime = + Number.parseInt(result.objdumpTime) + Number.parseInt(result.parsingTime); BaseCompiler.objdumpAndParseCounter.inc(dumpAndParseTime); } } else { @@ -3062,7 +3048,7 @@ export class BaseCompiler implements ICompiler { if (this.compiler.supportsCfg && backendOptions.produceCfg && backendOptions.produceCfg.asm) { const isLlvmIr = this.compiler.instructionSet === 'llvm' || - (options && options.includes('-emit-llvm')) || + options?.includes('-emit-llvm') || this.llvmIr.isLlvmIr(result.asm); result.cfg = cfg.generateStructure(this.compiler, result.asm, isLlvmIr); } @@ -3113,7 +3099,7 @@ export class BaseCompiler implements ICompiler { } async processAsm(result, filters: ParseFiltersAndOutputOptions, options: string[]) { - if ((options && options.includes('-emit-llvm')) || this.llvmIr.isLlvmIr(result.asm)) { + if (options?.includes('-emit-llvm') || this.llvmIr.isLlvmIr(result.asm)) { return await this.llvmIr.processFromFilters(result.asm, filters); } @@ -3177,7 +3163,7 @@ export class BaseCompiler implements ICompiler { const versionMatch = versionRegex.exec(version); if (versionMatch) { - const versionNum = parseFloat(versionMatch[1]); + const versionNum = Number.parseFloat(versionMatch[1]); return version.toLowerCase().includes('clang') && versionNum >= 3.3; } @@ -3355,18 +3341,15 @@ but nothing was dumped. Possible causes are: return result; } if (result.asmSize >= maxSize) { - result.asm = - ' ${maxSize} bytes)>`; + result.asm = ` ${maxSize} bytes)>`; return result; } if (postProcess.length > 0) { return await this.execPostProcess(result, postProcess, outputFilename, maxSize); - } else { - const contents = await fs.readFile(outputFilename); - result.asm = contents.toString(); - return result; } + const contents = await fs.readFile(outputFilename); + result.asm = contents.toString(); + return result; })(); return Promise.all([asmPromise, optPromise, stackUsagePromise]); } @@ -3407,16 +3390,21 @@ but nothing was dumped. Possible causes are: const exeFilename = path.basename(exe); if (exeFilename.includes('icc')) { return ICCParser; - } else if (exe.includes('clangir')) { + } + if (exe.includes('clangir')) { return ClangirParser; - } else if (exeFilename.includes('clang++') || exeFilename.includes('icpx')) { + } + if (exeFilename.includes('clang++') || exeFilename.includes('icpx')) { // check this first as "clang++" matches "g++" return ClangParser; - } else if (exeFilename.includes('clang') || exeFilename.includes('icx')) { + } + if (exeFilename.includes('clang') || exeFilename.includes('icx')) { return ClangCParser; - } else if (exeFilename.includes('gcc')) { + } + if (exeFilename.includes('gcc')) { return GCCCParser; - } else if (exeFilename.includes('g++')) { + } + if (exeFilename.includes('g++')) { return GCCParser; } //there is a lot of code around that makes this assumption. @@ -3462,9 +3450,8 @@ but nothing was dumped. Possible causes are: value: target, }; }); - } else { - return []; } + return []; } async getPossibleStdversAsOverrideValues(): Promise { @@ -3542,7 +3529,7 @@ but nothing was dumped. Possible causes are: name: CompilerOverrideType.toolchain, display_title: 'Toolchain', description: c_default_toolchain_description, - flags: [flag + ''], + flags: [`${flag}`], values: possibleToolchains, }); } @@ -3649,15 +3636,14 @@ but nothing was dumped. Possible causes are: delete this.compiler.cachedPossibleArguments; } return this; - } else { - const initResult = await this.getArgumentParserClass().parse(this); - - await this.populatePossibleOverrides(); - await this.populatePossibleRuntimeTools(); - - logger.info(`${compiler} ${version} is ready`); - return initResult; } + const initResult = await this.getArgumentParserClass().parse(this); + + await this.populatePossibleOverrides(); + await this.populatePossibleRuntimeTools(); + + logger.info(`${compiler} ${version} is ready`); + return initResult; } getModificationTime(): number | undefined { diff --git a/lib/binaries/binary-utils.ts b/lib/binaries/binary-utils.ts index 9c34b0aee..a386c1232 100644 --- a/lib/binaries/binary-utils.ts +++ b/lib/binaries/binary-utils.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import os from 'os'; +import os from 'node:os'; import {InstructionSet} from '../../types/instructionsets.js'; import {executeDirect} from '../exec.js'; @@ -85,8 +85,8 @@ export class BinaryInfoLinux { } static removeComments(value: string): string { - let filtered: string = ''; - let inComment: boolean = false; + let filtered = ''; + let inComment = false; for (const c of value) { if (!inComment && c === '(') { inComment = true; @@ -106,16 +106,17 @@ export class BinaryInfoLinux { if (isElf) { return { os: OSType.linux, - instructionSet: this.getInstructionSetForArchText(csv[1]), + instructionSet: BinaryInfoLinux.getInstructionSetForArchText(csv[1]), }; - } else if (isPE) { - const filteredLine = this.removeComments(csv[0]); + } + if (isPE) { + const filteredLine = BinaryInfoLinux.removeComments(csv[0]); const lastWordPos = filteredLine.lastIndexOf(' '); const lastWord = filteredLine.substring(lastWordPos + 1); return { os: OSType.windows, - instructionSet: this.getInstructionSetForArchText(lastWord), + instructionSet: BinaryInfoLinux.getInstructionSetForArchText(lastWord), }; } @@ -128,10 +129,9 @@ export class BinaryInfoLinux { os: OSType.windows, instructionSet: 'amd64', }; - } else { - const info = await executeDirect('/usr/bin/file', ['-b', filepath], {}); - if (info.code === 0) return this.parseFileInfo(info.stdout); } + const info = await executeDirect('/usr/bin/file', ['-b', filepath], {}); + if (info.code === 0) return BinaryInfoLinux.parseFileInfo(info.stdout); return undefined; } } diff --git a/lib/binaries/win-utils.ts b/lib/binaries/win-utils.ts index 69600716a..d65925a1c 100644 --- a/lib/binaries/win-utils.ts +++ b/lib/binaries/win-utils.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import * as fs from 'fs-extra'; @@ -73,11 +73,11 @@ export class WinUtils { if (this.skippable.includes(dll_name.toLowerCase())) continue; if (this.alreadyDone.includes(dll_name)) continue; - logger.debug('looking for ' + dll_name); + logger.debug(`looking for ${dll_name}`); const dll_path = await this.find_first_file_in_dirs(paths, dll_name); if (dll_path) { - logger.debug('found at ' + dll_path); + logger.debug(`found at ${dll_path}`); dlls_used.push(dll_path); this.alreadyDone.push(dll_name); diff --git a/lib/buildenvsetup/base.ts b/lib/buildenvsetup/base.ts index 0667ea272..8173229df 100644 --- a/lib/buildenvsetup/base.ts +++ b/lib/buildenvsetup/base.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import _ from 'underscore'; @@ -78,9 +78,11 @@ export class BuildEnvSetupBase { let searchFor = arch as string; if (this.compiler.exe.includes('icpx')) { return arch === 'x86' || arch === 'x86_64'; - } else if (this.compiler.exe.includes('circle')) { + } + if (this.compiler.exe.includes('circle')) { return arch === 'x86' || arch === 'x86_64'; - } else if (this.compiler.group === 'icc') { + } + if (this.compiler.group === 'icc') { result = await execCompilerCached(this.compiler.exe, ['--help']); if (arch === 'x86') { searchFor = '-m32'; @@ -90,9 +92,8 @@ export class BuildEnvSetupBase { } else if (this.compilerTypeOrGCC === 'gcc') { if (this.compiler.exe.includes('/icpx')) { return arch === 'x86' || arch === 'x86_64'; - } else { - result = await execCompilerCached(this.compiler.exe, ['--target-help']); } + result = await execCompilerCached(this.compiler.exe, ['--target-help']); } else if (this.compilerTypeOrGCC === 'clang') { const binpath = path.dirname(this.compiler.exe); const llc = path.join(binpath, 'llc'); @@ -142,13 +143,11 @@ export class BuildEnvSetupBase { if (target && arch) { if (arch.length < target.length) { return arch; - } else { - return target; } - } else { - if (target) return target; - if (arch) return arch; + return target; } + if (target) return target; + if (arch) return arch; return false; } @@ -157,17 +156,16 @@ export class BuildEnvSetupBase { const match = this.compiler.options.match(/-stdlib=(\S*)/i); if (match) { return match[1]; - } else { - const stdlibOption: string | undefined = _.find(key.options, option => { - return option.startsWith('-stdlib='); - }); - - if (stdlibOption) { - return stdlibOption.substring(8); - } - - return this.defaultLibCxx; } + const stdlibOption: string | undefined = _.find(key.options, option => { + return option.startsWith('-stdlib='); + }); + + if (stdlibOption) { + return stdlibOption.substring(8); + } + + return this.defaultLibCxx; } getTarget(key: CacheKey): string { @@ -176,14 +174,13 @@ export class BuildEnvSetupBase { if (key.options.includes('-m32')) { return 'x86'; - } else { - const target: string | undefined = _.find(key.options, option => { - return option.startsWith('-target=') || option.startsWith('--target='); - }); + } + const target: string | undefined = _.find(key.options, option => { + return option.startsWith('-target=') || option.startsWith('--target='); + }); - if (target) { - return target.substring(target.indexOf('=') + 1); - } + if (target) { + return target.substring(target.indexOf('=') + 1); } return 'x86_64'; diff --git a/lib/buildenvsetup/ceconan-circle.ts b/lib/buildenvsetup/ceconan-circle.ts index 22dabf18e..d3422f53d 100644 --- a/lib/buildenvsetup/ceconan-circle.ts +++ b/lib/buildenvsetup/ceconan-circle.ts @@ -45,7 +45,7 @@ export class BuildEnvSetupCeConanCircleDirect extends BuildEnvSetupCeConanDirect override async getConanBuildProperties(key: CacheKey): Promise { const props = await super.getConanBuildProperties(key); - props['compiler'] = this.linkedCompilerType; + props.compiler = this.linkedCompilerType; props['compiler.version'] = this.linkedCompilerId; return props; } diff --git a/lib/buildenvsetup/ceconan-rust.ts b/lib/buildenvsetup/ceconan-rust.ts index 0bb93b1c3..eeaea8d59 100644 --- a/lib/buildenvsetup/ceconan-rust.ts +++ b/lib/buildenvsetup/ceconan-rust.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import _ from 'underscore'; @@ -61,16 +61,14 @@ export class BuildEnvSetupCeConanRustDirect extends BuildEnvSetupCeConanDirect { } getArchFromTriple(triple: string) { - if (triple && triple.split) { + if (triple?.split) { const arr = triple.split('-'); - if (arr && arr[0]) { + if (arr?.[0]) { return arr[0]; - } else { - return triple; } - } else { - return ''; + return triple; } + return ''; } override getTarget(key: CacheKey) { @@ -84,12 +82,11 @@ export class BuildEnvSetupCeConanRustDirect extends BuildEnvSetupCeConanDirect { if (target) { const triple = target.substring(target.indexOf('=') + 1); return this.getArchFromTriple(triple); - } else { - const idx = key.options.indexOf('--target'); - if (idx !== -1) { - const triple = key.options[idx + 1]; - return this.getArchFromTriple(triple); - } + } + const idx = key.options.indexOf('--target'); + if (idx !== -1) { + const triple = key.options[idx + 1]; + return this.getArchFromTriple(triple); } return 'x86_64'; diff --git a/lib/buildenvsetup/ceconan.ts b/lib/buildenvsetup/ceconan.ts index 222fc2b1d..05b8c76fa 100644 --- a/lib/buildenvsetup/ceconan.ts +++ b/lib/buildenvsetup/ceconan.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; -import zlib from 'zlib'; +import path from 'node:path'; +import zlib from 'node:zlib'; import fs, {mkdirp} from 'fs-extra'; import request from 'request'; @@ -126,9 +126,8 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase { if (this.extractAllToRoot) { const filename = path.basename(zippedPath); return path.join(downloadPath, filename); - } else { - return path.join(downloadPath, libId, zippedPath); } + return path.join(downloadPath, libId, zippedPath); } async downloadAndExtractPackage( @@ -245,11 +244,11 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase { return _.all(buildProperties, (val, key) => { if ((key === 'compiler' || key === 'compiler.version') && elem.settings[key] === 'cshared') { return true; - } else if (key === 'compiler.libcxx' && elem.settings['compiler'] === 'cshared') { - return true; - } else { - return val === elem.settings[key]; } + if (key === 'compiler.libcxx' && elem.settings.compiler === 'cshared') { + return true; + } + return val === elem.settings[key]; }); }); } diff --git a/lib/cache/from-config.ts b/lib/cache/from-config.ts index 685471fdf..498c74870 100644 --- a/lib/cache/from-config.ts +++ b/lib/cache/from-config.ts @@ -32,8 +32,8 @@ import {OnDiskCache} from './on-disk.js'; import {S3Cache} from './s3.js'; function paramInt(config: string, param: string): number { - const result = parseInt(param); - if (isNaN(result)) throw new Error(`Bad params: ${config}`); + const result = Number.parseInt(param); + if (Number.isNaN(result)) throw new Error(`Bad params: ${config}`); return result; } diff --git a/lib/cache/on-disk.ts b/lib/cache/on-disk.ts index 12cc9929c..3d6e9b5a4 100644 --- a/lib/cache/on-disk.ts +++ b/lib/cache/on-disk.ts @@ -23,8 +23,8 @@ // POSSIBILITY OF SUCH DAMAGE. import {Buffer} from 'buffer'; -import crypto from 'crypto'; -import path from 'path'; +import crypto from 'node:crypto'; +import path from 'node:path'; import fs from 'fs-extra'; import {LRUCache} from 'lru-cache'; @@ -121,7 +121,7 @@ export class OnDiskCache extends BaseCache { size: value.length, }; // Write to a temp file and then rename - const tempFile = info.path + `.tmp.${crypto.randomUUID()}`; + const tempFile = `${info.path}.tmp.${crypto.randomUUID()}`; await fs.writeFile(tempFile, value); await fs.rename(tempFile, info.path); this.cache.set(key, info); diff --git a/lib/cfg/cfg-parsers/base.ts b/lib/cfg/cfg-parsers/base.ts index dcaba3803..49cb3f8b8 100644 --- a/lib/cfg/cfg-parsers/base.ts +++ b/lib/cfg/cfg-parsers/base.ts @@ -74,7 +74,7 @@ export class BaseCFGParser { public filterData(assembly: AssemblyLine[]) { const jmpLabelRegex = /\.L\d+:/; const isCode = (x: AssemblyLine) => - x && x.text && (x.source !== null || jmpLabelRegex.test(x.text) || this.isFunctionName(x)); + x?.text && (x.source !== null || jmpLabelRegex.test(x.text) || this.isFunctionName(x)); return this.filterTextSection(assembly).map(_.clone).filter(isCode); } @@ -108,9 +108,12 @@ export class BaseCFGParser { let rangeBb: BBRange = {nameId: functionName, start: first, end: 0, actionPos: []}; const result: BBRange[] = []; - const newRangeWith = function (oldRange: BBRange, nameId: string, start: number) { - return {nameId: nameId, start: start, actionPos: [], end: oldRange.end}; - }; + const newRangeWith = (oldRange: BBRange, nameId: string, start: number) => ({ + nameId: nameId, + start: start, + actionPos: [], + end: oldRange.end, + }); while (first < last) { const inst = asmArr[first].text; @@ -176,7 +179,7 @@ export class BaseCFGParser { } protected extractNodeName(inst: string) { - return inst.match(/\.L\d+/) + ':'; + return `${inst.match(/\.L\d+/)}:`; } protected splitToCanonicalBasicBlock(basicBlock: BBRange): CanonicalBB[] { @@ -194,31 +197,30 @@ export class BaseCFGParser { end: basicBlock.end, }, ]; - else if (actPosSz === 1) + if (actPosSz === 1) return [ {nameId: basicBlock.nameId, start: basicBlock.start, end: actionPos[0] + 1}, - {nameId: basicBlock.nameId + '@' + (actionPos[0] + 1), start: actionPos[0] + 1, end: basicBlock.end}, + {nameId: `${basicBlock.nameId}@${actionPos[0] + 1}`, start: actionPos[0] + 1, end: basicBlock.end}, ]; - else { - let first = 0; - const last = actPosSz; - const blockName = basicBlock.nameId; - let tmp: CanonicalBB = {nameId: blockName, start: basicBlock.start, end: actionPos[first] + 1}; - const result: CanonicalBB[] = []; - result.push(_.clone(tmp)); - while (first !== last - 1) { - tmp.nameId = blockName + '@' + (actionPos[first] + 1); - tmp.start = actionPos[first] + 1; - ++first; - tmp.end = actionPos[first] + 1; - result.push(_.clone(tmp)); - } - tmp = {nameId: blockName + '@' + (actionPos[first] + 1), start: actionPos[first] + 1, end: basicBlock.end}; + let first = 0; + const last = actPosSz; + const blockName = basicBlock.nameId; + let tmp: CanonicalBB = {nameId: blockName, start: basicBlock.start, end: actionPos[first] + 1}; + const result: CanonicalBB[] = []; + result.push(_.clone(tmp)); + while (first !== last - 1) { + tmp.nameId = `${blockName}@${actionPos[first] + 1}`; + tmp.start = actionPos[first] + 1; + ++first; + tmp.end = actionPos[first] + 1; result.push(_.clone(tmp)); - - return result; } + + tmp = {nameId: `${blockName}@${actionPos[first] + 1}`, start: actionPos[first] + 1, end: basicBlock.end}; + result.push(_.clone(tmp)); + + return result; } protected concatInstructions(asmArr: AssemblyLine[], first: number, last: number) { @@ -250,7 +252,7 @@ export class BaseCFGParser { return asm ? this.isBasicBlockEnd(asm.text, '') : false; }; - const generateName = function (name: string, suffix: number) { + const generateName = (name: string, suffix: number) => { const pos = name.indexOf('@'); if (pos === -1) return `${name}@${suffix}`; diff --git a/lib/cfg/cfg-parsers/clang.ts b/lib/cfg/cfg-parsers/clang.ts index 036755d40..86efbe716 100644 --- a/lib/cfg/cfg-parsers/clang.ts +++ b/lib/cfg/cfg-parsers/clang.ts @@ -36,7 +36,7 @@ export class ClangCFGParser extends BaseCFGParser { override filterData(assembly: ResultLine[]) { const jmpLabelRegex = /\.LBB\d+_\d+:/; const isCode = (x: ResultLine) => - x && x.text && (x.source !== null || jmpLabelRegex.test(x.text) || this.isFunctionName(x)); + x?.text && (x.source !== null || jmpLabelRegex.test(x.text) || this.isFunctionName(x)); const removeComments = (x: ResultLine) => { const pos_x86 = x.text.indexOf('# '); @@ -50,6 +50,6 @@ export class ClangCFGParser extends BaseCFGParser { } override extractNodeName(inst: string) { - return inst.match(/\.LBB\d+_\d+/) + ':'; + return `${inst.match(/\.LBB\d+_\d+/)}:`; } } diff --git a/lib/cfg/cfg-parsers/gcc.ts b/lib/cfg/cfg-parsers/gcc.ts index 089736b1c..00eaef2e9 100644 --- a/lib/cfg/cfg-parsers/gcc.ts +++ b/lib/cfg/cfg-parsers/gcc.ts @@ -36,11 +36,11 @@ export class GccCFGParser extends BaseCFGParser { override filterData(assembly: ResultLine[]) { const jmpLabelRegex = /\.L\d+:/; const isCode = (x: AssemblyLine) => - x && x.text && (x.source !== null || jmpLabelRegex.test(x.text) || this.isFunctionName(x)); + x?.text && (x.source !== null || jmpLabelRegex.test(x.text) || this.isFunctionName(x)); return this.filterTextSection(assembly).map(_.clone).filter(isCode); } override extractNodeName(inst: string) { - return inst.match(/\.L\d+/) + ':'; + return `${inst.match(/\.L\d+/)}:`; } } diff --git a/lib/cfg/cfg-parsers/llvm-ir.ts b/lib/cfg/cfg-parsers/llvm-ir.ts index 644beac29..17aee7176 100644 --- a/lib/cfg/cfg-parsers/llvm-ir.ts +++ b/lib/cfg/cfg-parsers/llvm-ir.ts @@ -83,8 +83,8 @@ export class LlvmIrCfgParser extends BaseCFGParser { const result: BBRange[] = []; let i = fn.start + 1; let bbStart = i; - let currentName: string = ''; - let namePrefix: string = fnName + '\n\n'; + let currentName = ''; + let namePrefix = `${fnName}\n\n`; while (i < fn.end) { const match = code[i].text.match(this.labelRe); if (match) { @@ -159,7 +159,8 @@ export class LlvmIrCfgParser extends BaseCFGParser { lastInst--; } return this.concatInstructions(asmArr, lastInst, end + 1); - } else if ( + } + if ( lastInst >= 1 && asmArr[lastInst].text.includes('unwind label') && asmArr[lastInst - 1].text.trim().includes('invoke ') @@ -168,7 +169,8 @@ export class LlvmIrCfgParser extends BaseCFGParser { // invoke void @__cxa_throw(ptr nonnull %exception, ptr nonnull @typeinfo for int, ptr null) #3 // to label %unreachable unwind label %lpad return this.concatInstructions(asmArr, lastInst - 1, lastInst + 1); - } else if ( + } + if ( lastInst >= 1 && asmArr[lastInst - 1].text.includes('landingpad') && asmArr[lastInst].text.includes('catch') @@ -177,7 +179,8 @@ export class LlvmIrCfgParser extends BaseCFGParser { // %0 = landingpad { ptr, i32 } // catch ptr null return this.concatInstructions(asmArr, lastInst - 1, lastInst + 1); - } else if ( + } + if ( lastInst >= 1 && asmArr[lastInst - 1].text.includes('callbr') && asmArr[lastInst].text.trim().startsWith('to label') @@ -186,9 +189,8 @@ export class LlvmIrCfgParser extends BaseCFGParser { // %2 = callbr i32 asm "mov ${1:l}, $0", "=r,!i,~{dirflag},~{fpsr},~{flags}"() #2 // to label %asm.fallthrough1 [label %err.split2] return this.concatInstructions(asmArr, lastInst - 1, lastInst + 1); - } else { - return asmArr[lastInst].text; } + return asmArr[lastInst].text; })(); let terminator; if (terminatingInstruction.includes('invoke ')) { diff --git a/lib/cfg/cfg-parsers/oat.ts b/lib/cfg/cfg-parsers/oat.ts index 3bb6485ee..9ab22f5ec 100644 --- a/lib/cfg/cfg-parsers/oat.ts +++ b/lib/cfg/cfg-parsers/oat.ts @@ -28,7 +28,7 @@ import {EdgeColor} from '../../../types/compilation/cfg.interfaces.js'; import {logger} from '../../logger.js'; import {BaseInstructionSetInfo, InstructionType} from '../instruction-sets/base.js'; -import {AssemblyLine, BaseCFGParser, BBRange, CanonicalBB, Edge, Range} from './base.js'; +import {AssemblyLine, BBRange, BaseCFGParser, CanonicalBB, Edge, Range} from './base.js'; // This currently only covers the default arm64 output. To support dex2oat's // other ISAs, we just need to make sure the correct isJmpInstruction() is being @@ -124,7 +124,7 @@ export class OatCFGParser extends BaseCFGParser { // '0x00004168' -> '0x4168' shortenHex(pc: string) { const match = pc.match(this.hexRegex); - if (match) return '0x' + match[1]; + if (match) return `0x${match[1]}`; return pc; } @@ -153,14 +153,12 @@ export class OatCFGParser extends BaseCFGParser { actionPos: [], }; - const newRangeWith = function (oldRange: BBRange, nameId: string, start: number) { - return { - nameId: nameId, - start: start, - actionPos: [], - end: oldRange.end, - }; - }; + const newRangeWith = (oldRange: BBRange, nameId: string, start: number) => ({ + nameId: nameId, + start: start, + actionPos: [], + end: oldRange.end, + }); const result: BBRange[] = []; while (first < last) { @@ -212,7 +210,7 @@ export class OatCFGParser extends BaseCFGParser { end: basicBlock.end, }, ]; - else if (actPosSz === 1) + if (actPosSz === 1) return [ {nameId: basicBlock.nameId, start: basicBlock.start, end: actionPos[0] + 1}, { @@ -221,30 +219,29 @@ export class OatCFGParser extends BaseCFGParser { end: basicBlock.end, }, ]; - else { - let first = 0; - const last = actPosSz; - const blockName = basicBlock.nameId; - let tmp: CanonicalBB = {nameId: blockName, start: basicBlock.start, end: actionPos[first] + 1}; - const result: CanonicalBB[] = []; - result.push(_.clone(tmp)); - while (first !== last - 1) { - tmp.nameId = this.extractNodeName(this.code[actionPos[first] + 1].text); - tmp.start = actionPos[first] + 1; - ++first; - tmp.end = actionPos[first] + 1; - result.push(_.clone(tmp)); - } - tmp = { - nameId: this.extractNodeName(this.code[actionPos[first] + 1].text), - start: actionPos[first] + 1, - end: basicBlock.end, - }; + let first = 0; + const last = actPosSz; + const blockName = basicBlock.nameId; + let tmp: CanonicalBB = {nameId: blockName, start: basicBlock.start, end: actionPos[first] + 1}; + const result: CanonicalBB[] = []; + result.push(_.clone(tmp)); + while (first !== last - 1) { + tmp.nameId = this.extractNodeName(this.code[actionPos[first] + 1].text); + tmp.start = actionPos[first] + 1; + ++first; + tmp.end = actionPos[first] + 1; result.push(_.clone(tmp)); - - return result; } + + tmp = { + nameId: this.extractNodeName(this.code[actionPos[first] + 1].text), + start: actionPos[first] + 1, + end: basicBlock.end, + }; + result.push(_.clone(tmp)); + + return result; } override makeEdges(asmArr: AssemblyLine[], arrOfCanonicalBasicBlock: CanonicalBB[]) { diff --git a/lib/cfg/cfg.ts b/lib/cfg/cfg.ts index fcdd4a64e..c1ea7033e 100644 --- a/lib/cfg/cfg.ts +++ b/lib/cfg/cfg.ts @@ -24,7 +24,7 @@ import type {CompilerInfo} from '../../types/compiler.interfaces.js'; -import {AssemblyLine, Edge, getParserByKey, Node} from './cfg-parsers/index.js'; +import {AssemblyLine, Edge, Node, getParserByKey} from './cfg-parsers/index.js'; import {OatCFGParser} from './cfg-parsers/oat.js'; import {getInstructionSetByKey} from './instruction-sets/index.js'; @@ -60,10 +60,9 @@ export function generateStructure(compilerInfo: CompilerInfo, asmArr: AssemblyLi // dex2oat is a special case because it can output different instruction // sets. Create an OAT parser instead of searching by ISA. - const parser = - compilerGroup && compilerGroup.includes('dex2oat') - ? new OatCFGParser(instructionSet) - : new (getParserByKey(compilerGroup))(instructionSet); + const parser = compilerGroup?.includes('dex2oat') + ? new OatCFGParser(instructionSet) + : new (getParserByKey(compilerGroup))(instructionSet); const code = parser.filterData(asmArr); const functions = parser.splitToFunctions(code); diff --git a/lib/cfg/instruction-sets/arm.ts b/lib/cfg/instruction-sets/arm.ts index 438d4a47b..9752ea635 100644 --- a/lib/cfg/instruction-sets/arm.ts +++ b/lib/cfg/instruction-sets/arm.ts @@ -58,29 +58,21 @@ export class ArmInstructionSetInfo extends BaseInstructionSetInfo { // blxcc reg // movcc pc, reg static conditionalJumps = new RegExp( - '\\b(?:' + - [ - `b\\.?${ArmInstructionSetInfo.conditions}(?:\\.w)?`, - `bx${ArmInstructionSetInfo.conditions}`, - `bxj${ArmInstructionSetInfo.conditions}`, - `cbz`, - `cbnz`, - `tbz`, - `tbnz`, - ] - .map(re => `(?:${re})`) - .join('|') + - ')\\b', - ); - static unconditionalJumps = new RegExp( - '\\b(?:' + [`b(?:\\.w)?`, `bx`, `bxj`].map(re => `(?:${re})`).join('|') + ')\\b', + `\\b(?:${[ + `b\\.?${ArmInstructionSetInfo.conditions}(?:\\.w)?`, + `bx${ArmInstructionSetInfo.conditions}`, + `bxj${ArmInstructionSetInfo.conditions}`, + 'cbz', + 'cbnz', + 'tbz', + 'tbnz', + ] + .map(re => `(?:${re})`) + .join('|')})\\b`, ); + static unconditionalJumps = new RegExp(`\\b(?:${['b(?:\\.w)?', 'bx', 'bxj'].map(re => `(?:${re})`).join('|')})\\b`); static returnInstruction = new RegExp( - '(?:' + - [`bx`, `ret`].map(re => `(?:${re})`).join('|') + - ')\\b.*' + - `|pop\\s*\\{(?:r(?:\\d{2,}|[4-9]),\\s*)*pc\\}.*` + - `|mov\\s*pc\\s*,.*`, + `(?:${['bx', 'ret'].map(re => `(?:${re})`).join('|')})\\b.*|pop\\s*\\{(?:r(?:\\d{2,}|[4-9]),\\s*)*pc\\}.*|mov\\s*pc\\s*,.*`, ); static override get key(): InstructionSet[] { @@ -97,11 +89,10 @@ export class ArmInstructionSetInfo extends BaseInstructionSetInfo { override getInstructionType(instruction: string) { const opcode = instruction.trim().split(' ')[0].toLowerCase(); if (ArmInstructionSetInfo.conditionalJumps.test(opcode)) return InstructionType.conditionalJmpInst; - else if (ArmInstructionSetInfo.unconditionalJumps.test(opcode)) return InstructionType.jmp; - else if (ArmInstructionSetInfo.returnInstruction.test(instruction.trim().toLocaleLowerCase())) { + if (ArmInstructionSetInfo.unconditionalJumps.test(opcode)) return InstructionType.jmp; + if (ArmInstructionSetInfo.returnInstruction.test(instruction.trim().toLocaleLowerCase())) { return InstructionType.retInst; - } else { - return InstructionType.notRetInst; } + return InstructionType.notRetInst; } } diff --git a/lib/cfg/instruction-sets/base.ts b/lib/cfg/instruction-sets/base.ts index 1c8905491..0f26a5c53 100644 --- a/lib/cfg/instruction-sets/base.ts +++ b/lib/cfg/instruction-sets/base.ts @@ -25,10 +25,10 @@ import {InstructionSet} from '../../../types/instructionsets.js'; export enum InstructionType { - jmp, - conditionalJmpInst, - notRetInst, - retInst, + jmp = 0, + conditionalJmpInst = 1, + notRetInst = 2, + retInst = 3, } export class BaseInstructionSetInfo { @@ -46,11 +46,10 @@ export class BaseInstructionSetInfo { getInstructionType(inst: string) { if (inst.includes('jmp') || inst.includes(' b ')) return InstructionType.jmp; - else if (this.isJmpInstruction(inst)) return InstructionType.conditionalJmpInst; - else if (inst.includes(' ret')) { + if (this.isJmpInstruction(inst)) return InstructionType.conditionalJmpInst; + if (inst.includes(' ret')) { return InstructionType.retInst; - } else { - return InstructionType.notRetInst; } + return InstructionType.notRetInst; } } diff --git a/lib/clientstate-normalizer.ts b/lib/clientstate-normalizer.ts index fbfab23a0..2f22f74f6 100644 --- a/lib/clientstate-normalizer.ts +++ b/lib/clientstate-normalizer.ts @@ -377,9 +377,8 @@ class GoldenLayoutComponents { filename: session.filename, }, }; - } else { - return editor; } + return editor; } createTreeComponent(tree: ClientStateTree, customTreeId?: number): GoldenLayoutComponentStruct { @@ -884,12 +883,11 @@ export class ClientStateGoldenifier extends GoldenLayoutComponents { createSourceContentArray(state: ClientState, leftSession: number, rightSession: number): BasicGoldenLayoutStruct[] { if (leftSession === rightSession) { return [this.createPresentationModeComponents(state.sessions[leftSession], 1, 100)]; - } else { - return [ - this.createPresentationModeComponents(state.sessions[leftSession], 1), - this.createPresentationModeComponents(state.sessions[rightSession], 2), - ]; } + return [ + this.createPresentationModeComponents(state.sessions[leftSession], 1), + this.createPresentationModeComponents(state.sessions[rightSession], 2), + ]; } getPresentationModeEmptyLayout() { diff --git a/lib/clientstate.ts b/lib/clientstate.ts index e6f8217c0..22944ca87 100644 --- a/lib/clientstate.ts +++ b/lib/clientstate.ts @@ -121,7 +121,7 @@ export class ClientStateCompiler { export class ClientStateExecutor { compilerVisible = false; compilerOutputVisible = false; - arguments: string = ''; + arguments = ''; argumentsVisible = false; stdin = ''; stdinVisible = false; diff --git a/lib/compilation-env.ts b/lib/compilation-env.ts index c885b7e1b..5648ebf22 100644 --- a/lib/compilation-env.ts +++ b/lib/compilation-env.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import child_process from 'child_process'; +import child_process from 'node:child_process'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -39,7 +39,7 @@ import {FormattingHandler} from './handlers/formatting.js'; import {logger} from './logger.js'; import type {PropertyGetter} from './properties.interfaces.js'; import {CompilerProps, PropFunc} from './properties.js'; -import {createStatsNoter, IStatsNoter} from './stats.js'; +import {IStatsNoter, createStatsNoter} from './stats.js'; export class CompilationEnvironment { ceProps: PropertyGetter; @@ -116,9 +116,9 @@ export class CompilationEnvironment { getEnv(needsMulti: boolean) { const env = {...this.baseEnv}; if (needsMulti && this.multiarch) { - env.LIBRARY_PATH = '/usr/lib/' + this.multiarch; - env.C_INCLUDE_PATH = '/usr/include/' + this.multiarch; - env.CPLUS_INCLUDE_PATH = '/usr/include/' + this.multiarch; + env.LIBRARY_PATH = `/usr/lib/${this.multiarch}`; + env.C_INCLUDE_PATH = `/usr/include/${this.multiarch}`; + env.CPLUS_INCLUDE_PATH = `/usr/include/${this.multiarch}`; } return env; } @@ -164,13 +164,13 @@ export class CompilationEnvironment { } getExecutableHash(object: CacheableValue): string { - return BaseCache.hash(object) + '_exec'; + return `${BaseCache.hash(object)}_exec`; } async executableGet(key: string, destinationFolder: string): Promise { const result = await this.executableCache.get(key); if (!result.hit) return null; - const filepath = destinationFolder + '/' + key; + const filepath = `${destinationFolder}/${key}`; await fs.writeFile(filepath, unwrap(result.data)); return filepath; } diff --git a/lib/compilation-queue.ts b/lib/compilation-queue.ts index b3b6ee4d4..7be20fdc7 100644 --- a/lib/compilation-queue.ts +++ b/lib/compilation-queue.ts @@ -23,7 +23,7 @@ // POSSIBILITY OF SUCH DAMAGE. // eslint-disable-next-line n/no-unsupported-features/node-builtins -import {executionAsyncId} from 'async_hooks'; +import {executionAsyncId} from 'node:async_hooks'; import {default as Queue} from 'p-queue'; import PromClient from 'prom-client'; @@ -90,7 +90,7 @@ export class CompilationQueue { () => { const dequeuedAt = Date.now(); queueDequeued.inc(); - if (options && options.abandonIfStale && dequeuedAt > enqueuedAt + this._staleAfterMs) { + if (options?.abandonIfStale && dequeuedAt > enqueuedAt + this._staleAfterMs) { queueCompleted.inc(); queueStale.inc(); const queueTimeSecs = (dequeuedAt - enqueuedAt) / 1000; diff --git a/lib/compiler-arguments.ts b/lib/compiler-arguments.ts index d8fb99c85..24d5bd8b3 100644 --- a/lib/compiler-arguments.ts +++ b/lib/compiler-arguments.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -53,7 +53,7 @@ export class CompilerArguments implements ICompilerArguments { localfolder = resolvePathFromAppRoot(localfolder); } - const filepath = path.join(localfolder, this.compilerId + '.json'); + const filepath = path.join(localfolder, `${this.compilerId}.json`); if (await fileExists(filepath)) { const contents = await fs.readFile(filepath); const stats = JSON.parse(contents.toString()); @@ -80,7 +80,7 @@ export class CompilerArguments implements ICompilerArguments { if (region && bucket && prefix && this.compilerId) { const s3 = new S3Bucket(bucket, region); - const result = await s3.get(this.compilerId + '.json', prefix); + const result = await s3.get(`${this.compilerId}.json`, prefix); if (result.hit) { const stats = JSON.parse(unwrap(result.data).toString()); _.each(stats, (times, arg) => { @@ -124,15 +124,20 @@ export class CompilerArguments implements ICompilerArguments { // prefer optimization flags or standard if statistics are not available if (a[1].description.includes('optimization')) { return -1; - } else if (b[1].description.includes('optimization')) { + } + if (b[1].description.includes('optimization')) { return 1; - } else if (a[1].description.includes('optimize')) { + } + if (a[1].description.includes('optimize')) { return -1; - } else if (b[1].description.includes('optimize')) { + } + if (b[1].description.includes('optimize')) { return 1; - } else if (a[1].description.includes('std')) { + } + if (a[1].description.includes('std')) { return -1; - } else if (b[1].description.includes('std')) { + } + if (b[1].description.includes('std')) { return 1; } } diff --git a/lib/compiler-finder.ts b/lib/compiler-finder.ts index 4049b3e41..0c473192a 100644 --- a/lib/compiler-finder.ts +++ b/lib/compiler-finder.ts @@ -22,10 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import http from 'http'; -import https from 'https'; -import path from 'path'; -import {promisify} from 'util'; +import http from 'node:http'; +import https from 'node:https'; +import path from 'node:path'; +import {promisify} from 'node:util'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -119,14 +119,11 @@ export class CompilerFinder { if (statusCode !== 200) { error = new Error( - 'Failed fetching remote compilers from ' + - `${uriSchema}://${host}:${port}${apiPath}\n` + - `Status Code: ${statusCode}`, + `Failed fetching remote compilers from ${uriSchema}://${host}:${port}${apiPath}\nStatus Code: ${statusCode}`, ); } else if (!contentType || !/^application\/json/.test(contentType)) { error = new Error( - 'Invalid content-type.\n' + - `Expected application/json but received ${contentType}`, + `Invalid content-type.\nExpected application/json but received ${contentType}`, ); } if (error) { @@ -147,7 +144,7 @@ export class CompilerFinder { // e.g. https://www.godbolt.ms // (see https://github.com/compiler-explorer/compiler-explorer/issues/1768) if (!compiler.alias) compiler.alias = []; - if (typeof compiler.alias == 'string') compiler.alias = [compiler.alias]; + if (typeof compiler.alias === 'string') compiler.alias = [compiler.alias]; // End fixup compiler.exe = '/dev/null'; compiler.remote = { @@ -184,7 +181,7 @@ export class CompilerFinder { const instances = await this.awsInstances(); const mapped = await Promise.all( instances.map(instance => { - logger.info('Checking instance ' + instance.InstanceId); + logger.info(`Checking instance ${instance.InstanceId}`); const address = this.awsProps('externalTestMode', false) ? instance.PublicDnsName : instance.PrivateDnsName; @@ -353,8 +350,7 @@ export class CompilerFinder { if (props('demanglerClassFile') !== undefined) { logger.error( - `Error in compiler.${compilerId}: ` + - 'demanglerClassFile is no longer supported, please use demanglerType', + `Error in compiler.${compilerId}: demanglerClassFile is no longer supported, please use demanglerType`, ); return null; } @@ -379,7 +375,7 @@ export class CompilerFinder { const bits = compilerName.split('@'); const host = bits[0]; const pathParts = bits[1].split('/'); - const port = parseInt(unwrap(pathParts.shift())); + const port = Number.parseInt(unwrap(pathParts.shift())); const path = pathParts.join('/'); return (await this.fetchRemote(host, port, path, this.ceProps, langId)) || []; } @@ -598,13 +594,13 @@ export class CompilerFinder { if (compiler.buildenvsetup) { compiler.buildenvsetup.props = (propName, def) => { - return this.compilerProps(langId, 'buildenvsetup.' + propName, def); + return this.compilerProps(langId, `buildenvsetup.${propName}`, def); }; } if (compiler.externalparser) { compiler.externalparser.props = (propName: string, def: any) => { - return this.compilerProps(langId, 'externalparser.' + propName, def); + return this.compilerProps(langId, `externalparser.${propName}`, def); }; } diff --git a/lib/compilers/ada.ts b/lib/compilers/ada.ts index 5b3c2229f..143cef467 100644 --- a/lib/compilers/ada.ts +++ b/lib/compilers/ada.ts @@ -23,7 +23,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ConfiguredOverrides} from '../../types/compilation/compiler-overrides.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -72,13 +72,13 @@ export class AdaCompiler extends BaseCompiler { // - "foo.o" may be used by intermediary file, so "-o foo.o" will not // work if building an executable. - if (key && key.filters && key.filters.binary) { + if (key?.filters?.binary) { return path.join(dirPath, 'example'); - } else if (key && key.filters && key.filters.binaryObject) { - return path.join(dirPath, 'example.o'); - } else { - return path.join(dirPath, 'example.s'); } + if (key?.filters?.binaryObject) { + return path.join(dirPath, 'example.o'); + } + return path.join(dirPath, 'example.s'); } override prepareArguments( @@ -174,13 +174,16 @@ export class AdaCompiler extends BaseCompiler { if (a === '-cargs') { part = 1; continue; - } else if (a === '-largs') { + } + if (a === '-largs') { part = 2; continue; - } else if (a === '-bargs') { + } + if (a === '-bargs') { part = 3; continue; - } else if (a === '-margs') { + } + if (a === '-margs') { part = 0; continue; } diff --git a/lib/compilers/argument-parsers.ts b/lib/compilers/argument-parsers.ts index 3df178316..befbad2e3 100644 --- a/lib/compilers/argument-parsers.ts +++ b/lib/compilers/argument-parsers.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; -import process from 'process'; +import path from 'node:path'; +import process from 'node:process'; import * as Sentry from '@sentry/node'; import fs from 'fs-extra'; @@ -58,7 +58,7 @@ export class BaseParser { } static getExampleFilepath(): string { - let filename = path.join(this.getExamplesRoot(), this.getDefaultExampleFilename()); + let filename = path.join(BaseParser.getExamplesRoot(), BaseParser.getDefaultExampleFilename()); if (!path.isAbsolute(filename)) filename = path.join(process.cwd(), filename); return filename; @@ -70,18 +70,19 @@ export class BaseParser { utils.eachLine(stdout, line => { const match1 = line.match(optionWithDescRegex); - if (match1 && match1[1] && match1[2]) { + if (match1?.[1] && match1[2]) { previousOption = match1[1].trim(); if (previousOption) { options[previousOption] = { - description: this.spaceCompress(match1[2].trim()), + description: BaseParser.spaceCompress(match1[2].trim()), timesused: 0, }; } return; - } else if (optionWithoutDescRegex) { + } + if (optionWithoutDescRegex) { const match2 = line.match(optionWithoutDescRegex); - if (match2 && match2[1]) { + if (match2?.[1]) { previousOption = match2[1].trim(); if (previousOption) { @@ -99,14 +100,14 @@ export class BaseParser { options[previousOption].description += line.trim(); else { if (options[previousOption].description.length > 0) { - const combined = options[previousOption].description + ' ' + line.trim(); + const combined = `${options[previousOption].description} ${line.trim()}`; options[previousOption].description = combined; } else { options[previousOption].description = line.trim(); } } - options[previousOption].description = this.spaceCompress(options[previousOption].description); + options[previousOption].description = BaseParser.spaceCompress(options[previousOption].description); } else { previousOption = false; } @@ -133,11 +134,11 @@ export class BaseParser { } static async getOptions(compiler: BaseCompiler, helpArg: string) { - const optionFinder1 = /^ *(--?[\d#+,<=>[\]a-z|-]* ?[\d+,<=>[\]a-z|-]*) +(.*)/i; + const optionFinder1 = /^ *(--?[\d#+,<=>[\]a-z|-]* ?[\d+,<=>[\]a-z|-]*) {2,}(.*)/i; const optionFinder2 = /^ *(--?[\d#+,<=>[\]a-z|-]* ?[\d+,<=>[\]a-z|-]*)/i; const result = await compiler.execCompilerCached(compiler.compiler.exe, [helpArg]); const options = - result.code === 0 ? this.parseLines(result.stdout + result.stderr, optionFinder1, optionFinder2) : {}; + result.code === 0 ? BaseParser.parseLines(result.stdout + result.stderr, optionFinder1, optionFinder2) : {}; compiler.possibleArguments.populateOptions(options); return options; } @@ -165,18 +166,18 @@ export class GCCParser extends BaseParser { static override async setCompilerSettingsFromOptions(compiler: BaseCompiler, options: Record) { const keys = _.keys(options); logger.debug(`gcc-like compiler options: ${keys.join(' ')}`); - if (this.hasSupport(options, '-masm=')) { - await this.checkAndSetMasmIntelIfSupported(compiler); + if (GCCParser.hasSupport(options, '-masm=')) { + await GCCParser.checkAndSetMasmIntelIfSupported(compiler); } - if (this.hasSupport(options, '-fstack-usage')) { + if (GCCParser.hasSupport(options, '-fstack-usage')) { compiler.compiler.stackUsageArg = '-fstack-usage'; compiler.compiler.supportsStackUsageOutput = true; } - if (this.hasSupport(options, '-fdiagnostics-color')) { + if (GCCParser.hasSupport(options, '-fdiagnostics-color')) { if (compiler.compiler.options) compiler.compiler.options += ' '; compiler.compiler.options += '-fdiagnostics-color=always'; } - if (this.hasSupport(options, '-fverbose-asm')) { + if (GCCParser.hasSupport(options, '-fverbose-asm')) { compiler.compiler.supportsVerboseAsm = true; } // This check is not infallible, but takes care of Rust and Swift being picked up :) @@ -188,22 +189,22 @@ export class GCCParser extends BaseParser { // not produce anything. compiler.compiler.removeEmptyGccDump = true; } - if (this.hasSupportStartsWith(options, '-march=')) compiler.compiler.supportsMarch = true; - if (this.hasSupportStartsWith(options, '--target=')) compiler.compiler.supportsTargetIs = true; - if (this.hasSupportStartsWith(options, '--target ')) compiler.compiler.supportsTarget = true; + if (GCCParser.hasSupportStartsWith(options, '-march=')) compiler.compiler.supportsMarch = true; + if (GCCParser.hasSupportStartsWith(options, '--target=')) compiler.compiler.supportsTargetIs = true; + if (GCCParser.hasSupportStartsWith(options, '--target ')) compiler.compiler.supportsTarget = true; } static override async parse(compiler: BaseCompiler) { const results = await Promise.all([ - this.getOptions(compiler, '-fsyntax-only --help'), - this.getOptions(compiler, '-fsyntax-only --target-help'), - this.getOptions(compiler, '-fsyntax-only --help=common'), - this.getOptions(compiler, '-fsyntax-only --help=warnings'), - this.getOptions(compiler, '-fsyntax-only --help=optimizers'), - this.getOptions(compiler, '-fsyntax-only --help=target'), + GCCParser.getOptions(compiler, '-fsyntax-only --help'), + GCCParser.getOptions(compiler, '-fsyntax-only --target-help'), + GCCParser.getOptions(compiler, '-fsyntax-only --help=common'), + GCCParser.getOptions(compiler, '-fsyntax-only --help=warnings'), + GCCParser.getOptions(compiler, '-fsyntax-only --help=optimizers'), + GCCParser.getOptions(compiler, '-fsyntax-only --help=target'), ]); const options = Object.assign({}, ...results); - await this.setCompilerSettingsFromOptions(compiler, options); + await GCCParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } @@ -213,9 +214,8 @@ export class GCCParser extends BaseParser { const match = result.stdout.match(re); if (match) { return match[1].split(' '); - } else { - return []; } + return []; } static getLanguageSpecificHelpFlags(): string[] { @@ -224,12 +224,12 @@ export class GCCParser extends BaseParser { static override async getPossibleStdvers(compiler: BaseCompiler): Promise { const possible: CompilerOverrideOptions = []; - const options = await this.getOptionsStrict(compiler, this.getLanguageSpecificHelpFlags()); + const options = await GCCParser.getOptionsStrict(compiler, GCCParser.getLanguageSpecificHelpFlags()); for (const opt in options) { if (opt.startsWith('-std=') && !options[opt].description?.startsWith('Deprecated')) { const stdver = opt.substring(5); possible.push({ - name: stdver + ': ' + options[opt].description, + name: `${stdver}: ${options[opt].description}`, value: stdver, }); } @@ -238,11 +238,11 @@ export class GCCParser extends BaseParser { } static override async getOptions(compiler: BaseCompiler, helpArg: string) { - const optionFinder1 = /^ *(--?[\d#+,<=>[\]a-z|-]* ?[\d+,<=>[\]a-z|-]*) +(.*)/i; + const optionFinder1 = /^ *(--?[\d#+,<=>[\]a-z|-]* ?[\d+,<=>[\]a-z|-]*) {2,}(.*)/i; const optionFinder2 = /^ *(--?[\d#+,<=>[\]a-z|-]* ?[\d+,<=>[\]a-z|-]*)/i; const result = await compiler.execCompilerCached(compiler.compiler.exe, helpArg.split(' ')); const options = - result.code === 0 ? this.parseLines(result.stdout + result.stderr, optionFinder1, optionFinder2) : {}; + result.code === 0 ? GCCParser.parseLines(result.stdout + result.stderr, optionFinder1, optionFinder2) : {}; compiler.possibleArguments.populateOptions(options); return options; } @@ -250,7 +250,7 @@ export class GCCParser extends BaseParser { static async getOptionsStrict(compiler: BaseCompiler, helpArgs: string[]) { const optionFinder = /^ {2}(--?[\d+,<=>[\]a-z|-]*) *(.*)/i; const result = await compiler.execCompilerCached(compiler.compiler.exe, helpArgs); - return result.code === 0 ? this.parseLines(result.stdout + result.stderr, optionFinder) : {}; + return result.code === 0 ? GCCParser.parseLines(result.stdout + result.stderr, optionFinder) : {}; } } @@ -265,51 +265,52 @@ export class ClangParser extends BaseParser { logger.error(`compiler options appear empty for ${compiler.compiler.id}`); } - if (this.hasSupport(options, '-fsave-optimization-record')) { + if (ClangParser.hasSupport(options, '-fsave-optimization-record')) { compiler.compiler.optArg = '-fsave-optimization-record'; compiler.compiler.supportsOptOutput = true; } - if (this.hasSupport(options, '-fstack-usage')) { + if (ClangParser.hasSupport(options, '-fstack-usage')) { compiler.compiler.stackUsageArg = '-fstack-usage'; compiler.compiler.supportsStackUsageOutput = true; } - if (this.hasSupport(options, '-fverbose-asm')) { + if (ClangParser.hasSupport(options, '-fverbose-asm')) { compiler.compiler.supportsVerboseAsm = true; } - if (this.hasSupport(options, '-emit-llvm')) { + if (ClangParser.hasSupport(options, '-emit-llvm')) { compiler.compiler.supportsIrView = true; compiler.compiler.irArg = ['-Xclang', '-emit-llvm', '-fsyntax-only']; compiler.compiler.minIrArgs = ['-emit-llvm']; } - if (this.hasSupport(options, '-emit-cir')) { + if (ClangParser.hasSupport(options, '-emit-cir')) { compiler.compiler.supportsClangirView = true; } if ( - this.hasSupport(options, '-mllvm') && - this.mllvmOptions.has('--print-before-all') && - this.mllvmOptions.has('--print-after-all') + ClangParser.hasSupport(options, '-mllvm') && + ClangParser.mllvmOptions.has('--print-before-all') && + ClangParser.mllvmOptions.has('--print-after-all') ) { compiler.compiler.optPipeline = { arg: ['-mllvm', '--print-before-all', '-mllvm', '--print-after-all'], moduleScopeArg: [], noDiscardValueNamesArg: [], }; - if (this.mllvmOptions.has('--print-module-scope')) { + if (ClangParser.mllvmOptions.has('--print-module-scope')) { compiler.compiler.optPipeline.moduleScopeArg = ['-mllvm', '-print-module-scope']; } - if (this.hasSupport(options, '-fno-discard-value-names')) { + if (ClangParser.hasSupport(options, '-fno-discard-value-names')) { compiler.compiler.optPipeline.noDiscardValueNamesArg = ['-fno-discard-value-names']; } } - if (this.hasSupport(options, '-fcolor-diagnostics')) compiler.compiler.options += ' -fcolor-diagnostics'; - if (this.hasSupport(options, '-fno-crash-diagnostics')) compiler.compiler.options += ' -fno-crash-diagnostics'; + if (ClangParser.hasSupport(options, '-fcolor-diagnostics')) compiler.compiler.options += ' -fcolor-diagnostics'; + if (ClangParser.hasSupport(options, '-fno-crash-diagnostics')) + compiler.compiler.options += ' -fno-crash-diagnostics'; - if (this.hasSupportStartsWith(options, '--target=')) compiler.compiler.supportsTargetIs = true; - if (this.hasSupportStartsWith(options, '--target ')) compiler.compiler.supportsTarget = true; + if (ClangParser.hasSupportStartsWith(options, '--target=')) compiler.compiler.supportsTargetIs = true; + if (ClangParser.hasSupportStartsWith(options, '--target ')) compiler.compiler.supportsTarget = true; } static getMainHelpOptions(): string[] { @@ -330,14 +331,21 @@ export class ClangParser extends BaseParser { static override async parse(compiler: BaseCompiler) { try { - const options = await this.getOptions(compiler, this.getMainHelpOptions().join(' ')); + const options = await ClangParser.getOptions(compiler, ClangParser.getMainHelpOptions().join(' ')); - const filename = this.getExampleFilepath(); + const filename = ClangParser.getExampleFilepath(); - this.mllvmOptions = new Set( - _.keys(await this.getOptions(compiler, this.getHiddenHelpOptions(filename).join(' '), false, true)), + ClangParser.mllvmOptions = new Set( + _.keys( + await ClangParser.getOptions( + compiler, + ClangParser.getHiddenHelpOptions(filename).join(' '), + false, + true, + ), + ), ); - this.setCompilerSettingsFromOptions(compiler, options); + ClangParser.setCompilerSettingsFromOptions(compiler, options); } catch (error) { const err = `Error while trying to generate llvm backend arguments for ${compiler.compiler.id}: ${error}`; logger.error(err); @@ -356,7 +364,7 @@ export class ClangParser extends BaseParser { if (!match[i]) return []; arr.push({ - name: match[i] + ': ' + match[maxToMatch], + name: `${match[i]}: ${match[maxToMatch]}`, value: match[i], }); } @@ -372,22 +380,22 @@ export class ClangParser extends BaseParser { const re4 = /note: use '([\w+:]*)', '([\w+:]*)', '([\w+:]*)', or '([\w+:]*)' for '(.*)' standard/; for (const line of lines) { let match = line.match(re1); - let stdvers = this.getRegexMatchesAsStdver(match, 2); + let stdvers = ClangParser.getRegexMatchesAsStdver(match, 2); possible.push(...stdvers); if (stdvers.length > 0) continue; match = line.match(re2); - stdvers = this.getRegexMatchesAsStdver(match, 3); + stdvers = ClangParser.getRegexMatchesAsStdver(match, 3); possible.push(...stdvers); if (stdvers.length > 0) continue; match = line.match(re3); - stdvers = this.getRegexMatchesAsStdver(match, 4); + stdvers = ClangParser.getRegexMatchesAsStdver(match, 4); possible.push(...stdvers); if (stdvers.length > 0) continue; match = line.match(re4); - stdvers = this.getRegexMatchesAsStdver(match, 5); + stdvers = ClangParser.getRegexMatchesAsStdver(match, 5); possible.push(...stdvers); } return possible; @@ -397,16 +405,20 @@ export class ClangParser extends BaseParser { let possible: CompilerOverrideOptions = []; // clang doesn't have a --help option to get the std versions, we'll have to compile with a fictional stdversion to coax a response - const filename = this.getExampleFilepath(); + const filename = ClangParser.getExampleFilepath(); - const result = await compiler.execCompilerCached(compiler.compiler.exe, this.getStdVersHelpOptions(filename), { - ...compiler.getDefaultExecOptions(), - createAndUseTempDir: true, - }); + const result = await compiler.execCompilerCached( + compiler.compiler.exe, + ClangParser.getStdVersHelpOptions(filename), + { + ...compiler.getDefaultExecOptions(), + createAndUseTempDir: true, + }, + ); if (result.stderr) { const lines = utils.splitLines(result.stderr); - possible = this.extractPossibleStdvers(lines); + possible = ClangParser.extractPossibleStdvers(lines); possible.sort((a, b) => { return a.value === b.value ? 0 : a.value > b.value ? 1 : -1; }); @@ -422,16 +434,15 @@ export class ClangParser extends BaseParser { const match = line.match(re); if (match) { return match[1]; - } else { - return false; } + return false; }) .filter(Boolean) as string[]; } static override async getPossibleTargets(compiler: BaseCompiler): Promise { - const result = await compiler.execCompilerCached(compiler.compiler.exe, this.getTargetsHelpOptions()); - return this.extractPossibleTargets(utils.splitLines(result.stdout)); + const result = await compiler.execCompilerCached(compiler.compiler.exe, ClangParser.getTargetsHelpOptions()); + return ClangParser.extractPossibleTargets(utils.splitLines(result.stdout)); } static override async getOptions(compiler: BaseCompiler, helpArg: string, populate = true, isolate = false) { @@ -442,7 +453,7 @@ export class ClangParser extends BaseParser { const result = await compiler.execCompilerCached(compiler.compiler.exe, helpArg.split(' '), execOptions); const options = result.code === 0 - ? this.parseLines(result.stdout + result.stderr, optionFinderWithDesc, optionFinderWithoutDesc) + ? ClangParser.parseLines(result.stdout + result.stderr, optionFinderWithDesc, optionFinderWithoutDesc) : {}; if (populate) compiler.possibleArguments.populateOptions(options); return options; @@ -491,10 +502,10 @@ export class ClangCParser extends ClangParser { export class CircleParser extends ClangParser { static override async getOptions(compiler: BaseCompiler, helpArg: string) { - const optionFinder1 = /^ +(--?[\w#,.<=>[\]|-]*) +- (.*)/i; + const optionFinder1 = /^ +(--?[\w#,.<=>[\]|-]*) {2,}- (.*)/i; const optionFinder2 = /^ +(--?[\w#,.<=>[\]|-]*)/i; const result = await compiler.execCompilerCached(compiler.compiler.exe, helpArg.split(' ')); - const options = result.code === 0 ? this.parseLines(result.stdout, optionFinder1, optionFinder2) : {}; + const options = result.code === 0 ? CircleParser.parseLines(result.stdout, optionFinder1, optionFinder2) : {}; compiler.possibleArguments.populateOptions(options); return options; } @@ -508,7 +519,8 @@ export class CircleParser extends ClangParser { if (!isInStdVerSection && line.startsWith(' --std=')) { isInStdVerSection = true; continue; - } else if (isInStdVerSection && line.startsWith(' --')) { + } + if (isInStdVerSection && line.startsWith(' --')) { break; } @@ -519,7 +531,7 @@ export class CircleParser extends ClangParser { const stdver = match[1]; const desc = match[2]; possible.push({ - name: stdver + ': ' + desc, + name: `${stdver}: ${desc}`, value: stdver, }); } @@ -530,44 +542,44 @@ export class CircleParser extends ClangParser { export class LDCParser extends BaseParser { static override async setCompilerSettingsFromOptions(compiler: BaseCompiler, options: Record) { - if (this.hasSupport(options, '--fsave-optimization-record')) { + if (LDCParser.hasSupport(options, '--fsave-optimization-record')) { compiler.compiler.optArg = '--fsave-optimization-record'; compiler.compiler.supportsOptOutput = true; } - if (this.hasSupport(options, '-fverbose-asm')) { + if (LDCParser.hasSupport(options, '-fverbose-asm')) { compiler.compiler.supportsVerboseAsm = true; } - if (this.hasSupport(options, '--print-before-all') && this.hasSupport(options, '--print-after-all')) { + if (LDCParser.hasSupport(options, '--print-before-all') && LDCParser.hasSupport(options, '--print-after-all')) { compiler.compiler.optPipeline = { arg: ['--print-before-all', '--print-after-all'], moduleScopeArg: [], noDiscardValueNamesArg: [], }; - if (this.hasSupport(options, '--print-module-scope')) { + if (LDCParser.hasSupport(options, '--print-module-scope')) { compiler.compiler.optPipeline.moduleScopeArg = ['--print-module-scope']; } - if (this.hasSupport(options, '--fno-discard-value-names')) { + if (LDCParser.hasSupport(options, '--fno-discard-value-names')) { compiler.compiler.optPipeline.noDiscardValueNamesArg = ['--fno-discard-value-names']; } } - if (this.hasSupport(options, '--enable-color')) { + if (LDCParser.hasSupport(options, '--enable-color')) { compiler.compiler.options += ' --enable-color'; } } static override async parse(compiler: BaseCompiler) { - const options = await this.getOptions(compiler, '--help-hidden'); - this.setCompilerSettingsFromOptions(compiler, options); + const options = await LDCParser.getOptions(compiler, '--help-hidden'); + LDCParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } static override async getOptions(compiler: BaseCompiler, helpArg: string, populate = true) { const optionFinder = /^\s*(--?[\d+,<=>[\]a-z|-]*)\s*(.*)/i; const result = await compiler.execCompilerCached(compiler.compiler.exe, helpArg.split(' ')); - const options = result.code === 0 ? this.parseLines(result.stdout + result.stderr, optionFinder) : {}; + const options = result.code === 0 ? LDCParser.parseLines(result.stdout + result.stderr, optionFinder) : {}; if (populate) { compiler.possibleArguments.populateOptions(options); } @@ -577,21 +589,21 @@ export class LDCParser extends BaseParser { export class ElixirParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '--help'); + await ElixirParser.getOptions(compiler, '--help'); return compiler; } } export class ErlangParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '-help'); + await ErlangParser.getOptions(compiler, '-help'); return compiler; } } export class PascalParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '-help'); + await PascalParser.getOptions(compiler, '-help'); return compiler; } } @@ -599,11 +611,11 @@ export class PascalParser extends BaseParser { export class ICCParser extends GCCParser { static override async setCompilerSettingsFromOptions(compiler: BaseCompiler, options: Record) { const keys = _.keys(options); - if (this.hasSupport(options, '-masm=')) { + if (ICCParser.hasSupport(options, '-masm=')) { compiler.compiler.intelAsm = '-masm=intel'; compiler.compiler.supportsIntel = true; } - if (this.hasSupport(options, '-fdiagnostics-color')) { + if (ICCParser.hasSupport(options, '-fdiagnostics-color')) { if (compiler.compiler.options) compiler.compiler.options += ' '; compiler.compiler.options += '-fdiagnostics-color=always'; } @@ -611,9 +623,9 @@ export class ICCParser extends GCCParser { compiler.compiler.supportsGccDump = true; compiler.compiler.removeEmptyGccDump = true; } - if (this.hasSupportStartsWith(options, '-march=')) compiler.compiler.supportsMarch = true; - if (this.hasSupportStartsWith(options, '--target=')) compiler.compiler.supportsTargetIs = true; - if (this.hasSupportStartsWith(options, '--target ')) compiler.compiler.supportsTarget = true; + if (ICCParser.hasSupportStartsWith(options, '-march=')) compiler.compiler.supportsMarch = true; + if (ICCParser.hasSupportStartsWith(options, '--target=')) compiler.compiler.supportsTargetIs = true; + if (ICCParser.hasSupportStartsWith(options, '--target ')) compiler.compiler.supportsTarget = true; } static extractPossibleStdvers(lines: string[]): CompilerOverrideOptions { @@ -632,7 +644,7 @@ export class ICCParser extends GCCParser { const descMatch = line.match(descRe); if (descMatch) { possible.push({ - name: descMatch[1] + ': ' + descMatch[2], + name: `${descMatch[1]}: ${descMatch[2]}`, value: descMatch[1], }); } else { @@ -653,35 +665,35 @@ export class ICCParser extends GCCParser { const result = await compiler.execCompilerCached(compiler.compiler.exe, ['--help']); const lines = utils.splitLines(result.stdout); - return this.extractPossibleStdvers(lines); + return ICCParser.extractPossibleStdvers(lines); } static override async parse(compiler: BaseCompiler) { - const results = await Promise.all([this.getOptions(compiler, '-fsyntax-only --help')]); + const results = await Promise.all([ICCParser.getOptions(compiler, '-fsyntax-only --help')]); const options = Object.assign({}, ...results); - await this.setCompilerSettingsFromOptions(compiler, options); + await ICCParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } } export class ISPCParser extends BaseParser { static override async setCompilerSettingsFromOptions(compiler: BaseCompiler, options: Record) { - if (this.hasSupport(options, '--x86-asm-syntax')) { + if (ISPCParser.hasSupport(options, '--x86-asm-syntax')) { compiler.compiler.intelAsm = '--x86-asm-syntax=intel'; compiler.compiler.supportsIntel = true; } } static override async parse(compiler: BaseCompiler) { - const options = await this.getOptions(compiler, '--help'); - await this.setCompilerSettingsFromOptions(compiler, options); + const options = await ISPCParser.getOptions(compiler, '--help'); + await ISPCParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } static override async getOptions(compiler: BaseCompiler, helpArg: string) { const result = await compiler.execCompilerCached(compiler.compiler.exe, [helpArg]); const optionFinder = /^\s*\[(--?[\d\s()+,/<=>a-z{|}-]*)]\s*(.*)/i; - const options = result.code === 0 ? this.parseLines(result.stdout + result.stderr, optionFinder) : {}; + const options = result.code === 0 ? ISPCParser.parseLines(result.stdout + result.stderr, optionFinder) : {}; compiler.possibleArguments.populateOptions(options); return options; } @@ -689,28 +701,28 @@ export class ISPCParser extends BaseParser { export class JavaParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '-help'); + await JavaParser.getOptions(compiler, '-help'); return compiler; } } export class KotlinParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '-help'); + await KotlinParser.getOptions(compiler, '-help'); return compiler; } } export class ScalaParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '-help'); + await ScalaParser.getOptions(compiler, '-help'); return compiler; } } export class VCParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '/help'); + await VCParser.getOptions(compiler, '/help'); return compiler; } @@ -725,10 +737,10 @@ export class VCParser extends BaseParser { if (!match) { if (previousOption && line.trim().length > 0) { if (options[previousOption].description.endsWith(':')) - options[previousOption].description += ' ' + line.trim(); + options[previousOption].description += ` ${line.trim()}`; else { if (options[previousOption].description.length > 0) - options[previousOption].description += ', ' + line.trim(); + options[previousOption].description += `, ${line.trim()}`; else options[previousOption].description = line.trim(); } } else { @@ -784,7 +796,7 @@ export class VCParser extends BaseParser { if (descMatch) { if (stdverValues.includes(descMatch[1])) { possible.push({ - name: descMatch[1] + ': ' + descMatch[2], + name: `${descMatch[1]}: ${descMatch[2]}`, value: descMatch[1], }); } else { @@ -802,13 +814,13 @@ export class VCParser extends BaseParser { const result = await compiler.execCompilerCached(compiler.compiler.exe, ['/help']); const lines = utils.splitLines(result.stdout); - return this.extractPossibleStdvers(lines); + return VCParser.extractPossibleStdvers(lines); } static override async getOptions(compiler: BaseCompiler, helpArg: string) { const result = await compiler.execCompilerCached(compiler.compiler.exe, [helpArg]); const optionFinder = /^\s*(\/[\w#+,.:<=>[\]{|}-]*)\s*(.*)/i; - const options = result.code === 0 ? this.parseLines(result.stdout, optionFinder) : {}; + const options = result.code === 0 ? VCParser.parseLines(result.stdout, optionFinder) : {}; compiler.possibleArguments.populateOptions(options); return options; } @@ -816,22 +828,22 @@ export class VCParser extends BaseParser { export class RustParser extends BaseParser { static override async setCompilerSettingsFromOptions(compiler: BaseCompiler, options: Record) { - if (this.hasSupport(options, '--color')) { + if (RustParser.hasSupport(options, '--color')) { if (compiler.compiler.options) compiler.compiler.options += ' '; compiler.compiler.options += '--color=always'; } - if (this.hasSupportStartsWith(options, '--target=')) compiler.compiler.supportsTargetIs = true; - if (this.hasSupportStartsWith(options, '--target ')) compiler.compiler.supportsTarget = true; + if (RustParser.hasSupportStartsWith(options, '--target=')) compiler.compiler.supportsTargetIs = true; + if (RustParser.hasSupportStartsWith(options, '--target ')) compiler.compiler.supportsTarget = true; } static override async parse(compiler: BaseCompiler) { const results = await Promise.all([ - this.getOptions(compiler, '--help'), - this.getOptions(compiler, '-C help'), - this.getOptions(compiler, '--help -v'), + RustParser.getOptions(compiler, '--help'), + RustParser.getOptions(compiler, '-C help'), + RustParser.getOptions(compiler, '--help -v'), ]); const options = Object.assign({}, ...results); - await this.setCompilerSettingsFromOptions(compiler, options); + await RustParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } @@ -840,7 +852,7 @@ export class RustParser extends BaseParser { const re = /--edition ([\d|]*)/; const match = result.stdout.match(re); - if (match && match[1]) { + if (match?.[1]) { return match[1].split('|'); } @@ -872,24 +884,23 @@ export class RustParser extends BaseParser { options[previousOption].description += line.trim(); else { if (options[previousOption].description.length > 0) - options[previousOption].description += ' ' + line.trim(); + options[previousOption].description += ` ${line.trim()}`; else options[previousOption].description = line.trim(); } } else { previousOption = false; } return; - } else { - if (match1) { - previousOption = match1[1].trim(); - if (match1[2]) description = match1[2].trim(); - } else if (match2) { - previousOption = match2[1].trim(); - if (match2[2]) description = match2[2].trim(); - } else if (match3) { - previousOption = match3[1].trim(); - if (match3[2]) description = match3[2].trim(); - } + } + if (match1) { + previousOption = match1[1].trim(); + if (match1[2]) description = match1[2].trim(); + } else if (match2) { + previousOption = match2[1].trim(); + if (match2[2]) description = match2[2].trim(); + } else if (match3) { + previousOption = match3[1].trim(); + if (match3[2]) description = match3[2].trim(); } if (previousOption) { @@ -910,9 +921,9 @@ export class RustParser extends BaseParser { if (helpArg === '-C help') { const optionFinder = /^\s*(-c\s*[\d=a-z-]*)\s--\s(.*)/i; - options = this.parseLines(result.stdout + result.stderr, optionFinder); + options = RustParser.parseLines(result.stdout + result.stderr, optionFinder); } else { - options = this.parseRustHelpLines(result.stdout + result.stderr); + options = RustParser.parseRustHelpLines(result.stdout + result.stderr); } } compiler.possibleArguments.populateOptions(options); @@ -922,29 +933,29 @@ export class RustParser extends BaseParser { export class ZksolcParser extends RustParser { static override async parse(compiler: BaseCompiler) { - const options = await this.getOptions(compiler, '--help'); - await this.setCompilerSettingsFromOptions(compiler, options); + const options = await ZksolcParser.getOptions(compiler, '--help'); + await ZksolcParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } } export class MrustcParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '--help'); + await MrustcParser.getOptions(compiler, '--help'); return compiler; } } export class NimParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '-help'); + await NimParser.getOptions(compiler, '-help'); return compiler; } } export class CrystalParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, 'build'); + await CrystalParser.getOptions(compiler, 'build'); return compiler; } } @@ -952,7 +963,7 @@ export class CrystalParser extends BaseParser { export class TableGenParser extends BaseParser { static async getPossibleActions(compiler: BaseCompiler): Promise { const result = await compiler.execCompilerCached(compiler.compiler.exe, ['--help']); - return this.extractPossibleActions(utils.splitLines(result.stdout)); + return TableGenParser.extractPossibleActions(utils.splitLines(result.stdout)); } static extractPossibleActions(lines: string[]): CompilerOverrideOptions { @@ -974,7 +985,7 @@ export class TableGenParser extends BaseParser { } actions.push({ - name: action_match[1].substring(2) + ': ' + action_match[2], + name: `${action_match[1].substring(2)}: ${action_match[2]}`, value: action_match[1], }); } @@ -986,21 +997,21 @@ export class TableGenParser extends BaseParser { export class TypeScriptNativeParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '--help'); + await TypeScriptNativeParser.getOptions(compiler, '--help'); return compiler; } } export class TurboCParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, ''); + await TurboCParser.getOptions(compiler, ''); return compiler; } } export class ToitParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '-help'); + await ToitParser.getOptions(compiler, '-help'); return compiler; } } @@ -1013,13 +1024,13 @@ export class JuliaParser extends BaseParser { compiler.compilerWrapperPath, helpArg, ]); - const options = result.code === 0 ? this.parseLines(result.stdout + result.stderr, optionFinder) : {}; + const options = result.code === 0 ? JuliaParser.parseLines(result.stdout + result.stderr, optionFinder) : {}; compiler.possibleArguments.populateOptions(options); return options; } static override async parse(compiler: JuliaCompiler) { - await this.getOptions(compiler, '--help'); + await JuliaParser.getOptions(compiler, '--help'); return compiler; } } @@ -1040,7 +1051,7 @@ export class Z88dkParser extends BaseParser { export class WasmtimeParser extends BaseParser { static override async parse(compiler: BaseCompiler) { - await this.getOptions(compiler, '--help'); + await WasmtimeParser.getOptions(compiler, '--help'); return compiler; } } @@ -1079,12 +1090,12 @@ export class FlangParser extends ClangParser { } static override async setCompilerSettingsFromOptions(compiler: BaseCompiler, options: Record) { - super.setCompilerSettingsFromOptions(compiler, options); + ClangParser.setCompilerSettingsFromOptions(compiler, options); // flang does not allow -emit-llvm to be used as it is with clang // as -Xflang -emit-llvm. Instead you just give -emit-llvm to flang // directly. - if (this.hasSupport(options, '-emit-llvm')) { + if (FlangParser.hasSupport(options, '-emit-llvm')) { compiler.compiler.supportsIrView = true; compiler.compiler.irArg = ['-emit-llvm']; compiler.compiler.minIrArgs = ['-emit-llvm']; @@ -1106,7 +1117,7 @@ export class FlangParser extends ClangParser { const re1 = /error: Only -std=([\w+]*) is allowed currently./; for (const line of lines) { const match = line.match(re1); - if (match && match[1]) { + if (match?.[1]) { possible.push({ name: match[1], value: match[1], @@ -1119,9 +1130,9 @@ export class FlangParser extends ClangParser { export class GHCParser extends GCCParser { static override async parse(compiler: BaseCompiler) { - const results = await Promise.all([this.getOptions(compiler, '--help')]); + const results = await Promise.all([GHCParser.getOptions(compiler, '--help')]); const options = Object.assign({}, ...results); - await this.setCompilerSettingsFromOptions(compiler, options); + await GHCParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } @@ -1129,7 +1140,7 @@ export class GHCParser extends GCCParser { const optionFinder1 = /^ {4}(-[\w[\]]+)\s+(.*)/i; const optionFinder2 = /^ {4}(-[\w[\]]+)/; const result = await compiler.execCompilerCached(compiler.compiler.exe, helpArg.split(' ')); - const options = result.code === 0 ? this.parseLines(result.stdout, optionFinder1, optionFinder2) : {}; + const options = result.code === 0 ? GHCParser.parseLines(result.stdout, optionFinder1, optionFinder2) : {}; compiler.possibleArguments.populateOptions(options); return options; @@ -1138,9 +1149,9 @@ export class GHCParser extends GCCParser { export class SwiftParser extends ClangParser { static override async parse(compiler: BaseCompiler) { - const results = await Promise.all([this.getOptions(compiler, '--help')]); + const results = await Promise.all([SwiftParser.getOptions(compiler, '--help')]); const options = Object.assign({}, ...results); - this.setCompilerSettingsFromOptions(compiler, options); + SwiftParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } @@ -1155,16 +1166,16 @@ export class SwiftParser extends ClangParser { export class TendraParser extends GCCParser { static override async parse(compiler: BaseCompiler) { - const results = await Promise.all([this.getOptions(compiler, '--help')]); + const results = await Promise.all([TendraParser.getOptions(compiler, '--help')]); const options = Object.assign({}, ...results); - await this.setCompilerSettingsFromOptions(compiler, options); + await TendraParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } static override async getOptions(compiler: BaseCompiler, helpArg: string) { const optionFinder = /^ *(-[\d#+,<=>[\]a-z|-]* ?[\d+,<=>[\]a-z|-]*) : +(.*)/i; const result = await compiler.execCompilerCached(compiler.compiler.exe, helpArg.split(' ')); - const options = this.parseLines(result.stdout + result.stderr, optionFinder); + const options = TendraParser.parseLines(result.stdout + result.stderr, optionFinder); compiler.possibleArguments.populateOptions(options); return options; } @@ -1185,10 +1196,13 @@ export class GolangParser extends GCCParser { static override async parse(compiler: BaseCompiler) { const results = await Promise.all([ - this.getOptions(compiler, 'build -o ./output.s "-gcflags=-S --help" ' + this.getExampleFilepath()), + GolangParser.getOptions( + compiler, + `build -o ./output.s "-gcflags=-S --help" ${GolangParser.getExampleFilepath()}`, + ), ]); const options = Object.assign({}, ...results); - await this.setCompilerSettingsFromOptions(compiler, options); + await GolangParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } @@ -1199,7 +1213,7 @@ export class GolangParser extends GCCParser { ...compiler.getDefaultExecOptions(), createAndUseTempDir: true, }); - const options = this.parseLines(result.stdout + result.stderr, optionFinder1, optionFinder2); + const options = GolangParser.parseLines(result.stdout + result.stderr, optionFinder1, optionFinder2); compiler.possibleArguments.populateOptions(options); return options; } @@ -1212,7 +1226,7 @@ export class GnuCobolParser extends GCCParser { static override async getPossibleStdvers(compiler: BaseCompiler): Promise { const possible: CompilerOverrideOptions = []; - const options = await this.getOptionsStrict(compiler, this.getLanguageSpecificHelpFlags()); + const options = await GnuCobolParser.getOptionsStrict(compiler, GnuCobolParser.getLanguageSpecificHelpFlags()); for (const opt in options) { if (opt.startsWith('-std=')) { const vers = options[opt].description @@ -1235,16 +1249,16 @@ export class GnuCobolParser extends GCCParser { export class MadpascalParser extends GCCParser { static override async parse(compiler: BaseCompiler) { - const results = await Promise.all([this.getOptions(compiler, '')]); + const results = await Promise.all([MadpascalParser.getOptions(compiler, '')]); const options = Object.assign({}, ...results); - await this.setCompilerSettingsFromOptions(compiler, options); + await MadpascalParser.setCompilerSettingsFromOptions(compiler, options); return compiler; } static override async getOptions(compiler: BaseCompiler, helpArg: string) { const optionFinder = /^(-[\w:<>]*) *(.*)/i; const result = await compiler.execCompilerCached(compiler.compiler.exe, []); - const options = this.parseLines(result.stdout + result.stderr, optionFinder); + const options = MadpascalParser.parseLines(result.stdout + result.stderr, optionFinder); compiler.possibleArguments.populateOptions(options); return options; } diff --git a/lib/compilers/assembly.ts b/lib/compilers/assembly.ts index 1d9fa9ed6..f94aac38d 100644 --- a/lib/compilers/assembly.ts +++ b/lib/compilers/assembly.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import fs from 'fs'; -import path from 'path'; +import fs from 'node:fs'; +import path from 'node:path'; import _ from 'underscore'; @@ -101,9 +101,11 @@ export class AssemblyCompiler extends BaseCompiler { const output = result.stdout.map(line => line.text).join('\n'); if (output.includes('ELF32') && output.includes('80386')) { return 'x86'; - } else if (output.includes('ELF64') && output.includes('X86-64')) { + } + if (output.includes('ELF64') && output.includes('X86-64')) { return 'x86_64'; - } else if (output.includes('Mach-O 64-bit x86-64')) { + } + if (output.includes('Mach-O 64-bit x86-64')) { // note: this is to support readelf=objdump on Mac return 'x86_64'; } diff --git a/lib/compilers/avrgcc6502.ts b/lib/compilers/avrgcc6502.ts index d0e27fd15..7ac37a834 100644 --- a/lib/compilers/avrgcc6502.ts +++ b/lib/compilers/avrgcc6502.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -50,7 +50,7 @@ export class AvrGcc6502Compiler extends BaseCompiler { public override getOutputFilename(dirPath: string, outputFilebase: string, key?: any) { let filename; - if (key && key.backendOptions && key.backendOptions.customOutputFilename) { + if (key?.backendOptions?.customOutputFilename) { filename = key.backendOptions.customOutputFilename; } else { filename = `${outputFilebase}.6502.asm`; @@ -58,9 +58,8 @@ export class AvrGcc6502Compiler extends BaseCompiler { if (dirPath) { return path.join(dirPath, filename); - } else { - return filename; } + return filename; } protected override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string): string[] { diff --git a/lib/compilers/beebasm.ts b/lib/compilers/beebasm.ts index ba9563146..621ce8e3d 100644 --- a/lib/compilers/beebasm.ts +++ b/lib/compilers/beebasm.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; diff --git a/lib/compilers/c3c.ts b/lib/compilers/c3c.ts index e8329218e..7335e638d 100644 --- a/lib/compilers/c3c.ts +++ b/lib/compilers/c3c.ts @@ -1,4 +1,4 @@ -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -21,6 +21,6 @@ export class C3Compiler extends BaseCompiler { } override getIrOutputFilename(inputFilename: string): string { - return this.filename(path.dirname(inputFilename) + '/output.ll'); + return this.filename(`${path.dirname(inputFilename)}/output.ll`); } } diff --git a/lib/compilers/carbon.ts b/lib/compilers/carbon.ts index b0ec58c17..62b434889 100644 --- a/lib/compilers/carbon.ts +++ b/lib/compilers/carbon.ts @@ -83,7 +83,7 @@ export class CarbonCompiler extends BaseCompiler { // Hook to parse out the "result: 123" line at the end of the interpreted execution run. const re = /^result: (\d+)$/; const match = re.exec(this.lastLine(result.asm as ResultLine[])); - const code = match ? parseInt(match[1]) : -1; + const code = match ? Number.parseInt(match[1]) : -1; result.execResult = { stdout: result.stdout, stderr: [], diff --git a/lib/compilers/cc65.ts b/lib/compilers/cc65.ts index ac5d9b06a..a2ca7f97c 100644 --- a/lib/compilers/cc65.ts +++ b/lib/compilers/cc65.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -67,13 +67,12 @@ export class Cc65Compiler extends BaseCompiler { override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { if (filters.binary) { return ['-g', '-o', this.filename(outputFilename)]; - } else { - return ['-g', '-S', '-c', '-o', this.filename(outputFilename)]; } + return ['-g', '-S', '-c', '-o', this.filename(outputFilename)]; } override getCompilerEnvironmentVariables(compilerflags: string) { - const allOptions = (this.compiler.options + ' ' + compilerflags).trim(); + const allOptions = `${this.compiler.options} ${compilerflags}`.trim(); return {...this.cmakeBaseEnv, CFLAGS: allOptions}; } @@ -132,7 +131,7 @@ export class Cc65Compiler extends BaseCompiler { res, outputFilename, ArtifactType.c64prg, - path.basename(outputFilename) + '.prg', + `${path.basename(outputFilename)}.prg`, ); } } diff --git a/lib/compilers/cerberus.ts b/lib/compilers/cerberus.ts index 94ef8a682..31f404e60 100644 --- a/lib/compilers/cerberus.ts +++ b/lib/compilers/cerberus.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {ParsedAsmResult} from '../../types/asmresult/asmresult.interfaces.js'; import {BypassCache, CacheKey, ExecutionOptions} from '../../types/compilation/compilation.interfaces.js'; @@ -66,7 +66,7 @@ export class CerberusCompiler extends BaseCompiler { override async objdump(outputFilename: string, result: any, maxSize: number) { if (!(await utils.fileExists(outputFilename))) { - result.asm = ''; + result.asm = ``; return result; } @@ -106,16 +106,15 @@ export class CerberusCompiler extends BaseCompiler { didExecute: true, buildResult: compileResult, }; - } else { - return { - stdout: compileResult.stdout, - stderr: compileResult.stderr, - code: compileResult.code, - didExecute: false, - buildResult: compileResult, - timedOut: false, - }; } + return { + stdout: compileResult.stdout, + stderr: compileResult.stderr, + code: compileResult.code, + didExecute: false, + buildResult: compileResult, + timedOut: false, + }; } override async processAsm(result): Promise { diff --git a/lib/compilers/circle.ts b/lib/compilers/circle.ts index d5e4d1ff9..857c722d5 100644 --- a/lib/compilers/circle.ts +++ b/lib/compilers/circle.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; diff --git a/lib/compilers/circt.ts b/lib/compilers/circt.ts index ea75d7142..1f9e638f9 100644 --- a/lib/compilers/circt.ts +++ b/lib/compilers/circt.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import {BaseCompiler} from '../base-compiler.js'; diff --git a/lib/compilers/clang.ts b/lib/compilers/clang.ts index af1e40073..aa92e8eb9 100644 --- a/lib/compilers/clang.ts +++ b/lib/compilers/clang.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import fs from 'fs'; -import path from 'path'; +import fs from 'node:fs'; +import path from 'node:path'; import _ from 'underscore'; @@ -99,8 +99,7 @@ export class ClangCompiler extends BaseCompiler { async addTimeTraceToResult(result: CompilationResult, dirPath: string, outputFilename: string) { const timeTraceJson = utils.changeExtension(outputFilename, '.json'); - const alternativeFilename = - outputFilename + '-' + utils.changeExtension(path.basename(result.inputFilename || 'example.cpp'), '.json'); + const alternativeFilename = `${outputFilename}-${utils.changeExtension(path.basename(result.inputFilename || 'example.cpp'), '.json')}`; const mainFilepath = path.join(dirPath, timeTraceJson); const alternativeJsonFilepath = path.join(dirPath, alternativeFilename); @@ -176,8 +175,7 @@ export class ClangCompiler extends BaseCompiler { return option === '-stdlib=libc++'; }) ) { - const addedIncludePath = - '-I' + path.join(path.dirname(this.compiler.exe), '../include/x86_64-unknown-linux-gnu/c++/v1/'); + const addedIncludePath = `-I${path.join(path.dirname(this.compiler.exe), '../include/x86_64-unknown-linux-gnu/c++/v1/')}`; if ( !_.any(userOptions, option => { return option === addedIncludePath; @@ -271,7 +269,7 @@ export class ClangCompiler extends BaseCompiler { } async extractBitcodeFromBundle(bundlefile: string, devicename: string): Promise { - const bcfile = path.join(path.dirname(bundlefile), devicename + '.bc'); + const bcfile = path.join(path.dirname(bundlefile), `${devicename}.bc`); const env = this.getDefaultExecOptions(); env.customCwd = path.dirname(bundlefile); @@ -290,7 +288,7 @@ export class ClangCompiler extends BaseCompiler { } if (this.llvmDisassemblerPath) { - const llvmirFile = path.join(path.dirname(bundlefile), devicename + '.ll'); + const llvmirFile = path.join(path.dirname(bundlefile), `${devicename}.ll`); const disassembleResult: UnprocessedExecResult = await this.exec(this.llvmDisassemblerPath, [bcfile], env); if (disassembleResult.code !== 0) { @@ -298,9 +296,8 @@ export class ClangCompiler extends BaseCompiler { } return fs.readFileSync(llvmirFile, 'utf8'); - } else { - return ''; } + return ''; } async processDeviceAssembly(deviceName: string, deviceAsm: string, filters, compilationInfo: CompilationInfo) { diff --git a/lib/compilers/clangcl.ts b/lib/compilers/clangcl.ts index aba579f26..13b513e85 100644 --- a/lib/compilers/clangcl.ts +++ b/lib/compilers/clangcl.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {LLVMIrBackendOptions} from '../../types/compilation/ir.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -76,7 +76,7 @@ export class ClangCLCompiler extends Win32Compiler { } override getIrOutputFilename(inputFilename: string): string { - return this.filename(path.dirname(inputFilename) + '/output.s.obj'); + return this.filename(`${path.dirname(inputFilename)}/output.s.obj`); } override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { diff --git a/lib/compilers/clean.ts b/lib/compilers/clean.ts index 34594cafa..3a7975263 100644 --- a/lib/compilers/clean.ts +++ b/lib/compilers/clean.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -39,9 +39,8 @@ export class CleanCompiler extends BaseCompiler { override optionsForFilter(filters: ParseFiltersAndOutputOptions) { if (filters.binary) { return []; - } else { - return ['-S']; } + return ['-S']; } override getOutputFilename(dirPath: string) { @@ -68,23 +67,20 @@ export class CleanCompiler extends BaseCompiler { if (!matches) matches = line.match(typeeerrorRegex); if (matches) { - return ':' + matches[1] + ',0: error: (' + matches[2] + ') ' + matches[3]; + return `:${matches[1]},0: error: (${matches[2]}) ${matches[3]}`; } matches = line.match(errorLineRegex); if (matches) { - return ':' + matches[1] + ',0: error: ' + matches[2]; + return `:${matches[1]},0: error: ${matches[2]}`; } matches = line.match(parseerrorRegex); if (matches) { if (matches[3] === '') { - return ':' + matches[1] + ',' + matches[2] + ': error: ' + matches[4]; - } else { - return ( - ':' + matches[1] + ',' + matches[2] + ': error: (' + matches[3] + ') ' + matches[4] - ); + return `:${matches[1]},${matches[2]}: error: ${matches[4]}`; } + return `:${matches[1]},${matches[2]}: error: (${matches[3]}) ${matches[4]}`; } return line; @@ -110,8 +106,8 @@ export class CleanCompiler extends BaseCompiler { execOptions.env.CLEANLIB = path.join(compilerPath, '../lib/exe'); } execOptions.env.CLEANPATH = this.compiler.libPath.join(':'); - execOptions.env.CLEANABCPATH = tmpDir + '/Clean System Files'; - execOptions.env.CLEANOPATH = tmpDir + '/obj'; + execOptions.env.CLEANABCPATH = `${tmpDir}/Clean System Files`; + execOptions.env.CLEANOPATH = `${tmpDir}/obj`; options.pop(); options.push(moduleName); diff --git a/lib/compilers/clspv.ts b/lib/compilers/clspv.ts index d3719d5d3..731f0ade5 100644 --- a/lib/compilers/clspv.ts +++ b/lib/compilers/clspv.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; diff --git a/lib/compilers/cppfront.ts b/lib/compilers/cppfront.ts index 55e6f701a..2849ba285 100644 --- a/lib/compilers/cppfront.ts +++ b/lib/compilers/cppfront.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; diff --git a/lib/compilers/cproc.ts b/lib/compilers/cproc.ts index fa577e8ce..4383bd2f6 100644 --- a/lib/compilers/cproc.ts +++ b/lib/compilers/cproc.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {BaseCompiler} from '../base-compiler.js'; @@ -36,7 +36,7 @@ export class CprocCompiler extends BaseCompiler { // needed for finding the qbe program const toolRoot = path.resolve(path.dirname(this.compiler.exe)); - execOptions.env.PATH = execOptions.env.PATH + ':' + toolRoot; + execOptions.env.PATH = `${execOptions.env.PATH}:${toolRoot}`; return execOptions; } } diff --git a/lib/compilers/crystal.ts b/lib/compilers/crystal.ts index 4eb3e9a2b..2dee520a3 100644 --- a/lib/compilers/crystal.ts +++ b/lib/compilers/crystal.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import semverParser from 'semver'; import _ from 'underscore'; @@ -80,17 +80,15 @@ export class CrystalCompiler extends BaseCompiler { override getIrOutputFilename(inputFilename: string, filters: ParseFiltersAndOutputOptions): string { if (this.usesNewEmitFilenames()) { return this.getOutputFilename(path.dirname(inputFilename), this.outputFilebase).replace('.s', '.ll'); - } else { - return super.getIrOutputFilename(inputFilename, filters); } + return super.getIrOutputFilename(inputFilename, filters); } override getOutputFilename(dirPath: string, outputFilebase: string) { if (this.usesNewEmitFilenames()) { return path.join(dirPath, `${outputFilebase}.s`); - } else { - return path.join(dirPath, `${path.basename(this.compileFilename, this.lang.extensions[0])}.s`); } + return path.join(dirPath, `${path.basename(this.compileFilename, this.lang.extensions[0])}.s`); } override getExecutableFilename(dirPath: string, outputFilebase: string) { diff --git a/lib/compilers/d8.ts b/lib/compilers/d8.ts index 69403abf9..2d88daa3e 100644 --- a/lib/compilers/d8.ts +++ b/lib/compilers/d8.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -199,7 +199,7 @@ export class D8Compiler extends BaseCompiler implements SimpleOutputFilenameComp const smaliFiles = files.filter(f => f.endsWith('.smali')); let objResult = ''; for (const smaliFile of smaliFiles) { - objResult = objResult.concat(fs.readFileSync(path.join(dirPath, smaliFile), 'utf8') + '\n\n'); + objResult = objResult.concat(`${fs.readFileSync(path.join(dirPath, smaliFile), 'utf8')}\n\n`); } const asmResult: ParsedAsmResult = { diff --git a/lib/compilers/dart.ts b/lib/compilers/dart.ts index 73075bc57..6283c5d61 100644 --- a/lib/compilers/dart.ts +++ b/lib/compilers/dart.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import Semver from 'semver'; @@ -79,9 +79,8 @@ export class DartCompiler extends BaseCompiler { const dartCompileIntroduction = '2.10.0'; if (Semver.lt(utils.asSafeVer(this.compiler.semver), dartCompileIntroduction, true)) { return ['-k', 'aot', '-o', this.filename(outputFilename)]; - } else { - return ['compile', 'aot-snapshot', '-o', this.filename(outputFilename)]; } + return ['compile', 'aot-snapshot', '-o', this.filename(outputFilename)]; } override getArgumentParserClass() { diff --git a/lib/compilers/dex2oat.ts b/lib/compilers/dex2oat.ts index 5d60080f1..ab5d08d32 100644 --- a/lib/compilers/dex2oat.ts +++ b/lib/compilers/dex2oat.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -225,7 +225,7 @@ export class Dex2OatCompiler extends BaseCompiler { let match; if (this.versionPrefixRegex.test(this.compiler.id)) { match = this.compiler.id.match(this.versionPrefixRegex); - versionPrefix = parseInt(match![2]); + versionPrefix = Number.parseInt(match![2]); } else if (this.latestVersionRegex.test(this.compiler.id)) { isLatest = true; } @@ -238,7 +238,7 @@ export class Dex2OatCompiler extends BaseCompiler { '--copy-dex-files=always', ...(versionPrefix >= 34 || isLatest ? ['--runtime-arg', '-Xgc:CMC'] : []), '--runtime-arg', - '-Xbootclasspath:' + bootclassjars.map(f => path.join(this.artArtifactDir, f)).join(':'), + `-Xbootclasspath:${bootclassjars.map(f => path.join(this.artArtifactDir, f)).join(':')}`, '--runtime-arg', '-Xbootclasspath-locations:/apex/com.android.art/javalib/core-oj.jar' + ':/apex/com.android.art/javalib/core-libart.jar' + @@ -352,17 +352,17 @@ export class Dex2OatCompiler extends BaseCompiler { // dex2oat doesn't have --version, but artArtifactDir contains a file with // the build number. override async getVersion() { - const versionFile = this.artArtifactDir + '/snapshot-creation-build-number.txt'; + const versionFile = `${this.artArtifactDir}/snapshot-creation-build-number.txt`; const version = fs.readFileSync(versionFile, {encoding: 'utf8'}); return { - stdout: 'Android Build ' + version, + stdout: `Android Build ${version}`, stderr: '', code: 0, }; } override async processAsm(result) { - let asm: string = ''; + let asm = ''; if (typeof result.asm === 'string') { const asmLines = utils.splitLines(result.asm); @@ -370,15 +370,13 @@ export class Dex2OatCompiler extends BaseCompiler { return { asm: [{text: asmLines[0], source: null}], }; - } else { - return { - asm: [{text: JSON.stringify(asmLines), source: null}], - }; } - } else { - // result.asm is an array, but we only expect it to have one value. - asm = result.asm[0].text; + return { + asm: [{text: JSON.stringify(asmLines), source: null}], + }; } + // result.asm is an array, but we only expect it to have one value. + asm = result.asm[0].text; const segments: ParsedAsmResultLine[] = []; if (this.fullOutput) { @@ -389,15 +387,15 @@ export class Dex2OatCompiler extends BaseCompiler { segments.push( { - text: 'Instruction set: ' + compileData.insnSet, + text: `Instruction set: ${compileData.insnSet}`, source: null, }, { - text: 'Instruction set features: ' + compileData.insnSetFeatures, + text: `Instruction set features: ${compileData.insnSetFeatures}`, source: null, }, { - text: 'Compiler filter: ' + compileData.compilerFilter, + text: `Compiler filter: ${compileData.compilerFilter}`, source: null, }, {text: '', source: null}, @@ -407,12 +405,12 @@ export class Dex2OatCompiler extends BaseCompiler { for (const className of classNames) { for (const method of classToMethods[className]) { segments.push({ - text: method + ' [' + methodsToSizes[method] + ' bytes]', + text: `${method} [${methodsToSizes[method]} bytes]`, source: null, }); for (const instruction of methodsToInstructions[method]) { segments.push({ - text: ' ' + instruction, + text: ` ${instruction}`, source: null, }); } @@ -470,10 +468,10 @@ export class Dex2OatCompiler extends BaseCompiler { inCode = true; } else if (inCode && this.insnRegex.test(l)) { match = l.match(this.insnRegex); - methodsToInstructions[currentMethod].push(match![1] + ' ' + match![2]); + methodsToInstructions[currentMethod].push(`${match![1]} ${match![2]}`); } else if (inCode && this.stackMapRegex.test(l)) { match = l.match(this.stackMapRegex); - methodsToInstructions[currentMethod].push(' ' + match![1] + ' ' + match![2]); + methodsToInstructions[currentMethod].push(` ${match![1]} ${match![2]}`); } } @@ -495,7 +493,7 @@ export class Dex2OatCompiler extends BaseCompiler { const compileEnd = performance.now(); try { - const classesCfg = dirPath + '/classes.cfg'; + const classesCfg = `${dirPath}/classes.cfg`; const rawText = fs.readFileSync(classesCfg, {encoding: 'utf8'}); const parseStart = performance.now(); const optPipeline = this.passDumpParser.process(rawText); diff --git a/lib/compilers/dmd.ts b/lib/compilers/dmd.ts index 92df38fd0..ea1854427 100644 --- a/lib/compilers/dmd.ts +++ b/lib/compilers/dmd.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -47,7 +47,7 @@ export class DMDCompiler extends BaseCompiler { } override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { - const options = ['-g', '-of' + this.filename(outputFilename)]; + const options = ['-g', `-of${this.filename(outputFilename)}`]; if (filters.binaryObject) options.push('-c'); return options; } diff --git a/lib/compilers/dosbox-compiler.ts b/lib/compilers/dosbox-compiler.ts index 0b317c705..51d45e4f4 100644 --- a/lib/compilers/dosbox-compiler.ts +++ b/lib/compilers/dosbox-compiler.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -121,7 +121,7 @@ export class DosboxCompiler extends BaseCompiler { result = await (this.env.enqueue(async () => this.exec(compiler, args, options), ) as Promise); - if (result && result.okToCache) { + if (result?.okToCache) { this.env .compilerCachePut(key as any, result, undefined) .then(() => { @@ -170,9 +170,8 @@ export class DosboxCompiler extends BaseCompiler { options.map(option => { if (option === inputFilename) { return path.basename(option); - } else { - return option; } + return option; }), inputFilename, execOptions, diff --git a/lib/compilers/dotnet.ts b/lib/compilers/dotnet.ts index 63bf6ea43..9c3b42133 100644 --- a/lib/compilers/dotnet.ts +++ b/lib/compilers/dotnet.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -788,9 +788,8 @@ do() if (fs.existsSync(versionFilePath)) { const versionString = await fs.readFile(versionFilePath); return versionString.toString(); - } else { - return ''; } + return ''; } async runCorerunForDisasm( @@ -859,11 +858,16 @@ do() ) { // prettier-ignore const crossgen2Options = [ - '-r', path.join(bclPath, '/'), - '-r', this.disassemblyLoaderPath, + '-r', + path.join(bclPath, '/'), + '-r', + this.disassemblyLoaderPath, dllPath, - '-o', `${AssemblyName}.r2r.dll`, - ].concat(toolOptions).concat(toolSwitches); + '-o', + `${AssemblyName}.r2r.dll`, + ] + .concat(toolOptions) + .concat(toolSwitches); if (sdkMajorVersion >= 9) { crossgen2Options.push('--inputbubble', '--compilebubblegenerics'); @@ -872,7 +876,7 @@ do() if (await fs.exists(this.crossgen2Path)) { compiler = this.crossgen2Path; } else { - crossgen2Options.unshift(this.crossgen2Path + '.dll'); + crossgen2Options.unshift(`${this.crossgen2Path}.dll`); } const compilerExecResult = await this.exec(compiler, crossgen2Options, execOptions); @@ -900,10 +904,14 @@ do() // prettier-ignore const ilcOptions = [ dllPath, - '-o', `${AssemblyName}.obj`, - '-r', this.disassemblyLoaderPath, - '-r', path.join(this.clrBuildDir, 'aotsdk', '*.dll'), - '-r', path.join(this.clrBuildDir, '*.dll'), + '-o', + `${AssemblyName}.obj`, + '-r', + this.disassemblyLoaderPath, + '-r', + path.join(this.clrBuildDir, 'aotsdk', '*.dll'), + '-r', + path.join(this.clrBuildDir, '*.dll'), '--initassembly:System.Private.CoreLib', '--initassembly:System.Private.StackTraceMetadata', '--initassembly:System.Private.TypeLoader', @@ -920,7 +928,9 @@ do() '--generateunmanagedentrypoints:System.Private.CoreLib', '--notrimwarn', '--noaotwarn', - ].concat(toolOptions).concat(toolSwitches); + ] + .concat(toolOptions) + .concat(toolSwitches); if (!buildToBinary) { ilcOptions.push('--nativelib', '--root:CompilerExplorer'); diff --git a/lib/compilers/elixir.ts b/lib/compilers/elixir.ts index c4087ee0d..d6ca0f78c 100644 --- a/lib/compilers/elixir.ts +++ b/lib/compilers/elixir.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; import {BaseCompiler} from '../base-compiler.js'; @@ -37,10 +37,7 @@ export class ElixirCompiler extends BaseCompiler { override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string): string[] { return [ '--eval', - '[input] = Code.required_files();' + - 'code = Code.compile_file(input)' + - '|> Enum.map(fn {_,code} -> :beam_disasm.file(code) end);' + - `:ok = File.write("${outputFilename}", inspect(code, pretty: true));`, + `[input] = Code.required_files();code = Code.compile_file(input)|> Enum.map(fn {_,code} -> :beam_disasm.file(code) end);:ok = File.write("${outputFilename}", inspect(code, pretty: true));`, ]; } diff --git a/lib/compilers/erlang.ts b/lib/compilers/erlang.ts index 66cc6af03..73d2ce989 100644 --- a/lib/compilers/erlang.ts +++ b/lib/compilers/erlang.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; import {BaseCompiler} from '../base-compiler.js'; @@ -38,12 +38,7 @@ export class ErlangCompiler extends BaseCompiler { return [ '-noshell', '-eval', - '{ok, Input} = init:get_argument(input),' + - "{ok, _, Output} = compile:file(Input, ['S', binary, no_line_info, report])," + - `{ok,Fd} = file:open("${outputFilename}", [write]),` + - 'beam_listing:module(Fd, Output),' + - 'file:close(Fd),' + - 'halt().', + `{ok, Input} = init:get_argument(input),{ok, _, Output} = compile:file(Input, ['S', binary, no_line_info, report]),{ok,Fd} = file:open("${outputFilename}", [write]),beam_listing:module(Fd, Output),file:close(Fd),halt().`, ]; } diff --git a/lib/compilers/erlangasm.ts b/lib/compilers/erlangasm.ts index 0aee2b0a2..fbfcd5d18 100644 --- a/lib/compilers/erlangasm.ts +++ b/lib/compilers/erlangasm.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; import {BaseCompiler} from '../base-compiler.js'; @@ -38,16 +38,7 @@ export class ErlangAsmCompiler extends BaseCompiler { return [ '-noshell', '-eval', - '{ok, Input} = init:get_argument(input),' + - "{ok, _, _} = compile:file(Input, ['S', binary, no_line_info, report])," + - `Output = "${outputFilename}",` + - '{ok,File}=epp:parse_file(Input,[]),' + - '{ok,Module,Binary}=compile:forms(File),' + - 'erts_debug:set_internal_state(available_internal_state, true),' + - 'erts_debug:set_internal_state(jit_asm_dump, true),' + - 'load_module(Module,Binary),' + - 'file:copy(atom_to_list(Module) ++ ".asm", Output),' + - 'halt().', + `{ok, Input} = init:get_argument(input),{ok, _, _} = compile:file(Input, ['S', binary, no_line_info, report]),Output = "${outputFilename}",{ok,File}=epp:parse_file(Input,[]),{ok,Module,Binary}=compile:forms(File),erts_debug:set_internal_state(available_internal_state, true),erts_debug:set_internal_state(jit_asm_dump, true),load_module(Module,Binary),file:copy(atom_to_list(Module) ++ ".asm", Output),halt().`, ]; } diff --git a/lib/compilers/ewarm.ts b/lib/compilers/ewarm.ts index ecb0afd6f..06131bef0 100644 --- a/lib/compilers/ewarm.ts +++ b/lib/compilers/ewarm.ts @@ -43,6 +43,6 @@ export class EWARMCompiler extends BaseCompiler { return []; } - return ['-lB', this.filename(outputFilename), '-o', this.filename(outputFilename + '.obj')]; + return ['-lB', this.filename(outputFilename), '-o', this.filename(`${outputFilename}.obj`)]; } } diff --git a/lib/compilers/ewavr.ts b/lib/compilers/ewavr.ts index cf19b3a7b..70d8eb310 100644 --- a/lib/compilers/ewavr.ts +++ b/lib/compilers/ewavr.ts @@ -45,6 +45,6 @@ export class EWAVRCompiler extends BaseCompiler { return []; } - return ['-lB', this.filename(outputFilename), '-o', this.filename(outputFilename + '.obj')]; + return ['-lB', this.filename(outputFilename), '-o', this.filename(`${outputFilename}.obj`)]; } } diff --git a/lib/compilers/fortran.ts b/lib/compilers/fortran.ts index 8234ffadf..7f3e9a9ab 100644 --- a/lib/compilers/fortran.ts +++ b/lib/compilers/fortran.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import * as fs from 'fs'; -import path from 'path'; +import * as fs from 'node:fs'; +import path from 'node:path'; import type {CompilationResult, ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import {SelectedLibraryVersion} from '../../types/libraries/libraries.interfaces.js'; @@ -46,7 +46,7 @@ export class FortranCompiler extends BaseCompiler { } getExactStaticLibNameAndPath(lib: string, libPaths: string[]): string { - const libFilename = 'lib' + lib + '.a'; + const libFilename = `lib${lib}.a`; // note: fortran doesn't use -llibname, // you have to add the full filename to the commandline instead @@ -97,7 +97,7 @@ export class FortranCompiler extends BaseCompiler { execOptions.customCwd = path.dirname(inputFilename); const result = await this.exec(compiler, options, execOptions); - const baseFilename = './' + path.basename(inputFilename); + const baseFilename = `./${path.basename(inputFilename)}`; return { ...result, stdout: utils.parseOutput(result.stdout, baseFilename), diff --git a/lib/compilers/gimple.ts b/lib/compilers/gimple.ts index 2d5db604c..76cdfec5b 100644 --- a/lib/compilers/gimple.ts +++ b/lib/compilers/gimple.ts @@ -21,7 +21,7 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import {BaseCompiler} from '../base-compiler.js'; diff --git a/lib/compilers/glsl.ts b/lib/compilers/glsl.ts index 8c12aee25..cdcfdd64d 100644 --- a/lib/compilers/glsl.ts +++ b/lib/compilers/glsl.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptions} from '../../types/compilation/compilation.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; diff --git a/lib/compilers/gnucobol.ts b/lib/compilers/gnucobol.ts index eb21171ba..18468d874 100644 --- a/lib/compilers/gnucobol.ts +++ b/lib/compilers/gnucobol.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -101,7 +101,7 @@ export class GnuCobolCompiler extends BaseCompiler { override getOutputFilename(dirPath: string, outputFilebase: string, key?: any): string { let filename; - if (key && key.backendOptions && key.backendOptions.customOutputFilename) { + if (key?.backendOptions?.customOutputFilename) { filename = key.backendOptions.customOutputFilename; } else if (key.filters.binary) { // note: interesting fact about gnucobol, if you name the outputfile output.s it will always output assembly @@ -114,9 +114,8 @@ export class GnuCobolCompiler extends BaseCompiler { if (dirPath) { return path.join(dirPath, filename); - } else { - return filename; } + return filename; } override getExecutableFilename(dirPath: string, outputFilebase: string) { diff --git a/lib/compilers/golang.ts b/lib/compilers/golang.ts index b62760c93..52556122e 100644 --- a/lib/compilers/golang.ts +++ b/lib/compilers/golang.ts @@ -203,7 +203,7 @@ export class GolangCompiler extends BaseCompiler { if (collisions > 0) { label += `_${collisions}`; } - usedLabels[label + ':'] = true; // record label use for later filtering + usedLabels[`${label}:`] = true; // record label use for later filtering return `${match[1]}${label}${match[3]}`; } @@ -242,11 +242,10 @@ export class GolangCompiler extends BaseCompiler { } if (filters.binary) { - return ['build', '-o', outputFilename, '-gcflags=' + unwrap(userOptions).join(' ')]; - } else { - // Add userOptions to -gcflags to preserve previous behavior. - return ['build', '-o', outputFilename, '-gcflags=-S ' + unwrap(userOptions).join(' ')]; + return ['build', '-o', outputFilename, `-gcflags=${unwrap(userOptions).join(' ')}`]; } + // Add userOptions to -gcflags to preserve previous behavior. + return ['build', '-o', outputFilename, `-gcflags=-S ${unwrap(userOptions).join(' ')}`]; } override filterUserOptions(userOptions: string[]) { diff --git a/lib/compilers/haskell.ts b/lib/compilers/haskell.ts index 843353deb..159888b21 100644 --- a/lib/compilers/haskell.ts +++ b/lib/compilers/haskell.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -75,7 +75,7 @@ export class HaskellCompiler extends BaseCompiler { override getSharedLibraryPathsAsArguments(libraries: SelectedLibraryVersion[]) { const libPathFlag = this.compiler.libpathFlag || '-L'; - return [libPathFlag + '.', ...this.getSharedLibraryPaths(libraries).map(path => libPathFlag + path)]; + return [`${libPathFlag}.`, ...this.getSharedLibraryPaths(libraries).map(path => libPathFlag + path)]; } override getArgumentParserClass(): any { diff --git a/lib/compilers/hook.ts b/lib/compilers/hook.ts index 4630e0766..3db2e8120 100644 --- a/lib/compilers/hook.ts +++ b/lib/compilers/hook.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type { CacheKey, @@ -96,7 +96,7 @@ export class HookCompiler extends BaseCompiler { } const match = text.match(instructionRegex); if (match) { - const lineNo = parseInt(match[1]); + const lineNo = Number.parseInt(match[1]); item.source = {line: lineNo, file: null}; lastLineNo = lineNo; continue; diff --git a/lib/compilers/jakt.ts b/lib/compilers/jakt.ts index 2a1c6d683..0fe6d84d4 100644 --- a/lib/compilers/jakt.ts +++ b/lib/compilers/jakt.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; diff --git a/lib/compilers/java.ts b/lib/compilers/java.ts index 5501b9e1c..e96c4c263 100644 --- a/lib/compilers/java.ts +++ b/lib/compilers/java.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import Semver from 'semver'; @@ -160,16 +160,15 @@ export class JavaCompiler extends BaseCompiler implements SimpleOutputFilenameCo didExecute: true, buildResult: compileResult, }; - } else { - return { - stdout: compileResult.stdout, - stderr: compileResult.stderr, - code: compileResult.code, - didExecute: false, - buildResult: compileResult, - timedOut: false, - }; } + return { + stdout: compileResult.stdout, + stderr: compileResult.stderr, + code: compileResult.code, + didExecute: false, + buildResult: compileResult, + timedOut: false, + }; } async getMainClassName(dirPath: string) { @@ -409,9 +408,8 @@ export class JavaCompiler extends BaseCompiler implements SimpleOutputFilenameCo firstSourceLine: methods.reduce((prev, method) => { if (method.startLine) { return prev === -1 ? method.startLine : Math.min(prev, method.startLine); - } else { - return prev; } + return prev; }, -1), methods: methods, textsBeforeMethod, diff --git a/lib/compilers/julia.ts b/lib/compilers/julia.ts index a6a83fb95..0826fad05 100644 --- a/lib/compilers/julia.ts +++ b/lib/compilers/julia.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {CompilationResult, ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; diff --git a/lib/compilers/ldc.ts b/lib/compilers/ldc.ts index 65ee6e599..c3384bbcd 100644 --- a/lib/compilers/ldc.ts +++ b/lib/compilers/ldc.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import semverParser from 'semver'; @@ -70,13 +70,13 @@ export class LDCCompiler extends BaseCompiler { } override getOutputFilename(dirPath: string, outputFilebase: string, key?: any): string { - if (key && key.filters && key.filters.binary) { + if (key?.filters?.binary) { return path.join(dirPath, 'output'); - } else if (key && key.filters && key.filters.binaryObject) { - return path.join(dirPath, 'output.o'); - } else { - return path.join(dirPath, 'output.s'); } + if (key?.filters?.binaryObject) { + return path.join(dirPath, 'output.o'); + } + return path.join(dirPath, 'output.s'); } override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { @@ -102,7 +102,7 @@ export class LDCCompiler extends BaseCompiler { override couldSupportASTDump(version: string) { const versionRegex = /\((\d\.\d+)\.\d+/; const versionMatch = versionRegex.exec(version); - return versionMatch ? semverParser.compare(versionMatch[1] + '.0', '1.4.0', true) >= 0 : false; + return versionMatch ? semverParser.compare(`${versionMatch[1]}.0`, '1.4.0', true) >= 0 : false; } override async generateAST(inputFilename: string, options: string[]): Promise { diff --git a/lib/compilers/llvm-mos.ts b/lib/compilers/llvm-mos.ts index 35b5fda00..1a98a85c5 100644 --- a/lib/compilers/llvm-mos.ts +++ b/lib/compilers/llvm-mos.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {CompilationResult, FiledataPair} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -68,8 +68,8 @@ export class LLVMMOSCompiler extends ClangCompiler { dynamicReloc: boolean, filters: ParseFiltersAndOutputOptions, ) { - if (!outputFilename.endsWith('.elf') && (await utils.fileExists(outputFilename + '.elf'))) { - outputFilename = outputFilename + '.elf'; + if (!outputFilename.endsWith('.elf') && (await utils.fileExists(`${outputFilename}.elf`))) { + outputFilename = `${outputFilename}.elf`; } intelAsm = false; diff --git a/lib/compilers/madpascal.ts b/lib/compilers/madpascal.ts index d084ba16f..eee90ed01 100644 --- a/lib/compilers/madpascal.ts +++ b/lib/compilers/madpascal.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -57,27 +57,24 @@ export class MadPascalCompiler extends BaseCompiler { const filename = `${outputFilebase}.a65`; if (dirPath) { return path.join(dirPath, filename); - } else { - return filename; } + return filename; } getAssemblerOutputFilename(dirPath: string, outputFilebase: string) { const filename = `${outputFilebase}.obx`; if (dirPath) { return path.join(dirPath, filename); - } else { - return filename; } + return filename; } getListingFilename(dirPath: string, outputFilebase: string) { const filename = `${outputFilebase}.lst`; if (dirPath) { return path.join(dirPath, filename); - } else { - return filename; } + return filename; } override getOutputFilename(dirPath: string, outputFilebase: string, key?: any): string { @@ -173,7 +170,7 @@ export class MadPascalCompiler extends BaseCompiler { const listingFilename = this.getListingFilename(tmpDir, this.outputFilebase); if (!(await utils.fileExists(listingFilename))) { - result.asm = ''; + result.asm = ``; return result; } diff --git a/lib/compilers/mlir.ts b/lib/compilers/mlir.ts index 1e20aa737..b26778304 100644 --- a/lib/compilers/mlir.ts +++ b/lib/compilers/mlir.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; diff --git a/lib/compilers/mrustc.ts b/lib/compilers/mrustc.ts index e929d87e6..accf14788 100644 --- a/lib/compilers/mrustc.ts +++ b/lib/compilers/mrustc.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; diff --git a/lib/compilers/nim.ts b/lib/compilers/nim.ts index dc2940c2e..723892611 100644 --- a/lib/compilers/nim.ts +++ b/lib/compilers/nim.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -48,15 +48,15 @@ export class NimCompiler extends BaseCompiler { } cacheDir(outputFilename: string) { - return outputFilename + '.cache'; + return `${outputFilename}.cache`; } override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { return [ '--debugger:native', // debugging info - '-o:' + outputFilename, //output file, only for js mode + `-o:${outputFilename}`, //output file, only for js mode '--nolinking', //disable linking, only compile to nimcache - '--nimcache:' + this.cacheDir(outputFilename), //output folder for the nimcache + `--nimcache:${this.cacheDir(outputFilename)}`, //output folder for the nimcache ]; } @@ -70,14 +70,14 @@ export class NimCompiler extends BaseCompiler { } expectedExtensionFromCommand(command: string) { - const isC = ['compile', 'compileToC', 'c'], - isCpp = ['compileToCpp', 'cpp', 'cc'], - isObjC = ['compileToOC', 'objc']; + const isC = ['compile', 'compileToC', 'c']; + const isCpp = ['compileToCpp', 'cpp', 'cc']; + const isObjC = ['compileToOC', 'objc']; if (isC.includes(command)) return '.c.o'; - else if (isCpp.includes(command)) return '.cpp.o'; - else if (isObjC.includes(command)) return '.m.o'; - else return null; + if (isCpp.includes(command)) return '.cpp.o'; + if (isObjC.includes(command)) return '.m.o'; + return null; } getCacheFile(options: string[], inputFilename: string, cacheDir: string) { @@ -87,7 +87,7 @@ export class NimCompiler extends BaseCompiler { const extension = this.expectedExtensionFromCommand(command); if (!extension) return null; const moduleName = path.basename(inputFilename); - const resultName = '@m' + moduleName + extension; + const resultName = `@m${moduleName}${extension}`; return path.join(cacheDir, resultName); } diff --git a/lib/compilers/nvcc.ts b/lib/compilers/nvcc.ts index cf2735e3c..0a5847fa8 100644 --- a/lib/compilers/nvcc.ts +++ b/lib/compilers/nvcc.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import * as fs from 'fs/promises'; -import Path from 'path'; +import * as fs from 'node:fs/promises'; +import Path from 'node:path'; import Semver from 'semver'; import _ from 'underscore'; @@ -114,18 +114,15 @@ export class NvccCompiler extends BaseCompiler { return result; } if (result.asmSize >= maxSize) { - result.asm = - ' ${maxSize} bytes)>`; + result.asm = ` ${maxSize} bytes)>`; return result; } if (postProcess.length > 0) { return await this.execPostProcess(result, postProcess, outputFilename, maxSize); - } else { - const contents = await fs.readFile(outputFilename, {encoding: 'utf8'}); - result.asm = contents.toString(); - return result; } + const contents = await fs.readFile(outputFilename, {encoding: 'utf8'}); + result.asm = contents.toString(); + return result; })() ).then(asm => { result.asm = typeof asm === 'string' ? asm : asm.asm; diff --git a/lib/compilers/nvcpp.ts b/lib/compilers/nvcpp.ts index d36366785..889b008b4 100644 --- a/lib/compilers/nvcpp.ts +++ b/lib/compilers/nvcpp.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import * as fs from 'fs/promises'; -import path from 'path'; +import * as fs from 'node:fs/promises'; +import path from 'node:path'; import {CompilationInfo, CompilationResult} from '../../types/compilation/compilation.interfaces.js'; import {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -44,10 +44,7 @@ export class NvcppCompiler extends BaseCompiler { constructor(info: PreliminaryCompilerInfo, env: CompilationEnvironment) { super(info, env); - this.cuobjdump = this.compilerProps( - 'compiler.' + this.compiler.id + '.cuobjdump', - undefined, - ); + this.cuobjdump = this.compilerProps(`compiler.${this.compiler.id}.cuobjdump`, undefined); this.deviceAsmParser = new SassAsmParser(this.compilerProps); diff --git a/lib/compilers/nvrtc.ts b/lib/compilers/nvrtc.ts index dcb828c64..01906f892 100644 --- a/lib/compilers/nvrtc.ts +++ b/lib/compilers/nvrtc.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import Path from 'path'; +import Path from 'node:path'; import Semver from 'semver'; diff --git a/lib/compilers/pascal-win.ts b/lib/compilers/pascal-win.ts index f861cd8ac..eb9ca2daa 100644 --- a/lib/compilers/pascal-win.ts +++ b/lib/compilers/pascal-win.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -85,10 +85,9 @@ export class PascalWinCompiler extends BaseCompiler { override filename(fn: string) { if (process.platform === 'linux' || process.platform === 'darwin') { - return 'Z:' + fn; - } else { - return super.filename(fn); + return `Z:${fn}`; } + return super.filename(fn); } override async objdump(outputFilename: string, result, maxSize: number, intelAsm: boolean) { @@ -106,7 +105,7 @@ export class PascalWinCompiler extends BaseCompiler { if (objResult.code === 0) { result.asm = objResult.stdout; } else { - result.asm = ''; + result.asm = ``; } return result; @@ -117,10 +116,7 @@ export class PascalWinCompiler extends BaseCompiler { await fs.writeFile( filename, // prettier-ignore - 'program prog;\n' + - 'uses ' + unitName + ' in \'' + unitPath + '\';\n' + - 'begin\n' + - 'end.\n', + `program prog;\nuses ${unitName} in \'${unitPath}\';\nbegin\nend.\n`, ); } @@ -131,7 +127,7 @@ export class PascalWinCompiler extends BaseCompiler { } else { const unitName = this.pasUtils.getUnitname(source); if (unitName) { - inputFilename = path.join(dirPath, unitName + '.pas'); + inputFilename = path.join(dirPath, `${unitName}.pas`); } else { inputFilename = path.join(dirPath, this.compileFilename); } diff --git a/lib/compilers/pascal.ts b/lib/compilers/pascal.ts index 4c77cfc11..a628f3aca 100644 --- a/lib/compilers/pascal.ts +++ b/lib/compilers/pascal.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -72,7 +72,7 @@ export class FPCCompiler extends BaseCompiler { override async postProcess(result, outputFilename: string, filters: ParseFiltersAndOutputOptions) { const userSourceFilename = result.inputFilename; const pasFilepath = path.join(result.dirPath, userSourceFilename); - const asmDumpFilepath = pasFilepath.substring(0, pasFilepath.length - 3) + 's'; + const asmDumpFilepath = `${pasFilepath.substring(0, pasFilepath.length - 3)}s`; return super.postProcess(result, asmDumpFilepath, filters); } @@ -92,8 +92,7 @@ export class FPCCompiler extends BaseCompiler { for (let j = 0; j < result.asm.length; ++j) { result.asm[j].text = this.demangler.demangleIfNeeded(result.asm[j].text); if ( - result.asm[j].source && - result.asm[j].source.file && + result.asm[j].source?.file && !result.asm[j].source.mainsource && this.isTheSameFileProbably(result.inputFilename, result.asm[j].source.file) ) { @@ -176,11 +175,10 @@ export class FPCCompiler extends BaseCompiler { if (furtherLookback === -1) break; if (endOfProc === -1) { - newSource = newSource + input.substring(furtherLookback) + '\n'; + newSource = `${newSource + input.substring(furtherLookback)}\n`; break; - } else { - newSource = newSource + input.substring(furtherLookback, endOfProc + 3) + '\n'; } + newSource = `${newSource + input.substring(furtherLookback, endOfProc + 3)}\n`; foundSourceAt = input.indexOf('/app/', endOfProc + 3); } @@ -196,21 +194,18 @@ export class FPCCompiler extends BaseCompiler { await fs.writeFile( filename, // prettier-ignore - 'program prog;\n' + - 'uses ' + unitName + ' in \'' + unitPath + '\';\n' + - 'begin\n' + - 'end.\n', + `program prog;\nuses ${unitName} in \'${unitPath}\';\nbegin\nend.\n`, ); } getMainSourceFilename(source: string) { let inputFilename; if (this.pasUtils.isProgram(source)) { - inputFilename = this.pasUtils.getProgName(source) + '.dpr'; + inputFilename = `${this.pasUtils.getProgName(source)}.dpr`; } else { const unitName = this.pasUtils.getUnitname(source); if (unitName) { - inputFilename = unitName + '.pas'; + inputFilename = `${unitName}.pas`; } else { inputFilename = this.compileFilename; } @@ -256,7 +251,7 @@ export class FPCCompiler extends BaseCompiler { execOptions.customCwd = dirPath; if (this.nasmPath) { execOptions.env = _.clone(process.env) as Record; - execOptions.env.PATH = execOptions.env.PATH + ':' + this.nasmPath; + execOptions.env.PATH = `${execOptions.env.PATH}:${this.nasmPath}`; } if (!alreadyHasDPR) { @@ -266,7 +261,7 @@ export class FPCCompiler extends BaseCompiler { } options.pop(); - options.push('-FE' + dirPath, '-B', projectFile); + options.push(`-FE${dirPath}`, '-B', projectFile); return this.parseOutput(await this.exec(compiler, options, execOptions), inputFilename, dirPath); } @@ -298,14 +293,13 @@ export class FPCCompiler extends BaseCompiler { if (Number.isNaN(Number(valueInBrackets))) { return ` .file ${currentFileId} "${valueInBrackets}"`; - } else { - return ` .loc ${currentFileId} ${valueInBrackets} 0`; } - } else if (asm.startsWith('.Le')) { - return ' .cfi_endproc'; - } else { - return false; + return ` .loc ${currentFileId} ${valueInBrackets} 0`; } + if (asm.startsWith('.Le')) { + return ' .cfi_endproc'; + } + return false; } tryGetFilenumber(asm: string, files: Record) { @@ -324,7 +318,7 @@ export class FPCCompiler extends BaseCompiler { if (Number.isNaN(Number(valueInBrackets))) { if (!files[valueInBrackets]) { let maxFileId = _.max(files); - if (maxFileId === -Infinity) { + if (maxFileId === Number.NEGATIVE_INFINITY) { maxFileId = 0; } diff --git a/lib/compilers/pony.ts b/lib/compilers/pony.ts index 96f85bff8..033e95718 100644 --- a/lib/compilers/pony.ts +++ b/lib/compilers/pony.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {CompilationResult, ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import {LLVMIrBackendOptions} from '../../types/compilation/ir.interfaces.js'; diff --git a/lib/compilers/ptxas.ts b/lib/compilers/ptxas.ts index 05e97da2b..355df3ec2 100644 --- a/lib/compilers/ptxas.ts +++ b/lib/compilers/ptxas.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {CompilationResult, ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -49,14 +49,14 @@ export class PtxAssembler extends BaseCompiler { parsePtxOutput(lines: string, inputFilename: string, pathPrefix: string) { const re = /^ptxas\s*, line (\d+);(.*)/; const result: ResultLine[] = []; - utils.eachLine(lines, function (line) { + utils.eachLine(lines, line => { if (pathPrefix) line = line.replace(pathPrefix, ''); if (inputFilename) { line = line.split(inputFilename).join(''); if (inputFilename.indexOf('./') === 0) { - line = line.split('/home/ubuntu/' + inputFilename.substring(2)).join(''); - line = line.split('/home/ce/' + inputFilename.substring(2)).join(''); + line = line.split(`/home/ubuntu/${inputFilename.substring(2)}`).join(''); + line = line.split(`/home/ce/${inputFilename.substring(2)}`).join(''); } } if (line !== null) { @@ -66,7 +66,7 @@ export class PtxAssembler extends BaseCompiler { lineObj.text = `:${match[1]} ${match[2].trim()}`; lineObj.tag = { severity: 0, - line: parseInt(match[1]), + line: Number.parseInt(match[1]), column: 0, text: match[2].trim(), }; @@ -107,8 +107,8 @@ export class PtxAssembler extends BaseCompiler { return { ...result, inputFilename, - stdout: this.parsePtxOutput(result.stdout, './' + this.compileFilename, 'no idea what to put here'), - stderr: this.parsePtxOutput(result.stderr, './' + this.compileFilename, 'no idea what to put here'), + stdout: this.parsePtxOutput(result.stdout, `./${this.compileFilename}`, 'no idea what to put here'), + stderr: this.parsePtxOutput(result.stderr, `./${this.compileFilename}`, 'no idea what to put here'), }; } @@ -132,7 +132,7 @@ export class PtxAssembler extends BaseCompiler { if (objResult.code === 0) { result.objdumpTime = objResult.execTime; } else { - result.asm = ''; + result.asm = ``; } return result; } diff --git a/lib/compilers/python.ts b/lib/compilers/python.ts index 68c83e7ab..46ab42601 100644 --- a/lib/compilers/python.ts +++ b/lib/compilers/python.ts @@ -60,7 +60,7 @@ export class PythonCompiler extends BaseCompiler { const match = line.match(lineRe); if (match) { - const lineno = parseInt(match[1]); + const lineno = Number.parseInt(match[1]); sourceLoc = {line: lineno, file: null}; lastLineNo = lineno; } else if (line) { diff --git a/lib/compilers/pythran.ts b/lib/compilers/pythran.ts index 5f6fe381a..5c043b0a9 100644 --- a/lib/compilers/pythran.ts +++ b/lib/compilers/pythran.ts @@ -1,4 +1,4 @@ -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -33,7 +33,7 @@ export class PythranCompiler extends BaseCompiler { const execOptions = super.getDefaultExecOptions(); if (this.cpp_compiler_root) { - execOptions.env.PATH = execOptions.env.PATH + ':' + path.join(this.cpp_compiler_root, 'bin'); + execOptions.env.PATH = `${execOptions.env.PATH}:${path.join(this.cpp_compiler_root, 'bin')}`; } return execOptions; @@ -50,7 +50,7 @@ export class PythranCompiler extends BaseCompiler { } override getCompilerResultLanguageId(filters?: ParseFiltersAndOutputOptions): string | undefined { - if (filters !== undefined && filters.binary) return 'asm'; - else return 'cppp'; + if (filters?.binary) return 'asm'; + return 'cppp'; } } diff --git a/lib/compilers/r8.ts b/lib/compilers/r8.ts index e1e57647d..872eecefc 100644 --- a/lib/compilers/r8.ts +++ b/lib/compilers/r8.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -167,9 +167,9 @@ export class R8Compiler extends D8Compiler implements SimpleOutputFilenameCompil if (this.lang.id === 'android-kotlin') { libArgs.push( '--lib', - this.kotlinLibPath + '/kotlin-stdlib.jar', + `${this.kotlinLibPath}/kotlin-stdlib.jar`, '--lib', - this.kotlinLibPath + '/annotations-13.0.jar', + `${this.kotlinLibPath}/annotations-13.0.jar`, ); } return libArgs; diff --git a/lib/compilers/racket.ts b/lib/compilers/racket.ts index b2a683c85..12f733aef 100644 --- a/lib/compilers/racket.ts +++ b/lib/compilers/racket.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -199,9 +199,9 @@ export class RacketCompiler extends BaseCompiler { execOptions.maxOutput = 1024 * 1024 * 1024; // Dump various optimisation passes during compilation - execOptions.env['PLT_LINKLET_SHOW_CP0'] = '1'; - execOptions.env['PLT_LINKLET_SHOW_PASSES'] = 'all'; - execOptions.env['PLT_LINKLET_SHOW_ASSEMBLY'] = '1'; + execOptions.env.PLT_LINKLET_SHOW_CP0 = '1'; + execOptions.env.PLT_LINKLET_SHOW_PASSES = 'all'; + execOptions.env.PLT_LINKLET_SHOW_ASSEMBLY = '1'; const compileStart = performance.now(); const output = await this.runCompiler(this.compiler.exe, options, pipelineFile, execOptions); diff --git a/lib/compilers/rga.ts b/lib/compilers/rga.ts index d9a21857f..e5d01da43 100644 --- a/lib/compilers/rga.ts +++ b/lib/compilers/rga.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -203,7 +203,7 @@ Please supply an ASIC from the following options:`, const files = await fs.readdir(outputDir, {encoding: 'utf8'}); for (const file of files) { - if (file.startsWith((asicSelection.asic as string) + '_output')) { + if (file.startsWith(`${asicSelection.asic as string}_output`)) { await fs.rename(path.join(outputDir, file), outputFile); registerAnalysisFile = path.join(outputDir, file.replace('output', 'livereg').replace('.s', '.txt')); diff --git a/lib/compilers/ruby.ts b/lib/compilers/ruby.ts index e12d64ef5..6b7a5fd0d 100644 --- a/lib/compilers/ruby.ts +++ b/lib/compilers/ruby.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -64,12 +64,12 @@ export class RubyCompiler extends BaseCompiler { const match = line.match(lineRe); if (match) { - lastLineNo = parseInt(match[1]); + lastLineNo = Number.parseInt(match[1]); } else if (line) { const fileMatch = line.match(fileRe); if (fileMatch) { lastFile = fileMatch[1]; - lastLineNo = parseInt(fileMatch[2]); + lastLineNo = Number.parseInt(fileMatch[2]); } } else { lastFile = null; diff --git a/lib/compilers/rust.ts b/lib/compilers/rust.ts index 253880b74..af21f9026 100644 --- a/lib/compilers/rust.ts +++ b/lib/compilers/rust.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {SemVer} from 'semver'; import _ from 'underscore'; @@ -182,9 +182,8 @@ export class RustCompiler extends BaseCompiler { if (this.buildenvsetup) { const libraryDetails = await this.getRequiredLibraryVersions(key.libraries); return this.buildenvsetup.setup(key, dirPath, libraryDetails); - } else { - return []; } + return []; } override fixIncompatibleOptions( diff --git a/lib/compilers/rustc-cg-gcc.ts b/lib/compilers/rustc-cg-gcc.ts index 85b6bfc73..16f29c304 100644 --- a/lib/compilers/rustc-cg-gcc.ts +++ b/lib/compilers/rustc-cg-gcc.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -60,7 +60,7 @@ export class RustcCgGCCCompiler extends RustCompiler { } override getGccDumpOptions(gccDumpOptions, outputFilename: string) { - return ['-C', 'llvm-args=' + super.getGccDumpOptions(gccDumpOptions, outputFilename).join(' ')]; + return ['-C', `llvm-args=${super.getGccDumpOptions(gccDumpOptions, outputFilename).join(' ')}`]; } override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string, userOptions?: string[]) { @@ -70,7 +70,7 @@ export class RustcCgGCCCompiler extends RustCompiler { let options = [ '-Z', - 'codegen-backend=' + path.join(toolroot, 'lib', 'librustc_codegen_gcc.so'), + `codegen-backend=${path.join(toolroot, 'lib', 'librustc_codegen_gcc.so')}`, '--sysroot', path.join(toolroot, 'sysroot'), ]; diff --git a/lib/compilers/solidity-zksync.ts b/lib/compilers/solidity-zksync.ts index eafe15700..53ced4d93 100644 --- a/lib/compilers/solidity-zksync.ts +++ b/lib/compilers/solidity-zksync.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {BaseCompiler} from '../base-compiler.js'; @@ -62,7 +62,7 @@ export class SolidityZKsyncCompiler extends BaseCompiler { const combinedJson = JSON.parse(result.asm); const asm: any[] = []; for (const build of Object.values(combinedJson.contracts) as JSON[]) { - asm.push({text: build['asm']}); + asm.push({text: build.asm}); } return {asm}; } diff --git a/lib/compilers/solidity.ts b/lib/compilers/solidity.ts index 0c0a9f74b..8182e413d 100644 --- a/lib/compilers/solidity.ts +++ b/lib/compilers/solidity.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import * as fs from 'fs'; -import path from 'path'; +import * as fs from 'node:fs'; +import path from 'node:path'; import Semver from 'semver'; @@ -115,20 +115,18 @@ export class SolidityCompiler extends BaseCompiler { return node.name === 'FunctionDefinition'; }) .map(node => { - const [begin, length] = node.src.split(':').map(x => parseInt(x)); + const [begin, length] = node.src.split(':').map(x => Number.parseInt(x)); let name = node.attributes.isConstructor ? 'constructor' : node.attributes.name; // encode the args into the name so we can // differentiate between overloads if (node.children[0].children.length > 0) { - name += - '_' + - node.children[0].children - .map(paramNode => { - return paramNode.attributes.type; - }) - .join('_'); + name += `_${node.children[0].children + .map(paramNode => { + return paramNode.attributes.type; + }) + .join('_')}`; } return { @@ -147,20 +145,18 @@ export class SolidityCompiler extends BaseCompiler { return node.nodeType === 'FunctionDefinition'; }) .map(node => { - const [begin, length] = node.src.split(':').map(x => parseInt(x)); + const [begin, length] = node.src.split(':').map(x => Number.parseInt(x)); let name = node.kind === 'constructor' ? 'constructor' : node.name; // encode the args into the name so we can // differentiate between overloads if (node.parameters.parameters.length > 0) { - name += - '_' + - node.parameters.parameters - .map(paramNode => { - return paramNode.typeName.name; - }) - .join('_'); + name += `_${node.parameters.parameters + .map(paramNode => { + return paramNode.typeName.name; + }) + .join('_')}`; } return { @@ -179,7 +175,7 @@ export class SolidityCompiler extends BaseCompiler { const generatedSources = {}; for (const generatedSource of generatedSourcesData) { generatedSources[generatedSource.id] = generatedSource.ast.statements.map(statement => { - const [begin, length] = statement.src.split(':').map(x => parseInt(x)); + const [begin, length] = statement.src.split(':').map(x => Number.parseInt(x)); return { name: statement.name, begin: begin, @@ -272,11 +268,11 @@ export class SolidityCompiler extends BaseCompiler { (Object.entries(data.asm['.data']) as [string, any][]).map(([id, {'.code': code}]) => { // some .data sections do not contain embedded .code if (code === undefined) return []; - else return [{text: `\t${id}:`}, processOpcodes(code, '\t', generatedSourcesRuntime)]; + return [{text: `\t${id}:`}, processOpcodes(code, '\t', generatedSourcesRuntime)]; }), ]; }) - .flat(Infinity), + .flat(Number.POSITIVE_INFINITY), }; } } diff --git a/lib/compilers/spice.ts b/lib/compilers/spice.ts index 717d2e1ba..c5f7b0dcc 100644 --- a/lib/compilers/spice.ts +++ b/lib/compilers/spice.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import Semver from 'semver'; import _ from 'underscore'; @@ -116,7 +116,7 @@ export class SpiceCompiler extends BaseCompiler { override getIrOutputFilename(inputFilename: string): string { const dirPath = path.dirname(inputFilename); - return path.join(dirPath, 'example-ir-code' + this.optLevelSuffix + '.ll'); + return path.join(dirPath, `example-ir-code${this.optLevelSuffix}.ll`); } override getObjdumpOutputFilename(inputFilename: string): string { diff --git a/lib/compilers/spirv-tools.ts b/lib/compilers/spirv-tools.ts index 54a5b87e2..cd600dd2b 100644 --- a/lib/compilers/spirv-tools.ts +++ b/lib/compilers/spirv-tools.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -161,7 +161,7 @@ export class SPIRVToolsCompiler extends BaseCompiler { return result; } - const spvasmFilename = path.join(sourceDir, this.outputFilebase + '.spvasm'); + const spvasmFilename = path.join(sourceDir, `${this.outputFilebase}.spvasm`); const disassemblerFlags = [spvBinFilename, '-o', spvasmFilename]; // Will likely never fail diff --git a/lib/compilers/spirv.ts b/lib/compilers/spirv.ts index e32e0d3f9..bae39f65d 100644 --- a/lib/compilers/spirv.ts +++ b/lib/compilers/spirv.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {ConfiguredOverrides} from '../../types/compilation/compiler-overrides.interfaces.js'; @@ -107,7 +107,7 @@ export class SPIRVCompiler extends BaseCompiler { override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { const sourceDir = path.dirname(outputFilename); - const bitcodeFilename = path.join(sourceDir, this.outputFilebase + '.bc'); + const bitcodeFilename = path.join(sourceDir, `${this.outputFilebase}.bc`); return ['-cc1', '-debug-info-kind=limited', '-dwarf-version=5', '-debugger-tuning=gdb', '-o', bitcodeFilename]; } @@ -126,7 +126,7 @@ export class SPIRVCompiler extends BaseCompiler { execOptions: ExecutionOptionsWithEnv, ) { const sourceDir = path.dirname(inputFilename); - const bitcodeFilename = path.join(sourceDir, this.outputFilebase + '.bc'); + const bitcodeFilename = path.join(sourceDir, `${this.outputFilebase}.bc`); if (!execOptions) { execOptions = this.getDefaultExecOptions(); @@ -142,7 +142,7 @@ export class SPIRVCompiler extends BaseCompiler { return result; } - const spvBinFilename = path.join(sourceDir, this.outputFilebase + '.spv'); + const spvBinFilename = path.join(sourceDir, `${this.outputFilebase}.spv`); const translatorFlags = ['-spirv-debug', bitcodeFilename, '-o', spvBinFilename]; const spvBin = await this.exec(this.translatorPath, translatorFlags, execOptions); @@ -153,7 +153,7 @@ export class SPIRVCompiler extends BaseCompiler { return result; } - const spvasmFilename = path.join(sourceDir, this.outputFilebase + '.spvasm'); + const spvasmFilename = path.join(sourceDir, `${this.outputFilebase}.spvasm`); const disassemblerFlags = [spvBinFilename, '-o', spvasmFilename]; const spvasmOutput = await this.exec(this.disassemblerPath, disassemblerFlags, execOptions); @@ -180,7 +180,7 @@ export class SPIRVCompiler extends BaseCompiler { execOptions.customCwd = path.dirname(inputFilename); const sourceDir = path.dirname(inputFilename); - const outputFile = path.join(sourceDir, this.outputFilebase + '.bc'); + const outputFile = path.join(sourceDir, `${this.outputFilebase}.bc`); const newOptions = options; newOptions.concat('-S'); diff --git a/lib/compilers/tic2000.ts b/lib/compilers/tic2000.ts index b641cd355..1376c498b 100644 --- a/lib/compilers/tic2000.ts +++ b/lib/compilers/tic2000.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -42,7 +42,7 @@ export class TIC2000 extends BaseCompiler { } override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { - const options = ['-g', '-c', '-n', '--output_file=' + outputFilename]; + const options = ['-g', '-c', '-n', `--output_file=${outputFilename}`]; filters.preProcessLines = this.preProcessLines.bind(this); @@ -63,7 +63,7 @@ export class TIC2000 extends BaseCompiler { if (match) { // Add two lines stating the file and location to allow parsing the source location by the standard // parser - asmLines.splice(i, 0, ' .file 1 ' + match[1], ' .loc 1 ' + match[2] + ' ' + match[3]); + asmLines.splice(i, 0, ` .file 1 ${match[1]}`, ` .loc 1 ${match[2]} ${match[3]}`); i += 2; } } diff --git a/lib/compilers/tinyc.ts b/lib/compilers/tinyc.ts index 967f8d688..9cebe4527 100644 --- a/lib/compilers/tinyc.ts +++ b/lib/compilers/tinyc.ts @@ -36,12 +36,11 @@ export class TinyCCompiler extends BaseCompiler { override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string, userOptions?: string[]) { if (_.some(unwrap(userOptions), opt => opt === '--help' || opt === '-h' || opt === '-hh')) { return []; - } else { - if (!_.some(unwrap(userOptions), opt => opt === '-E')) { - filters.binary = true; - } - return ['-g', '-o', this.filename(outputFilename)]; } + if (!_.some(unwrap(userOptions), opt => opt === '-E')) { + filters.binary = true; + } + return ['-g', '-o', this.filename(outputFilename)]; } override filterUserOptions(userOptions: string[]) { diff --git a/lib/compilers/toit.ts b/lib/compilers/toit.ts index 19a73bd6d..47909dbba 100644 --- a/lib/compilers/toit.ts +++ b/lib/compilers/toit.ts @@ -41,7 +41,7 @@ export class ToitCompiler extends BaseCompiler { } cacheDir(outputFilename: string) { - return outputFilename + '.cache'; + return `${outputFilename}.cache`; } override optionsForFilter( diff --git a/lib/compilers/turboc.ts b/lib/compilers/turboc.ts index b404ce5e2..80c6e6ca4 100644 --- a/lib/compilers/turboc.ts +++ b/lib/compilers/turboc.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {SelectedLibraryVersion} from '../../types/libraries/libraries.interfaces.js'; import {logger} from '../logger.js'; diff --git a/lib/compilers/typescript-native.ts b/lib/compilers/typescript-native.ts index 08b8b51df..a68cb3ea6 100644 --- a/lib/compilers/typescript-native.ts +++ b/lib/compilers/typescript-native.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import Semver from 'semver'; @@ -82,7 +82,7 @@ export class TypeScriptNativeCompiler extends BaseCompiler { } if (this.tscNewOutput) { - addOpts.push('-o=' + this.filename(outputFilename)); + addOpts.push(`-o=${this.filename(outputFilename)}`); } return addOpts; @@ -106,7 +106,7 @@ export class TypeScriptNativeCompiler extends BaseCompiler { ) { const newOptions = options.filter(e => !e.startsWith('--emit=') && !e.startsWith('-o=')); if (this.tscNewOutput) { - newOptions.push('-o=' + this.getIrOutputFilename(inputFilename, filters)); + newOptions.push(`-o=${this.getIrOutputFilename(inputFilename, filters)}`); } return await super.generateIR(inputFilename, newOptions, irOptions, produceCfg, filters); @@ -127,7 +127,7 @@ export class TypeScriptNativeCompiler extends BaseCompiler { override async handleInterpreting(key: CacheKey, executeParameters: ExecutableExecutionOptions) { executeParameters.args = [ '--emit=jit', - this.tscSharedLib ? '--shared-libs=' + this.tscSharedLib : '-nogc', + this.tscSharedLib ? `--shared-libs=${this.tscSharedLib}` : '-nogc', ...executeParameters.args, ]; diff --git a/lib/compilers/v.ts b/lib/compilers/v.ts index 152816aec..7b2276efb 100644 --- a/lib/compilers/v.ts +++ b/lib/compilers/v.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {CompilationResult, ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -91,7 +91,7 @@ export class VCompiler extends BaseCompiler { } override getOutputFilename(dirPath: string, outputFilebase: string, key?: any): string { - return path.join(dirPath, 'output' + this.outputFileExt); + return path.join(dirPath, `output${this.outputFileExt}`); } override async runCompiler( @@ -106,8 +106,8 @@ export class VCompiler extends BaseCompiler { } const tmpDir = path.dirname(inputFilename); - execOptions.env['VMODULES'] = path.join(tmpDir, '.vmodules'); - execOptions.env['VTMP'] = tmpDir; + execOptions.env.VMODULES = path.join(tmpDir, '.vmodules'); + execOptions.env.VTMP = tmpDir; if (!execOptions.customCwd) { execOptions.customCwd = tmpDir; @@ -134,7 +134,7 @@ export class VCompiler extends BaseCompiler { case 'c': case 'go': case 'wasm': { - return '.' + backend; + return `.${backend}`; } case 'js': case 'js_node': diff --git a/lib/compilers/v8.ts b/lib/compilers/v8.ts index 9a785ec23..92784efa8 100644 --- a/lib/compilers/v8.ts +++ b/lib/compilers/v8.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -41,12 +41,12 @@ export class V8Compiler extends BaseCompiler { } override getIrOutputFilename(inputFilename: string): string { - return this.filename(path.dirname(inputFilename) + '/code.asm'); + return this.filename(`${path.dirname(inputFilename)}/code.asm`); } public override getOutputFilename(dirPath: string, outputFilebase: string, key?: any) { let filename; - if (key && key.backendOptions && key.backendOptions.customOutputFilename) { + if (key?.backendOptions?.customOutputFilename) { filename = key.backendOptions.customOutputFilename; } else { filename = 'code.asm'; @@ -54,9 +54,8 @@ export class V8Compiler extends BaseCompiler { if (dirPath) { return path.join(dirPath, filename); - } else { - return filename; } + return filename; } override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { diff --git a/lib/compilers/vala.ts b/lib/compilers/vala.ts index 161873f22..5f311c569 100644 --- a/lib/compilers/vala.ts +++ b/lib/compilers/vala.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; diff --git a/lib/compilers/wasmtime.ts b/lib/compilers/wasmtime.ts index 535c90547..95d744c0a 100644 --- a/lib/compilers/wasmtime.ts +++ b/lib/compilers/wasmtime.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; import {BaseCompiler} from '../base-compiler.js'; diff --git a/lib/compilers/win32-mingw-clang.ts b/lib/compilers/win32-mingw-clang.ts index 6be35bb14..146ab6bba 100644 --- a/lib/compilers/win32-mingw-clang.ts +++ b/lib/compilers/win32-mingw-clang.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {BuildResult, BypassCache, CacheKey, CompilationResult} from '../../types/compilation/compilation.interfaces.js'; import {ExecutableExecutionOptions} from '../../types/execution/execution.interfaces.js'; diff --git a/lib/compilers/win32-mingw-gcc.ts b/lib/compilers/win32-mingw-gcc.ts index 01788e33f..c2c8e2c48 100644 --- a/lib/compilers/win32-mingw-gcc.ts +++ b/lib/compilers/win32-mingw-gcc.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {BuildResult, BypassCache, CacheKey, CompilationResult} from '../../types/compilation/compilation.interfaces.js'; import {ExecutableExecutionOptions} from '../../types/execution/execution.interfaces.js'; diff --git a/lib/compilers/win32.ts b/lib/compilers/win32.ts index 4e371de0a..fd37a65fc 100644 --- a/lib/compilers/win32.ts +++ b/lib/compilers/win32.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import _ from 'underscore'; @@ -57,7 +57,7 @@ export class Win32Compiler extends BaseCompiler { } override getExecutableFilename(dirPath: string, outputFilebase: string, key?: CacheKey) { - return this.getOutputFilename(dirPath, outputFilebase, key) + '.exe'; + return `${this.getOutputFilename(dirPath, outputFilebase, key)}.exe`; } override getObjdumpOutputFilename(defaultOutputFilename: string) { @@ -86,7 +86,7 @@ export class Win32Compiler extends BaseCompiler { override getStaticLibraryLinks(libraries: SelectedLibraryVersion[]) { return super.getSortedStaticLibraries(libraries).map(lib => { - return '"' + lib + '.lib"'; + return `"${lib}.lib"`; }); } @@ -142,7 +142,7 @@ export class Win32Compiler extends BaseCompiler { override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string, userOptions?: string[]) { if (filters.binary) { - const mapFilename = outputFilename + '.map'; + const mapFilename = `${outputFilename}.map`; const mapFileReader = new MapFileReaderVS(mapFilename); filters.preProcessBinaryAsmLines = asmLines => { @@ -155,29 +155,27 @@ export class Win32Compiler extends BaseCompiler { return [ '/nologo', '/FA', - '/Fa' + this.filename(outputFilename.replace(/\.exe$/, '')), - '/Fo' + this.filename(outputFilename.replace(/\.exe$/, '') + '.obj'), - '/Fm' + this.filename(mapFilename), - '/Fe' + this.filename(this.getExecutableFilename(path.dirname(outputFilename), 'output')), - ]; - } else { - return [ - '/nologo', - '/FA', - '/c', - '/Fa' + this.filename(outputFilename), - '/Fo' + this.filename(outputFilename + '.obj'), + `/Fa${this.filename(outputFilename.replace(/\.exe$/, ''))}`, + `/Fo${this.filename(`${outputFilename.replace(/\.exe$/, '')}.obj`)}`, + `/Fm${this.filename(mapFilename)}`, + `/Fe${this.filename(this.getExecutableFilename(path.dirname(outputFilename), 'output'))}`, ]; } + return [ + '/nologo', + '/FA', + '/c', + `/Fa${this.filename(outputFilename)}`, + `/Fo${this.filename(`${outputFilename}.obj`)}`, + ]; } override async processAsm(result, filters: ParseFiltersAndOutputOptions) { if (filters.binary) { filters.dontMaskFilenames = true; return this.binaryAsmParser.process(result.asm, filters); - } else { - return this.asm.process(result.asm, filters); } + return this.asm.process(result.asm, filters); } override exec(compiler: string, args: string[], options_: ExecutionOptions) { @@ -185,10 +183,10 @@ export class Win32Compiler extends BaseCompiler { options.env = Object.assign({}, options.env); if (this.compiler.includePath) { - options.env['INCLUDE'] = this.compiler.includePath; + options.env.INCLUDE = this.compiler.includePath; } if (this.compiler.libPath) { - options.env['LIB'] = this.compiler.libPath.join(';'); + options.env.LIB = this.compiler.libPath.join(';'); } for (const [env, to] of this.compiler.envVars) { options.env[env] = to; diff --git a/lib/compilers/wine-vc.ts b/lib/compilers/wine-vc.ts index 6c0691ab2..3dd758b86 100644 --- a/lib/compilers/wine-vc.ts +++ b/lib/compilers/wine-vc.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -47,7 +47,7 @@ export class WineVcCompiler extends BaseCompiler { } override filename(fn: string) { - return 'Z:' + fn; + return `Z:${fn}`; } override async runCompiler( @@ -73,7 +73,7 @@ export class WineVcCompiler extends BaseCompiler { } override getExecutableFilename(dirPath: string, outputFilebase: string) { - return this.getOutputFilename(dirPath, outputFilebase) + '.exe'; + return `${this.getOutputFilename(dirPath, outputFilebase)}.exe`; } override getObjdumpOutputFilename(defaultOutputFilename: string) { @@ -86,7 +86,7 @@ export class WineVcCompiler extends BaseCompiler { override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string) { if (filters.binary) { - const mapFilename = outputFilename + '.map'; + const mapFilename = `${outputFilename}.map`; const mapFileReader = new MapFileReaderVS(mapFilename); filters.preProcessBinaryAsmLines = (asmLines: string[]) => { @@ -99,19 +99,18 @@ export class WineVcCompiler extends BaseCompiler { return [ '/nologo', '/FA', - '/Fa' + this.filename(outputFilename), - '/Fo' + this.filename(outputFilename + '.obj'), - '/Fm' + this.filename(mapFilename), - '/Fe' + this.filename(this.getExecutableFilename(path.dirname(outputFilename), 'output')), - ]; - } else { - return [ - '/nologo', - '/FA', - '/c', - '/Fa' + this.filename(outputFilename), - '/Fo' + this.filename(outputFilename + '.obj'), + `/Fa${this.filename(outputFilename)}`, + `/Fo${this.filename(`${outputFilename}.obj`)}`, + `/Fm${this.filename(mapFilename)}`, + `/Fe${this.filename(this.getExecutableFilename(path.dirname(outputFilename), 'output'))}`, ]; } + return [ + '/nologo', + '/FA', + '/c', + `/Fa${this.filename(outputFilename)}`, + `/Fo${this.filename(`${outputFilename}.obj`)}`, + ]; } } diff --git a/lib/compilers/wsl-vc.ts b/lib/compilers/wsl-vc.ts index 039d9f826..240459e5a 100644 --- a/lib/compilers/wsl-vc.ts +++ b/lib/compilers/wsl-vc.ts @@ -25,8 +25,8 @@ // The main difference from wine-vc.js is that we translate // compiler path from Unix mounted volume (/mnt/c/tmp) to Windows (c:/tmp) -import os from 'os'; -import path from 'path'; +import os from 'node:os'; +import path from 'node:path'; import type {ExecutionOptions, ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -61,13 +61,13 @@ export class WslVcCompiler extends Win32VcCompiler { const options = Object.assign({}, options_); options.env = Object.assign({}, options.env); - let old_env = options.env['WSLENV']; + let old_env = options.env.WSLENV; if (old_env) { - old_env = ':' + old_env; + old_env = `:${old_env}`; } else { old_env = ''; } - options.env['WSLENV'] = 'INCLUDE:LIB' + old_env; + options.env.WSLENV = `INCLUDE:LIB${old_env}`; return super.exec(compiler, args, options); } diff --git a/lib/compilers/wyrm.ts b/lib/compilers/wyrm.ts index 6ac761ba8..310a91e59 100644 --- a/lib/compilers/wyrm.ts +++ b/lib/compilers/wyrm.ts @@ -21,8 +21,8 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import fs from 'fs/promises'; -import path from 'path'; +import fs from 'node:fs/promises'; +import path from 'node:path'; import {ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; diff --git a/lib/compilers/ylc.ts b/lib/compilers/ylc.ts index 47e56c093..43fbd9321 100644 --- a/lib/compilers/ylc.ts +++ b/lib/compilers/ylc.ts @@ -1,4 +1,4 @@ -import path from 'path'; +import path from 'node:path'; import {ConfiguredOverrides} from '../../types/compilation/compiler-overrides.interfaces.js'; import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js'; @@ -15,7 +15,7 @@ export class YLCCompiler extends BaseCompiler { } override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string, userOptions: string[]) { - return ['-o=' + this.filename(outputFilename)]; + return [`-o=${this.filename(outputFilename)}`]; } override getArgumentParserClass() { @@ -71,7 +71,7 @@ export class YLCCompiler extends BaseCompiler { return this.orderArguments( options, - '-in=' + inputFilename, + `-in=${inputFilename}`, libIncludes, libOptions, libPathsAsFlags, diff --git a/lib/compilers/z88dk.ts b/lib/compilers/z88dk.ts index 6364ae58d..b5dbcfcc3 100644 --- a/lib/compilers/z88dk.ts +++ b/lib/compilers/z88dk.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import type {ExecutionOptions, ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js'; import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js'; @@ -58,9 +58,9 @@ export class z88dkCompiler extends BaseCompiler { public override getOutputFilename(dirPath: string, outputFilebase: string, key?: any): string { let filename; - if (key && key.backendOptions && key.backendOptions.customOutputFilename) { + if (key?.backendOptions?.customOutputFilename) { filename = key.backendOptions.customOutputFilename; - } else if (key && key.filters.binary) { + } else if (key?.filters.binary) { filename = `${outputFilebase}`; } else { filename = `${outputFilebase}.c.asm`; @@ -68,9 +68,8 @@ export class z88dkCompiler extends BaseCompiler { if (dirPath) { return path.join(dirPath, filename); - } else { - return filename; } + return filename; } public override orderArguments( @@ -105,10 +104,9 @@ export class z88dkCompiler extends BaseCompiler { protected override optionsForFilter(filters: ParseFiltersAndOutputOptions, outputFilename: string): string[] { if (filters.binary) { - return ['-o', outputFilename + '.s', '-create-app']; - } else { - return ['-S']; + return ['-o', `${outputFilename}.s`, '-create-app']; } + return ['-S']; } override getDefaultExecOptions(): ExecutionOptionsWithEnv { @@ -144,13 +142,13 @@ export class z88dkCompiler extends BaseCompiler { outputFilename = this.getObjdumpOutputFilename(outputFilename); // sometimes (with +z80 for example) the .bin file is written and the .s file is empty - if (await utils.fileExists(outputFilename + '.bin')) { + if (await utils.fileExists(`${outputFilename}.bin`)) { outputFilename += '.bin'; } else { - if (await utils.fileExists(outputFilename + '.s')) { + if (await utils.fileExists(`${outputFilename}.s`)) { outputFilename += '.s'; } else { - result.asm = ''; + result.asm = ``; return result; } } @@ -160,7 +158,7 @@ export class z88dkCompiler extends BaseCompiler { if (this.externalparser) { const objResult = await this.externalparser.objdumpAndParseAssembly(result.dirPath, args, filters); if (objResult.parsingTime !== undefined) { - objResult.objdumpTime = parseInt(result.execTime) - parseInt(result.parsingTime); + objResult.objdumpTime = Number.parseInt(result.execTime) - Number.parseInt(result.parsingTime); delete objResult.execTime; } diff --git a/lib/compilers/zig.ts b/lib/compilers/zig.ts index abb130633..cb805de1e 100644 --- a/lib/compilers/zig.ts +++ b/lib/compilers/zig.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import Semver from 'semver'; import _ from 'underscore'; @@ -124,9 +124,9 @@ export class ZigCompiler extends BaseCompiler { options.push('--cache-dir', outputDir, '--name', name); if (filters.binary) { - options.push('-femit-bin=' + desiredName); + options.push(`-femit-bin=${desiredName}`); } else { - options.push('-fno-emit-bin', '-femit-asm=' + desiredName); + options.push('-fno-emit-bin', `-femit-asm=${desiredName}`); } return options; } diff --git a/lib/demangler/cpp.ts b/lib/demangler/cpp.ts index 07f88610b..a2b4fac48 100644 --- a/lib/demangler/cpp.ts +++ b/lib/demangler/cpp.ts @@ -25,12 +25,12 @@ import {BaseDemangler} from './base.js'; const LabelMetadata = [ - {ident: new RegExp('C1E[a-zA-Z0-9_$]*$'), description: 'complete object constructor'}, - {ident: new RegExp('C2E[a-zA-Z0-9_$]*$'), description: 'base object constructor'}, - {ident: new RegExp('C3E[a-zA-Z0-9_$]*$'), description: 'complete object allocating constructor'}, - {ident: new RegExp('D0Ev$'), description: 'deleting destructor'}, - {ident: new RegExp('D1Ev$'), description: 'complete object destructor'}, - {ident: new RegExp('D2Ev$'), description: 'base object destructor'}, + {ident: /C1E[a-zA-Z0-9_$]*$/, description: 'complete object constructor'}, + {ident: /C2E[a-zA-Z0-9_$]*$/, description: 'base object constructor'}, + {ident: /C3E[a-zA-Z0-9_$]*$/, description: 'complete object allocating constructor'}, + {ident: /D0Ev$/, description: 'deleting destructor'}, + {ident: /D1Ev$/, description: 'complete object destructor'}, + {ident: /D2Ev$/, description: 'base object destructor'}, ]; export class CppDemangler extends BaseDemangler { diff --git a/lib/demangler/pascal.ts b/lib/demangler/pascal.ts index c86001be8..bade5d2f9 100644 --- a/lib/demangler/pascal.ts +++ b/lib/demangler/pascal.ts @@ -96,10 +96,10 @@ export class PascalDemangler extends BaseDemangler { public composeReadableMethodSignature(unitname: string, classname: string, methodname: string, params: string) { let signature = ''; - if (classname !== '') signature = classname.toLowerCase() + '.'; + if (classname !== '') signature = `${classname.toLowerCase()}.`; signature = signature + methodname.toLowerCase(); - signature = signature + '(' + params.toLowerCase() + ')'; + signature = `${signature}(${params.toLowerCase()})`; return signature; } @@ -122,20 +122,21 @@ export class PascalDemangler extends BaseDemangler { const unmangledGlobalVar = text.substring(13).toLowerCase(); this.symbolStore.add(text, unmangledGlobalVar); return unmangledGlobalVar; - } else if (text.startsWith('U_OUTPUT_')) { + } + if (text.startsWith('U_OUTPUT_')) { const unmangledGlobalVar = text.substring(9).toLowerCase(); this.symbolStore.add(text, unmangledGlobalVar); return unmangledGlobalVar; } - let idx, - paramtype = '', - phase = 0; - let unitname = '', - classname = '', - methodname = '', - params = '', - resulttype = ''; + let idx; + let paramtype = ''; + let phase = 0; + let unitname = ''; + let classname = ''; + let methodname = ''; + let params = ''; + let resulttype = ''; idx = text.indexOf('$_$'); if (idx !== -1) { @@ -172,7 +173,7 @@ export class PascalDemangler extends BaseDemangler { else if (phase === 1) { if (paramtype === '') phase = 2; else if (params !== '') { - params = params + ',' + paramtype; + params = `${params},${paramtype}`; paramtype = ''; } else if (params === '') { params = paramtype; @@ -190,7 +191,7 @@ export class PascalDemangler extends BaseDemangler { if (params === '') { params = paramtype; } else { - params = params + ',' + paramtype; + params = `${params},${paramtype}`; } } } @@ -216,10 +217,9 @@ export class PascalDemangler extends BaseDemangler { text = text.replace(translations[idx][0], translations[idx][1]); } - return text; - } else { return text; } + return text; } public override async process(result: ParsedAsmResult, execOptions?: ExecutionOptions) { diff --git a/lib/demangler/prefix-tree.ts b/lib/demangler/prefix-tree.ts index 57c82858e..fb0aaf20e 100644 --- a/lib/demangler/prefix-tree.ts +++ b/lib/demangler/prefix-tree.ts @@ -92,7 +92,7 @@ export class PrefixTree { node = node[character]; if (!node) break; } - if (node && node['result']) return node['result']; + if (node?.result) return node.result; return null; } diff --git a/lib/demangler/win32-llvm.ts b/lib/demangler/win32-llvm.ts index ec35eaa6c..0c483f750 100644 --- a/lib/demangler/win32-llvm.ts +++ b/lib/demangler/win32-llvm.ts @@ -69,7 +69,7 @@ export class LLVMWin32Demangler extends Win32Demangler { symbolArray.push(symb); } - const stdin = symbolArray.join('\n') + '\n'; + const stdin = `${symbolArray.join('\n')}\n`; await demangleFromStdin(stdin); return translations; diff --git a/lib/exec.ts b/lib/exec.ts index 004e332ea..d17d7e243 100644 --- a/lib/exec.ts +++ b/lib/exec.ts @@ -23,10 +23,10 @@ // POSSIBILITY OF SUCH DAMAGE. import buffer from 'buffer'; -import child_process from 'child_process'; -import os from 'os'; -import path from 'path'; -import {Stream} from 'stream'; +import child_process from 'node:child_process'; +import os from 'node:os'; +import path from 'node:path'; +import {Stream} from 'node:stream'; import fs from 'fs-extra'; import treeKill from 'tree-kill'; @@ -353,7 +353,7 @@ function executeCEWrapper(command: string, args: string[], options: ExecutionOpt } function withFirejailTimeout(args: string[], options?: ExecutionOptions) { - if (options && options.timeoutMs) { + if (options?.timeoutMs) { // const ExtraWallClockLeewayMs = 1000; const ExtraCpuLeewayMs = 1500; return args.concat([`--rlimit-cpu=${Math.round((options.timeoutMs + ExtraCpuLeewayMs) / 1000)}`]); @@ -369,7 +369,7 @@ function sandboxFirejail(command: string, args: string[], options: ExecutionOpti '--quiet', '--deterministic-exit-code', '--deterministic-shutdown', - '--profile=' + getFirejailProfileFilePath('sandbox'), + `--profile=${getFirejailProfileFilePath('sandbox')}`, `--private=${execPath}`, '--private-cwd', ]); @@ -410,7 +410,7 @@ export async function sandbox( const type = execProps('sandboxType', 'firejail'); const dispatchEntry = sandboxDispatchTable[type as 'none' | 'nsjail' | 'firejail' | 'cewrapper']; if (!dispatchEntry) throw new Error(`Bad sandbox type ${type}`); - if (!command) throw new Error(`No executable provided`); + if (!command) throw new Error('No executable provided'); return await dispatchEntry(command, args, options); } @@ -442,7 +442,7 @@ export function startWineInit() { await fs.mkdir(prefix); } - logger.info(`Killing any pre-existing wine-server`); + logger.info('Killing any pre-existing wine-server'); child_process.exec(`${server} -k || true`, {env: env}); // We run a long-lived cmd process, to: @@ -454,12 +454,12 @@ export function startWineInit() { let wineServer: child_process.ChildProcess | undefined; if (firejail) { - logger.info(`Starting a new, firejailed, long-lived wineserver complex`); + logger.info('Starting a new, firejailed, long-lived wineserver complex'); wineServer = child_process.spawn( firejail, [ '--quiet', - '--profile=' + getFirejailProfileFilePath('wine'), + `--profile=${getFirejailProfileFilePath('wine')}`, '--private', `--name=${wineSandboxName}`, wine, @@ -570,7 +570,7 @@ async function executeFirejail(command: string, args: string[], options: Executi options.env = applyWineEnv(options.env || {}); args = [command, ...args]; command = execProps('wine'); - baseOptions.push('--profile=' + getFirejailProfileFilePath('wine'), `--join=${wineSandboxName}`); + baseOptions.push(`--profile=${getFirejailProfileFilePath('wine')}`, `--join=${wineSandboxName}`); delete options.customCwd; baseOptions.push(command); await wineInitPromise; @@ -578,7 +578,7 @@ async function executeFirejail(command: string, args: string[], options: Executi } logger.debug('Regular execution via firejail', {command, args}); - baseOptions.push('--profile=' + getFirejailProfileFilePath('execute')); + baseOptions.push(`--profile=${getFirejailProfileFilePath('execute')}`); if (options.ldPath) { baseOptions.push(`--env=LD_LIBRARY_PATH=${options.ldPath.join(path.delimiter)}`); @@ -628,6 +628,6 @@ export async function execute( const type = execProps('executionType', 'none'); const dispatchEntry = executeDispatchTable[type]; if (!dispatchEntry) throw new Error(`Bad sandbox type ${type}`); - if (!command) throw new Error(`No executable provided`); + if (!command) throw new Error('No executable provided'); return await dispatchEntry(command, args, options); } diff --git a/lib/execution/base-execution-env.ts b/lib/execution/base-execution-env.ts index 663695a7b..0485e567b 100644 --- a/lib/execution/base-execution-env.ts +++ b/lib/execution/base-execution-env.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import os from 'os'; -import path from 'path'; +import os from 'node:os'; +import path from 'node:path'; import fs from 'fs-extra'; import temp from 'temp'; @@ -85,7 +85,7 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { protected async executableGet(hash: string, destinationFolder: string) { const result = await this.environment.executableCache.get(hash); if (!result.hit) return null; - const filepath = destinationFolder + '/' + hash; + const filepath = `${destinationFolder}/${hash}`; await fs.writeFile(filepath, unwrap(result.data)); return filepath; } @@ -99,7 +99,7 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { await this.packager.unpack(outputFilename, dirPath); const buildResultsBuf = await fs.readFile(path.join(dirPath, compilationResultFilename)); const buildResults = JSON.parse(buildResultsBuf.toString('utf8')); - logger.debug(hash + ' => ' + JSON.stringify(buildResults)); + logger.debug(`${hash} => ${JSON.stringify(buildResults)}`); const endTime = process.hrtime.bigint(); let inputFilename = ''; @@ -111,7 +111,7 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { if (buildResults.executableFilename) { const execPath = utils.maskRootdir(buildResults.executableFilename); executableFilename = path.join(dirPath, execPath); - logger.debug('executableFilename => ' + executableFilename); + logger.debug(`executableFilename => ${executableFilename}`); } else { logger.error(`No executableFilename provided for package ${hash}`); } @@ -123,9 +123,8 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { executableFilename: executableFilename, packageDownloadAndUnzipTime: utils.deltaTimeNanoToMili(startTime, endTime), }); - } else { - throw new ExecutablePackageCacheMiss('Tried to get executable from cache, but got a cache miss'); } + throw new ExecutablePackageCacheMiss('Tried to get executable from cache, but got a cache miss'); } async downloadExecutablePackage(hash: string): Promise { @@ -148,10 +147,7 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { } if ( - this.buildResult && - this.buildResult.defaultExecOptions && - this.buildResult.defaultExecOptions.env && - this.buildResult.defaultExecOptions.env.PATH + this.buildResult?.defaultExecOptions?.env?.PATH ) { if (env.PATH.length > 0) env.PATH = env.PATH + path.delimiter + this.buildResult.defaultExecOptions.env.PATH; @@ -168,7 +164,7 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { env, }; - if (this.buildResult && this.buildResult.preparedLdPaths) { + if (this.buildResult?.preparedLdPaths) { execOptions.ldPath = this.buildResult.preparedLdPaths.concat(extraLdPaths); } else { execOptions.ldPath = extraLdPaths; @@ -248,14 +244,13 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { } catch (err: UnprocessedExecResult | any) { if (err.code && err.stderr) { return utils.processExecutionResult(err); - } else { + } return { ...utils.getEmptyExecutionResult(), stdout: err.stdout ? utils.parseOutput(err.stdout) : [], stderr: err.stderr ? utils.parseOutput(err.stderr) : [], code: err.code === undefined ? -1 : err.code, }; - } } } @@ -292,7 +287,7 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { const tracer = path.join(libSegFaultPath, 'tracer'); if (execOptions.env.LD_PRELOAD) { - execOptions.env.LD_PRELOAD = preloadSo + ':' + execOptions.env.LD_PRELOAD; + execOptions.env.LD_PRELOAD = `${preloadSo}:${execOptions.env.LD_PRELOAD}`; } else { execOptions.env.LD_PRELOAD = preloadSo; } @@ -334,10 +329,9 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment { } return processed; - } else { + } const execResult: UnprocessedExecResult = await exec.sandbox(executable, args, execOptions); return this.processUserExecutableExecutionResult(execResult, Array.from(lineParseOptions.values())); - } } processUserExecutableExecutionResult( diff --git a/lib/execution/dotnet-execution-env.ts b/lib/execution/dotnet-execution-env.ts index ec5ebe2c8..4254c5ecb 100644 --- a/lib/execution/dotnet-execution-env.ts +++ b/lib/execution/dotnet-execution-env.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {BasicExecutionResult, ExecutableExecutionOptions} from '../../types/execution/execution.interfaces.js'; import * as utils from '../utils.js'; @@ -81,14 +81,13 @@ export class DotnetExecutionEnvironment extends LocalExecutionEnvironment { } catch (err: any) { if (err.code && err.stderr) { return utils.processExecutionResult(err); - } else { - return { - ...utils.getEmptyExecutionResult(), - stdout: err.stdout ? utils.parseOutput(err.stdout) : [], - stderr: err.stderr ? utils.parseOutput(err.stderr) : [], - code: err.code === undefined ? -1 : err.code, - }; } + return { + ...utils.getEmptyExecutionResult(), + stdout: err.stdout ? utils.parseOutput(err.stdout) : [], + stderr: err.stderr ? utils.parseOutput(err.stderr) : [], + code: err.code === undefined ? -1 : err.code, + }; } } } diff --git a/lib/execution/events-websocket.ts b/lib/execution/events-websocket.ts index ace19989b..bb4dce04b 100644 --- a/lib/execution/events-websocket.ts +++ b/lib/execution/events-websocket.ts @@ -29,10 +29,10 @@ import {logger} from '../logger.js'; import {PropertyGetter} from '../properties.interfaces.js'; export class EventsWsBase { - protected expectClose: boolean = false; + protected expectClose = false; protected events_url: string; protected ws: WebSocket | undefined = undefined; - protected got_error: boolean = false; + protected got_error = false; constructor(props: PropertyGetter) { this.events_url = props('execqueue.events_url', ''); diff --git a/lib/execution/execution-triple.ts b/lib/execution/execution-triple.ts index 7e0bd6ed0..760966c91 100644 --- a/lib/execution/execution-triple.ts +++ b/lib/execution/execution-triple.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import os from 'os'; +import os from 'node:os'; import {InstructionSet} from '../../types/instructionsets.js'; import {OSType} from '../binaries/binary-utils.js'; @@ -60,11 +60,14 @@ class CurrentHostExecHelper { const hostArch = os.arch(); if (hostArch === 'arm64' && value === 'aarch64') { return true; - } else if (hostArch === 'arm' && value === 'arm32') { + } + if (hostArch === 'arm' && value === 'arm32') { return true; - } else if (hostArch === 'x64' && (value === 'amd64' || value === 'x86')) { + } + if (hostArch === 'x64' && (value === 'amd64' || value === 'x86')) { return true; - } else if (hostArch === 'ia32' && value === 'x86') { + } + if (hostArch === 'ia32' && value === 'x86') { return true; } diff --git a/lib/execution/remote-execution-env.ts b/lib/execution/remote-execution-env.ts index 0c874884e..0fc535054 100644 --- a/lib/execution/remote-execution-env.ts +++ b/lib/execution/remote-execution-env.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import crypto from 'crypto'; +import crypto from 'node:crypto'; import {ExecutionParams} from '../../types/compilation/compilation.interfaces.js'; import {BasicExecutionResult, ExecutableExecutionOptions} from '../../types/execution/execution.interfaces.js'; diff --git a/lib/execution/sqs-execution-queue.ts b/lib/execution/sqs-execution-queue.ts index 214a69d23..871629e24 100644 --- a/lib/execution/sqs-execution-queue.ts +++ b/lib/execution/sqs-execution-queue.ts @@ -54,7 +54,7 @@ export class SqsExecuteQueueBase { } getSqsQueueUrl(triple: BaseExecutionTriple) { - return this.queue_url + '-' + triple.toString() + '.fifo'; + return `${this.queue_url}-${triple.toString()}.fifo`; } } @@ -113,9 +113,8 @@ export class SqsWorkerMode extends SqsExecuteQueueBase { if (queued_message.Body) { const json = queued_message.Body; return JSON.parse(json) as RemoteExecutionMessage; - } else { - return undefined; } + return undefined; } finally { if (queued_message.ReceiptHandle) { await this.sqs.deleteMessage({ @@ -146,7 +145,7 @@ async function sendResultViaWebsocket( async function doOneExecution(queue: SqsWorkerMode, compilationEnvironment: CompilationEnvironment) { const msg = await queue.pop(); - if (msg && msg.guid) { + if (msg?.guid) { try { const executor = new LocalExecutionEnvironment(compilationEnvironment); await executor.downloadExecutablePackage(msg.hash); diff --git a/lib/external-parsers/base.ts b/lib/external-parsers/base.ts index 0133b047a..1a056d03d 100644 --- a/lib/external-parsers/base.ts +++ b/lib/external-parsers/base.ts @@ -1,5 +1,5 @@ -import fs from 'fs'; -import path from 'path'; +import fs from 'node:fs'; +import path from 'node:path'; import type {ParsedAsmResult} from '../../types/asmresult/asmresult.interfaces.js'; import {CompilerInfo} from '../../types/compiler.interfaces.js'; @@ -52,12 +52,7 @@ export class ExternalParserBase implements IExternalParser { private getObjdumpStarterScriptContent(filters: ParseFiltersAndOutputOptions) { const parserArgs = this.getParserArguments(filters, true); - return ( - '#!/bin/bash\n' + - `OBJDUMP=${this.objdumperPath}\n` + - `ASMPARSER=${this.parserPath}\n` + - `$OBJDUMP "$@" | $ASMPARSER ${parserArgs.join(' ')}\n` - ); + return `#!/bin/bash\nOBJDUMP=${this.objdumperPath}\nASMPARSER=${this.parserPath}\n$OBJDUMP "$@" | $ASMPARSER ${parserArgs.join(' ')}\n`; } private async writeStarterScriptObjdump( diff --git a/lib/global.ts b/lib/global.ts index 0f42165d3..4e8b5a283 100644 --- a/lib/global.ts +++ b/lib/global.ts @@ -31,7 +31,3 @@ declare global { var handler_config: HandlerConfig; /* eslint-enable no-var */ } - -// Necessary because we're not exporting any actual symbols from this file -// See https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html -export {}; diff --git a/lib/handlers/api.ts b/lib/handlers/api.ts index ef027e9b2..a4e229a15 100644 --- a/lib/handlers/api.ts +++ b/lib/handlers/api.ts @@ -237,8 +237,8 @@ export class ApiHandler { .concat([title]) .map(item => item.length), ); - const header = title.padEnd(maxLength, ' ') + ' | Name\n'; - const body = list.map(lang => lang.id.padEnd(maxLength, ' ') + ' | ' + lang.name).join('\n'); + const header = `${title.padEnd(maxLength, ' ')} | Name\n`; + const body = list.map(lang => `${lang.id.padEnd(maxLength, ' ')} | ${lang.name}`).join('\n'); res.set('Content-Type', 'text/plain'); res.send(header + body); } diff --git a/lib/handlers/compile.ts b/lib/handlers/compile.ts index 086a773c6..78de2dd0a 100644 --- a/lib/handlers/compile.ts +++ b/lib/handlers/compile.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import * as Sentry from '@sentry/node'; import express from 'express'; @@ -279,7 +279,7 @@ export class CompileHandler implements ICompileHandler { const compilersById: Partial>> = {}; try { this.clientOptions = clientOptions; - logger.info('Creating compilers: ' + compilers.length); + logger.info(`Creating compilers: ${compilers.length}`); let compilersCreated = 0; const createdCompilers = remove(await Promise.all(compilers.map(c => this.create(c))), null); for (const compiler of createdCompilers) { @@ -288,7 +288,7 @@ export class CompileHandler implements ICompileHandler { compilersById[langId][compiler.getInfo().id] = compiler; compilersCreated++; } - logger.info('Compilers created: ' + compilersCreated); + logger.info(`Compilers created: ${compilersCreated}`); if (this.awsProps) { logger.info('Fetching possible arguments from storage'); await Promise.all( @@ -308,7 +308,7 @@ export class CompileHandler implements ICompileHandler { } compilerAliasMatch(compiler: BaseCompiler, compilerId: string): boolean { - return compiler.compiler.alias && compiler.compiler.alias.includes(compilerId); + return compiler.compiler.alias?.includes(compilerId); } compilerIdOrAliasMatch(compiler: BaseCompiler, compilerId: string): boolean { @@ -322,13 +322,12 @@ export class CompileHandler implements ICompileHandler { if (langCompilers) { if (langCompilers[compilerId]) { return langCompilers[compilerId]; - } else { - const compiler = _.find(langCompilers, (compiler: BaseCompiler) => { - return this.compilerAliasMatch(compiler, compilerId); - }); - - if (compiler) return compiler; } + const compiler = _.find(langCompilers, (compiler: BaseCompiler) => { + return this.compilerAliasMatch(compiler, compilerId); + }); + + if (compiler) return compiler; } // If the lang is bad, try to find it in every language @@ -353,20 +352,20 @@ export class CompileHandler implements ICompileHandler { logger.warn(`Unable to find compiler with lang ${lang} for JSON request`, withoutBody); } return compiler; - } else if (req.body && req.body.compiler) { + } + if (req.body?.compiler) { const compiler = this.findCompiler(req.body.lang, req.body.compiler); if (!compiler) { const withoutBody = _.extend({}, req.body, {source: ''}); logger.warn(`Unable to find compiler with lang ${req.body.lang} for request`, withoutBody); } return compiler; - } else { - const compiler = this.findCompiler(req.lang, req.params.compiler); - if (!compiler) { - logger.warn(`Unable to find compiler with lang ${req.lang} for request params`, req.params); - } - return compiler; } + const compiler = this.findCompiler(req.lang, req.params.compiler); + if (!compiler) { + logger.warn(`Unable to find compiler with lang ${req.lang} for request params`, req.params); + } + return compiler; } checkRequestRequirements(req: express.Request): CompileRequestJsonBody { @@ -376,12 +375,12 @@ export class CompileHandler implements ICompileHandler { } parseRequest(req: express.Request, compiler: BaseCompiler): ParsedRequest { - let source: string, - options: string, - backendOptions: Record = {}, - filters: ParseFiltersAndOutputOptions, - bypassCache = BypassCache.None, - tools; + let source: string; + let options: string; + let backendOptions: Record = {}; + let filters: ParseFiltersAndOutputOptions; + let bypassCache = BypassCache.None; + let tools; const execReqParams: UnparsedExecutionParams = {}; let libraries: any[] = []; // IF YOU MODIFY ANYTHING HERE PLEASE UPDATE THE DOCUMENTATION! @@ -400,7 +399,7 @@ export class CompileHandler implements ICompileHandler { filters = {...compiler.getDefaultFilters(), ...requestOptions.filters}; tools = requestOptions.tools; libraries = requestOptions.libraries || []; - } else if (req.body && req.body.compiler) { + } else if (req.body?.compiler) { const textRequest = req.body as CompileRequestTextBody; source = textRequest.source; if (textRequest.bypassCache) bypassCache = textRequest.bypassCache; @@ -491,9 +490,8 @@ export class CompileHandler implements ICompileHandler { if (data.presplit) { return data.usedOptions; - } else { - return utils.splitArguments(data.usedOptions); } + return utils.splitArguments(data.usedOptions); } return false; } @@ -504,9 +502,8 @@ export class CompileHandler implements ICompileHandler { error: true, message: error.message, }); - } else { - return next(error); } + return next(error); } handleCmake(req: express.Request, res: express.Response, next: express.NextFunction) { @@ -541,7 +538,7 @@ export class CompileHandler implements ICompileHandler { // Convert a boolean input to an enum's underlying numeric value .cmake(req.body.files, parsedRequest, req.body.bypassCache * 1) .then(result => { - if (result.didExecute || (result.execResult && result.execResult.didExecute)) + if (result.didExecute || result.execResult?.didExecute) this.cmakeExecuteCounter.inc({language: compiler.lang.id}); res.send(result); }) @@ -592,9 +589,8 @@ export class CompileHandler implements ICompileHandler { if (filterAnsi) { // https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python return text.replaceAll(/(\x9B|\x1B\[)[\d:;<=>?]*[ -/]*[@-~]/g, ''); - } else { - return text; } + return text; } this.compileCounter.inc({language: compiler.lang.id}); @@ -609,33 +605,31 @@ export class CompileHandler implements ICompileHandler { .compile(source, options, backendOptions, filters, bypassCache, tools, executeParameters, libraries, files) .then( result => { - if (result.didExecute || (result.execResult && result.execResult.didExecute)) + if (result.didExecute || result.execResult?.didExecute) this.executeCounter.inc({language: compiler.lang.id}); if (req.accepts(['text', 'json']) === 'json') { res.send(result); } else { res.set('Content-Type', 'text/plain'); try { - if (!_.isEmpty(this.textBanner)) res.write('# ' + this.textBanner + '\n'); + if (!_.isEmpty(this.textBanner)) res.write(`# ${this.textBanner}\n`); res.write(textify(result.asm, backendOptions.filterAnsi)); - if (result.code !== 0) res.write('\n# Compiler exited with result code ' + result.code); + if (result.code !== 0) res.write(`\n# Compiler exited with result code ${result.code}`); if (!_.isEmpty(result.stdout)) - res.write('\nStandard out:\n' + textify(result.stdout, backendOptions.filterAnsi)); + res.write(`\nStandard out:\n${textify(result.stdout, backendOptions.filterAnsi)}`); if (!_.isEmpty(result.stderr)) - res.write('\nStandard error:\n' + textify(result.stderr, backendOptions.filterAnsi)); + res.write(`\nStandard error:\n${textify(result.stderr, backendOptions.filterAnsi)}`); if (result.execResult) { - res.write('\n\n# Execution result with exit code ' + result.execResult.code + '\n'); + res.write(`\n\n# Execution result with exit code ${result.execResult.code}\n`); if (!_.isEmpty(result.execResult.stdout)) { res.write( - '# Standard out:\n' + - textify(result.execResult.stdout, backendOptions.filterAnsi), + `# Standard out:\n${textify(result.execResult.stdout, backendOptions.filterAnsi)}`, ); } if (!_.isEmpty(result.execResult.stderr)) { res.write( - '\n# Standard error:\n' + - textify(result.execResult.stderr, backendOptions.filterAnsi), + `\n# Standard error:\n${textify(result.execResult.stderr, backendOptions.filterAnsi)}`, ); } } diff --git a/lib/handlers/health-check.ts b/lib/handlers/health-check.ts index f64fcdf6f..dfea71283 100644 --- a/lib/handlers/health-check.ts +++ b/lib/handlers/health-check.ts @@ -57,7 +57,7 @@ export class HealthCheckHandler { await this.compilationQueue.enqueue(async () => {}, {highPriority: true}); if (!this.isExecutionWorker && !this.compileHandler.hasLanguages()) { - logger.error(`*** HEALTH CHECK FAILURE: no languages/compilers detected`); + logger.error('*** HEALTH CHECK FAILURE: no languages/compilers detected'); res.status(500).end(); return; } diff --git a/lib/handlers/noscript.ts b/lib/handlers/noscript.ts index 0bf209ad1..a358c0de7 100644 --- a/lib/handlers/noscript.ts +++ b/lib/handlers/noscript.ts @@ -161,7 +161,7 @@ export class NoScriptHandler { this.contentPolicyHeader(res); let wantedLanguage = 'c++'; - if (req.params && req.params.language) { + if (req.params?.language) { wantedLanguage = req.params.language; } else { if (this.defaultLanguage) wantedLanguage = this.defaultLanguage; diff --git a/lib/handlers/route-api.ts b/lib/handlers/route-api.ts index 8fbc8fe10..efc1b4a27 100644 --- a/lib/handlers/route-api.ts +++ b/lib/handlers/route-api.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import zlib from 'zlib'; +import zlib from 'node:zlib'; import express from 'express'; @@ -106,7 +106,7 @@ export class RouteAPI { storedCodeHandler(req: express.Request, res: express.Response, next: express.NextFunction) { const id = req.params.id; - const sessionid = parseInt(req.params.session); + const sessionid = Number.parseInt(req.params.session); this.storageHandler .expandId(id) .then(result => { diff --git a/lib/handlers/site-templates.ts b/lib/handlers/site-templates.ts index 0e71d5c28..324b5be26 100644 --- a/lib/handlers/site-templates.ts +++ b/lib/handlers/site-templates.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import * as fs from 'fs'; +import * as fs from 'node:fs'; import {SiteTemplatesType} from '../../types/features/site-templates.interfaces.js'; @@ -36,8 +36,8 @@ function splitProperty(line: string) { } function partition(array: T[], filter: (value: T) => boolean): [T[], T[]] { - const pass: T[] = [], - fail: T[] = []; + const pass: T[] = []; + const fail: T[] = []; for (const item of array) { if (filter(item)) { pass.push(item); @@ -51,7 +51,7 @@ function partition(array: T[], filter: (value: T) => boolean): [T[], T[]] { export function loadSiteTemplates(configDir: string) { const [meta, templates] = partition( fs - .readFileSync(configDir + '/site-templates.conf', 'utf8') + .readFileSync(`${configDir}/site-templates.conf`, 'utf8') .split('\n') .filter(l => l !== '') .map(splitProperty) diff --git a/lib/keyed-type.ts b/lib/keyed-type.ts index 45fd13cfb..e7b237e5b 100644 --- a/lib/keyed-type.ts +++ b/lib/keyed-type.ts @@ -69,9 +69,8 @@ export function makeKeyedTypeGetter( return function getFromKey(key) { if (key in keyMap) { return keyMap[key]; - } else { - throw new Error(`No ${typeName} named '${key}' found`); } + throw new Error(`No ${typeName} named '${key}' found`); }; } @@ -85,8 +84,7 @@ export function makeDefaultedKeyedTypeGetter( return function getFromKey(key) { if (key in keyMap) { return keyMap[key]; - } else { - return defaultObject; } + return defaultObject; }; } diff --git a/lib/languages.ts b/lib/languages.ts index e8d9a0be9..a3f0f5a19 100644 --- a/lib/languages.ts +++ b/lib/languages.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -879,7 +879,7 @@ export const languages = Object.fromEntries( Object.entries(definitions).map(([key, lang]) => { let example: string; try { - example = fs.readFileSync(path.join('examples', key, 'default' + lang.extensions[0]), 'utf8'); + example = fs.readFileSync(path.join('examples', key, `default${lang.extensions[0]}`), 'utf8'); } catch (error) { example = 'Oops, something went wrong and we could not get the default code for this language.'; } diff --git a/lib/llvm-ast.ts b/lib/llvm-ast.ts index e9e461887..682cc617f 100644 --- a/lib/llvm-ast.ts +++ b/lib/llvm-ast.ts @@ -81,17 +81,16 @@ export class LlvmAstParser { const begin = this.parsePoint(beginEnd[0], lastLineNo); const end = this.parsePoint(beginEnd[1], begin.line); return {type: LlvmAstParser.locTypes.SPAN, begin, end}; - } else { - return {type: LlvmAstParser.locTypes.POINT, loc: this.parsePoint(span, lastLineNo)}; } + return {type: LlvmAstParser.locTypes.POINT, loc: this.parsePoint(span, lastLineNo)}; } return {type: LlvmAstParser.locTypes.NONE}; } // Link the AST lines with spans of source locations (lines+columns) parseAndSetSourceLines(astDump: ResultLine[]) { - let lfrom: any = {line: null, loc: null}, - lto: any = {line: null, loc: null}; + let lfrom: any = {line: null, loc: null}; + let lto: any = {line: null, loc: null}; for (const line of astDump) { const span = this.parseSpan(line.text, lfrom.line); switch (span.type) { @@ -141,7 +140,7 @@ export class LlvmAstParser { const addressRegex = /^([^A-Za-z]*[A-Za-z]+) 0x[\da-z]+/gm; const slocRegex2 = / ?>?/g; - let mostRecentIsSource: boolean = false; + let mostRecentIsSource = false; const isBlockUserSource = (output: ResultLine[], start: number, mostRecentIsSource: boolean) => { for (let i = start + 1; i < output.length; ++i) { diff --git a/lib/llvm-ir.ts b/lib/llvm-ir.ts index 6c4e7ee3b..02289107a 100644 --- a/lib/llvm-ir.ts +++ b/lib/llvm-ir.ts @@ -256,12 +256,11 @@ export class LlvmIrParser { asm: demangled.asm, languageId: 'llvm-ir', }; - } else { - return { - asm: result, - languageId: 'llvm-ir', - }; } + return { + asm: result, + languageId: 'llvm-ir', + }; } async processFromFilters(ir: string, filters: ParseFiltersAndOutputOptions): Promise { diff --git a/lib/llvm-opt-transformer.ts b/lib/llvm-opt-transformer.ts index 6e03994e3..d4c853075 100644 --- a/lib/llvm-opt-transformer.ts +++ b/lib/llvm-opt-transformer.ts @@ -47,8 +47,8 @@ function DisplayOptInfo(optInfo: LLVMOptInfo) { let inc = ''; for (const [key, value] of Object.entries(x)) { if (key === 'DebugLoc') { - if (value['Line'] !== 0) { - inc += ' (' + value['Line'] + ':' + value['Column'] + ')'; + if (value.Line !== 0) { + inc += ` (${value.Line}:${value.Column})`; } } else { inc += value; @@ -60,13 +60,13 @@ function DisplayOptInfo(optInfo: LLVMOptInfo) { return displayString; } -export function processRawOptRemarks(buffer: string, compileFileName: string = ''): LLVMOptInfo[] { +export function processRawOptRemarks(buffer: string, compileFileName = ''): LLVMOptInfo[] { const output: LLVMOptInfo[] = []; const remarksSet: Set = new Set(); const remarks: any = parseAllDocuments(buffer); for (const doc of remarks) { if (doc.errors !== undefined && doc.errors.length > 0) { - logger.warn('YAMLParseError: ' + JSON.stringify(doc.errors[0])); + logger.warn(`YAMLParseError: ${JSON.stringify(doc.errors[0])}`); continue; } diff --git a/lib/logger.ts b/lib/logger.ts index e5b7105a1..a63831982 100644 --- a/lib/logger.ts +++ b/lib/logger.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import os from 'os'; -import {Writable} from 'stream'; +import os from 'node:os'; +import {Writable} from 'node:stream'; import {LEVEL, MESSAGE} from 'triple-beam'; import winston from 'winston'; diff --git a/lib/mapfiles/map-file-delphi.ts b/lib/mapfiles/map-file-delphi.ts index d8d5042ee..5a0ebee6b 100644 --- a/lib/mapfiles/map-file-delphi.ts +++ b/lib/mapfiles/map-file-delphi.ts @@ -43,13 +43,13 @@ export class MapFileReaderDelphi extends MapFileReader { */ override tryReadingCodeSegmentInfo(line: string) { let matches = line.match(this.regexDelphiCodeSegmentOffset); - if (matches && !matches[4].includes('$') && parseInt(matches[2], 16) >= this.preferredLoadAddress) { - const addressWithOffset = parseInt(matches[2], 16); + if (matches && !matches[4].includes('$') && Number.parseInt(matches[2], 16) >= this.preferredLoadAddress) { + const addressWithOffset = Number.parseInt(matches[2], 16); this.segmentOffsets.push({ segment: matches[1], addressInt: addressWithOffset, address: addressWithOffset.toString(16), - segmentLength: parseInt(matches[3], 16), + segmentLength: Number.parseInt(matches[3], 16), }); } else { matches = line.match(this.regexDelphiCodeSegment); @@ -57,8 +57,8 @@ export class MapFileReaderDelphi extends MapFileReader { this.segments.push({ ...this.addressToObject(matches[1], matches[2]), id: this.segments.length + 1, - segmentLength: parseInt(matches[3], 16), - unitName: matches[4] === 'prog' ? 'prog.dpr' : matches[4] + '.pas', + segmentLength: Number.parseInt(matches[3], 16), + unitName: matches[4] === 'prog' ? 'prog.dpr' : `${matches[4]}.pas`, }); } else { matches = line.match(this.regexDelphiICodeSegment); @@ -66,8 +66,8 @@ export class MapFileReaderDelphi extends MapFileReader { this.isegments.push({ ...this.addressToObject(matches[1], matches[2]), id: this.isegments.length + 1, - segmentLength: parseInt(matches[3], 16), - unitName: matches[4] === 'prog' ? 'prog.dpr' : matches[4] + '.pas', + segmentLength: Number.parseInt(matches[3], 16), + unitName: matches[4] === 'prog' ? 'prog.dpr' : `${matches[4]}.pas`, }); } } @@ -107,7 +107,7 @@ export class MapFileReaderDelphi extends MapFileReader { if (matches) { this.lineNumbers.push({ ...this.addressToObject(matches[2], matches[3]), - lineNumber: parseInt(matches[1], 10), + lineNumber: Number.parseInt(matches[1], 10), }); hasLineNumbers = true; diff --git a/lib/mapfiles/map-file-vs.ts b/lib/mapfiles/map-file-vs.ts index 848c63f50..195b611f5 100644 --- a/lib/mapfiles/map-file-vs.ts +++ b/lib/mapfiles/map-file-vs.ts @@ -32,7 +32,7 @@ export class MapFileReaderVS extends MapFileReader { override tryReadingPreferredAddress(line: string) { const matches = line.match(this.regexVSLoadAddress); if (matches) { - this.preferredLoadAddress = parseInt(matches[1], 16); + this.preferredLoadAddress = Number.parseInt(matches[1], 16); } } @@ -50,7 +50,7 @@ export class MapFileReaderVS extends MapFileReader { this.segments.push({ ...this.addressToObject(matches[1], matches[2]), id: this.segments.length + 1, - segmentLength: parseInt(matches[3], 16), + segmentLength: Number.parseInt(matches[3], 16), unitName: false, }); } @@ -62,10 +62,10 @@ export class MapFileReaderVS extends MapFileReader { override tryReadingNamedAddress(line: string) { const matches = line.match(this.regexVsNames); if (matches && matches.length >= 7 && matches[4] !== '') { - const addressWithOffset = parseInt(matches[4], 16); + const addressWithOffset = Number.parseInt(matches[4], 16); const symbolObject = { segment: matches[1], - addressWithoutOffset: parseInt(matches[2], 16), + addressWithoutOffset: Number.parseInt(matches[2], 16), addressInt: addressWithOffset, address: addressWithOffset.toString(16), displayName: matches[3], diff --git a/lib/mapfiles/map-file.ts b/lib/mapfiles/map-file.ts index ef8c65c8a..84222c6db 100644 --- a/lib/mapfiles/map-file.ts +++ b/lib/mapfiles/map-file.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import fs from 'fs'; +import fs from 'node:fs'; import * as utils from '../utils.js'; @@ -108,7 +108,8 @@ export class MapFileReader { const lineInfo = this.lineNumbers[idx]; if (!segment && lineInfo.addressInt === address) { return lineInfo; - } else if (segment === lineInfo.segment && lineInfo.addressWithoutOffset === address) { + } + if (segment === lineInfo.segment && lineInfo.addressWithoutOffset === address) { return lineInfo; } } @@ -126,7 +127,7 @@ export class MapFileReader { } } - return this.preferredLoadAddress + parseInt(segment, 16) * this.segmentMultiplier; + return this.preferredLoadAddress + Number.parseInt(segment, 16) * this.segmentMultiplier; } setSegmentOffset(segment: string, address: number) { @@ -196,7 +197,8 @@ export class MapFileReader { const info = this.segments[idx]; if (!segment && info.addressInt === address) { return info; - } else if (info.segment === segment && info.addressWithoutOffset === address) { + } + if (info.segment === segment && info.addressWithoutOffset === address) { return info; } } @@ -212,7 +214,8 @@ export class MapFileReader { const info = this.segments[idx]; if (!segment && address >= info.addressInt && address < info.addressInt + info.segmentLength) { return info; - } else if ( + } + if ( segment === info.segment && address >= info.addressWithoutOffset && address < info.addressWithoutOffset + info.segmentLength @@ -247,7 +250,8 @@ export class MapFileReader { const info = this.namedAddresses[idx]; if (!segment && info.addressInt === address) { return info; - } else if (segment === info.segment && info.addressWithoutOffset === address) { + } + if (segment === info.segment && info.addressWithoutOffset === address) { return info; } } @@ -286,7 +290,7 @@ export class MapFileReader { } addressToObject(segment: string, address: string): LineNumber { - const addressWithoutOffset = parseInt(address, 16); + const addressWithoutOffset = Number.parseInt(address, 16); const addressWithOffset = this.getSegmentOffset(segment) + addressWithoutOffset; return { diff --git a/lib/node-graceful.ts b/lib/node-graceful.ts index 2ee2ddbf0..ca2f71585 100644 --- a/lib/node-graceful.ts +++ b/lib/node-graceful.ts @@ -80,7 +80,7 @@ export class Graceful { } public static clear() { - Graceful.listeners.splice(0, Infinity); + Graceful.listeners.splice(0, Number.POSITIVE_INFINITY); Graceful.updateRegistration(); } @@ -115,7 +115,7 @@ export class Graceful { if (Number(Graceful.timeout)) { const timeoutRef = setTimeout(() => Graceful.killProcess(true), Graceful.timeout); - if (timeoutRef && timeoutRef.unref) timeoutRef.unref(); + if (timeoutRef?.unref) timeoutRef.unref(); } for (const listener of listeners) { diff --git a/lib/options-handler.ts b/lib/options-handler.ts index 3a9fcc7aa..faa3fdd3a 100755 --- a/lib/options-handler.ts +++ b/lib/options-handler.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import https from 'https'; -import path from 'path'; +import https from 'node:https'; +import path from 'node:path'; import fs from 'fs-extra'; import semverParser from 'semver'; @@ -233,29 +233,29 @@ export class ClientOptionsHandler { tools[lang] = {}; for (const tool of forLang.split(':')) { const toolBaseName = `tools.${tool}`; - const className = this.compilerProps(lang, toolBaseName + '.class'); + const className = this.compilerProps(lang, `${toolBaseName}.class`); const Tool = getToolTypeByKey(className); - const toolPath = this.compilerProps(lang, toolBaseName + '.exe'); + const toolPath = this.compilerProps(lang, `${toolBaseName}.exe`); if (fs.existsSync(toolPath)) { tools[lang][tool] = new Tool( { id: tool, - name: this.compilerProps(lang, toolBaseName + '.name'), - type: this.compilerProps(lang, toolBaseName + '.type') as ToolTypeKey, + name: this.compilerProps(lang, `${toolBaseName}.name`), + type: this.compilerProps(lang, `${toolBaseName}.type`) as ToolTypeKey, exe: toolPath, - exclude: splitIntoArray(this.compilerProps(lang, toolBaseName + '.exclude')), - includeKey: this.compilerProps(lang, toolBaseName + '.includeKey'), - options: splitArguments(this.compilerProps(lang, toolBaseName + '.options')), - args: this.compilerProps(lang, toolBaseName + '.args'), + exclude: splitIntoArray(this.compilerProps(lang, `${toolBaseName}.exclude`)), + includeKey: this.compilerProps(lang, `${toolBaseName}.includeKey`), + options: splitArguments(this.compilerProps(lang, `${toolBaseName}.options`)), + args: this.compilerProps(lang, `${toolBaseName}.args`), languageId: this.compilerProps( lang, - toolBaseName + '.languageId', + `${toolBaseName}.languageId`, ) as LanguageKey, - stdinHint: this.compilerProps(lang, toolBaseName + '.stdinHint'), - monacoStdin: this.compilerProps(lang, toolBaseName + '.monacoStdin'), - icon: this.compilerProps(lang, toolBaseName + '.icon'), - darkIcon: this.compilerProps(lang, toolBaseName + '.darkIcon'), + stdinHint: this.compilerProps(lang, `${toolBaseName}.stdinHint`), + monacoStdin: this.compilerProps(lang, `${toolBaseName}.monacoStdin`), + icon: this.compilerProps(lang, `${toolBaseName}.icon`), + darkIcon: this.compilerProps(lang, `${toolBaseName}.darkIcon`), compilerLanguage: lang as LanguageKey, }, { @@ -281,74 +281,74 @@ export class ClientOptionsHandler { for (const lib of forLang.split(':')) { const libBaseName = `libs.${lib}`; libraries[lang][lib] = { - name: this.compilerProps(lang, libBaseName + '.name'), - url: this.compilerProps(lang, libBaseName + '.url'), - description: this.compilerProps(lang, libBaseName + '.description'), - staticliblink: splitIntoArray(this.compilerProps(lang, libBaseName + '.staticliblink')), - liblink: splitIntoArray(this.compilerProps(lang, libBaseName + '.liblink')), - dependencies: splitIntoArray(this.compilerProps(lang, libBaseName + '.dependencies')), + name: this.compilerProps(lang, `${libBaseName}.name`), + url: this.compilerProps(lang, `${libBaseName}.url`), + description: this.compilerProps(lang, `${libBaseName}.description`), + staticliblink: splitIntoArray(this.compilerProps(lang, `${libBaseName}.staticliblink`)), + liblink: splitIntoArray(this.compilerProps(lang, `${libBaseName}.liblink`)), + dependencies: splitIntoArray(this.compilerProps(lang, `${libBaseName}.dependencies`)), versions: {}, - examples: splitIntoArray(this.compilerProps(lang, libBaseName + '.examples')), - options: splitArguments(this.compilerProps(lang, libBaseName + '.options', '')), - packagedheaders: this.compilerProps(lang, libBaseName + '.packagedheaders', false), + examples: splitIntoArray(this.compilerProps(lang, `${libBaseName}.examples`)), + options: splitArguments(this.compilerProps(lang, `${libBaseName}.options`, '')), + packagedheaders: this.compilerProps(lang, `${libBaseName}.packagedheaders`, false), }; - const listedVersions = `${this.compilerProps(lang, libBaseName + '.versions')}`; + const listedVersions = `${this.compilerProps(lang, `${libBaseName}.versions`)}`; if (listedVersions) { for (const version of listedVersions.split(':')) { - const libVersionName = libBaseName + `.versions.${version}`; + const libVersionName = `${libBaseName}.versions.${version}`; const versionObject: VersionInfo = { - version: this.compilerProps(lang, libVersionName + '.version'), + version: this.compilerProps(lang, `${libVersionName}.version`), staticliblink: splitIntoArray( - this.compilerProps(lang, libVersionName + '.staticliblink'), + this.compilerProps(lang, `${libVersionName}.staticliblink`), libraries[lang][lib].staticliblink, ), - alias: splitIntoArray(this.compilerProps(lang, libVersionName + '.alias')), + alias: splitIntoArray(this.compilerProps(lang, `${libVersionName}.alias`)), dependencies: splitIntoArray( - this.compilerProps(lang, libVersionName + '.dependencies'), + this.compilerProps(lang, `${libVersionName}.dependencies`), libraries[lang][lib].dependencies, ), path: [], libpath: [], liblink: splitIntoArray( - this.compilerProps(lang, libVersionName + '.liblink'), + this.compilerProps(lang, `${libVersionName}.liblink`), libraries[lang][lib].liblink, ), // Library options might get overridden later options: libraries[lang][lib].options, - hidden: this.compilerProps(lang, libVersionName + '.hidden', false), + hidden: this.compilerProps(lang, `${libVersionName}.hidden`, false), packagedheaders: libraries[lang][lib].packagedheaders, }; - const lookupversion = this.compilerProps(lang, libVersionName + '.lookupversion'); + const lookupversion = this.compilerProps(lang, `${libVersionName}.lookupversion`); if (lookupversion) { versionObject.lookupversion = lookupversion; } - const lookupname = this.compilerProps(lang, libVersionName + '.lookupname'); + const lookupname = this.compilerProps(lang, `${libVersionName}.lookupname`); if (lookupname) { versionObject.lookupname = lookupname; } - const includes = this.compilerProps(lang, libVersionName + '.path'); + const includes = this.compilerProps(lang, `${libVersionName}.path`); if (includes) { versionObject.path = includes.split(path.delimiter); } else if (version !== 'autodetect') { logger.warn(`Library ${lib} ${version} (${lang}) has no include paths`); } - const libpath = this.compilerProps(lang, libVersionName + '.libpath'); + const libpath = this.compilerProps(lang, `${libVersionName}.libpath`); if (libpath) { versionObject.libpath = libpath.split(path.delimiter); } - const options = this.compilerProps(lang, libVersionName + '.options'); + const options = this.compilerProps(lang, `${libVersionName}.options`); if (options !== undefined) { versionObject.options = splitArguments(options); } versionObject.packagedheaders = this.compilerProps( lang, - libVersionName + '.packagedheaders', + `${libVersionName}.packagedheaders`, libraries[lang][lib].packagedheaders, ); @@ -367,7 +367,7 @@ export class ClientOptionsHandler { let order = 0; // Set $order to index on array. As group is an array, iteration order is guaranteed. for (const lib of versions) { - lib['$order'] = order++; + lib.$order = order++; } } } @@ -376,7 +376,7 @@ export class ClientOptionsHandler { getRemoteId(remoteUrl: string, language: LanguageKey) { const url = new URL(remoteUrl); - return url.host.replaceAll('.', '_') + '_' + language; + return `${url.host.replaceAll('.', '_')}_${language}`; } libArrayToObject(libsArr: any[]) { @@ -398,7 +398,7 @@ export class ClientOptionsHandler { const remoteId = this.getRemoteId(remoteUrl, language); if (!this.remoteLibs[remoteId]) { return new Promise(resolve => { - const url = remoteUrl + '/api/libraries/' + language; + const url = `${remoteUrl}/api/libraries/${language}`; logger.info(`Fetching remote libraries from ${url}`); let fullData = ''; https.get(url, res => { @@ -473,7 +473,7 @@ export class ClientOptionsHandler { let order = 0; // Set $order to -index on array. As group is an array, iteration order is guaranteed. for (const compiler of group) { - compiler['$order'] = -order++; + compiler.$order = -order++; } } diff --git a/lib/packager.ts b/lib/packager.ts index 7bfae2f20..e5572e5b8 100644 --- a/lib/packager.ts +++ b/lib/packager.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import {promisify} from 'util'; +import {promisify} from 'node:util'; import TarGzip from 'node-targz'; diff --git a/lib/parsers/asm-parser-beebasm.ts b/lib/parsers/asm-parser-beebasm.ts index 3597f7fb4..a75d547ba 100644 --- a/lib/parsers/asm-parser-beebasm.ts +++ b/lib/parsers/asm-parser-beebasm.ts @@ -38,11 +38,11 @@ export class AsmParserBeebAsm extends AsmParser { if (addressAndInstructionMatch) { assert(addressAndInstructionMatch.groups); const opcodes = (addressAndInstructionMatch.groups.opcodes || '').split(' ').filter(x => !!x); - const address = parseInt(addressAndInstructionMatch.groups.address, 16); + const address = Number.parseInt(addressAndInstructionMatch.groups.address, 16); asmLines.push({ address: address, opcodes: opcodes, - text: ' ' + addressAndInstructionMatch.groups.disasm, + text: ` ${addressAndInstructionMatch.groups.disasm}`, }); } }); diff --git a/lib/parsers/asm-parser-cc65.ts b/lib/parsers/asm-parser-cc65.ts index e2b86b95d..5a923b505 100644 --- a/lib/parsers/asm-parser-cc65.ts +++ b/lib/parsers/asm-parser-cc65.ts @@ -95,7 +95,7 @@ export class CC65AsmParser extends AsmParser { if (match) { const label = match[1]; result.push({ - text: label + ' := ' + match[2], + text: `${label} := ${match[2]}`, }); labelDefinitions[label] = result.length + 1; continue; @@ -114,19 +114,19 @@ export class CC65AsmParser extends AsmParser { const address = label.match(this.labelAddressRe); if (address) { result.push({ - text: label + ':', - address: parseInt(address[1], 16), + text: `${label}:`, + address: Number.parseInt(address[1], 16), }); } else { result.push({ - text: label + ':', + text: `${label}:`, }); } labelDefinitions[label] = result.length + 1; result.push({ - text: ' ' + asmtext, + text: ` ${asmtext}`, labels: this.extractLabels(asmtext, 3), }); @@ -143,11 +143,9 @@ export class CC65AsmParser extends AsmParser { } result.push({ - text: ' ' + asmtext, + text: ` ${asmtext}`, labels: this.extractLabels(asmtext, 3), }); - - continue; } } diff --git a/lib/parsers/asm-parser-cpp.ts b/lib/parsers/asm-parser-cpp.ts index b01a659cf..ef5592781 100644 --- a/lib/parsers/asm-parser-cpp.ts +++ b/lib/parsers/asm-parser-cpp.ts @@ -47,11 +47,11 @@ export class AsmParserCpp implements IAsmParser { for (const line of utils.splitLines(asmResult)) { let advance = true; const match = line.match(lineRe); - if (match && match.groups) { + if (match?.groups) { // TODO perhaps we'll need to check the file here at some point in the future. // TODO I've temporarily disabled this as the result is visually too noisy // was: source = {file: null, line: parseInt(match.groups.line)}; - source = {file: match.groups.file, line: parseInt(match.groups.line)}; + source = {file: match.groups.file, line: Number.parseInt(match.groups.line)}; if (filters.directives) { continue; } diff --git a/lib/parsers/asm-parser-dart.ts b/lib/parsers/asm-parser-dart.ts index 642e16c1c..4a18d5d1d 100644 --- a/lib/parsers/asm-parser-dart.ts +++ b/lib/parsers/asm-parser-dart.ts @@ -93,11 +93,11 @@ export class DartAsmParser extends AsmParser { if (dontMaskFilenames) { source = { file: utils.maskRootdir(match[1]), - line: parseInt(match.groups.line), + line: Number.parseInt(match.groups.line), mainsource: true, }; } else { - source = {file: null, line: parseInt(match.groups.line), mainsource: true}; + source = {file: null, line: Number.parseInt(match.groups.line), mainsource: true}; } continue; } @@ -110,7 +110,7 @@ export class DartAsmParser extends AsmParser { func = match[2]; if (this.isUserFunction(func)) { asm.push({ - text: func + ':', + text: `${func}:`, source: null, labels: labelsInLine, }); @@ -134,9 +134,9 @@ export class DartAsmParser extends AsmParser { match = line.match(this.asmOpcodeRe); if (match) { assert(match.groups); - const address = parseInt(match.groups.address, 16); + const address = Number.parseInt(match.groups.address, 16); const opcodes = (match.groups.opcodes || '').split(' ').filter(x => !!x); - const disassembly = ' ' + AsmRegex.filterAsmLine(match.groups.disasm, filters); + const disassembly = ` ${AsmRegex.filterAsmLine(match.groups.disasm, filters)}`; const destMatch = line.match(this.destRe); if (destMatch) { const labelName = destMatch[2]; diff --git a/lib/parsers/asm-parser-dotnet.ts b/lib/parsers/asm-parser-dotnet.ts index c87f6456f..57ce62287 100644 --- a/lib/parsers/asm-parser-dotnet.ts +++ b/lib/parsers/asm-parser-dotnet.ts @@ -123,7 +123,7 @@ export class DotNetAsmParser implements IAsmParser { // ; Assembly listing for method ConsoleApplication.Program:Main(System.String[]) // ^ This character is the 31st character in this string. // `substring` removes the first 30 characters from it and uses the rest as a label. - cleanedAsm.push(line.substring(30) + ':'); + cleanedAsm.push(`${line.substring(30)}:`); continue; } @@ -156,16 +156,16 @@ export class DotNetAsmParser implements IAsmParser { for (const i in result.labelDef) { const label = result.labelDef[i]; - labelDefinitions.push([label.name, parseInt(i)]); + labelDefinitions.push([label.name, Number.parseInt(i)]); } for (const i in result.methodDef) { const method = result.methodDef[i]; - labelDefinitions.push([method, parseInt(i)]); + labelDefinitions.push([method, Number.parseInt(i)]); } for (const line in asmLines) { - if (result.labelDef[line] && result.labelDef[line].remove) continue; + if (result.labelDef[line]?.remove) continue; const labels: InlineLabel[] = []; const label = result.labelUsage[line] || result.methodUsage[line]; diff --git a/lib/parsers/asm-parser-ewavr.ts b/lib/parsers/asm-parser-ewavr.ts index 8d3f47343..9f401c0c9 100644 --- a/lib/parsers/asm-parser-ewavr.ts +++ b/lib/parsers/asm-parser-ewavr.ts @@ -102,18 +102,16 @@ export class AsmEWAVRParser extends AsmParser { const matches = line.match(this.filenameComment); if (matches) { return matches[3]; - } else { - return null; } + return null; }; const getLineNumberFromComment = (line: string) => { const matches = line.match(this.lineNumberComment); if (matches) { - return parseInt(matches[1]); - } else { - return null; + return Number.parseInt(matches[1]); } + return null; }; const asmLines = utils.splitLines(asm); diff --git a/lib/parsers/asm-parser-hexagon.ts b/lib/parsers/asm-parser-hexagon.ts index 4b163a21e..8d89abf38 100644 --- a/lib/parsers/asm-parser-hexagon.ts +++ b/lib/parsers/asm-parser-hexagon.ts @@ -40,7 +40,8 @@ export class HexagonAsmParser extends AsmParser { override checkVLIWpacket(line: string, inVLIWpacket: boolean) { if (this.vliwPacketBegin.test(line)) { return true; - } else if (this.vliwPacketEnd.test(line)) { + } + if (this.vliwPacketEnd.test(line)) { return false; } diff --git a/lib/parsers/asm-parser-mads.ts b/lib/parsers/asm-parser-mads.ts index 8bd6ce019..a36b1d635 100644 --- a/lib/parsers/asm-parser-mads.ts +++ b/lib/parsers/asm-parser-mads.ts @@ -82,13 +82,13 @@ export class MadsAsmParser extends AsmParser { ): ParsedAsmResultLine { const labelsInLine: AsmResultLabel[] = []; - const address = parseInt(matchGroups.address, 16); + const address = Number.parseInt(matchGroups.address, 16); const opcodes = (matchGroups.opcodes || '').split(' ').filter(x => !!x); let text = ''; if (matchGroups.label) { - text = matchGroups.label.trim() + ': '; + text = `${matchGroups.label.trim()}: `; } - const disassembly = ' ' + AsmRegex.filterAsmLine(matchGroups.disasm, filters); + const disassembly = ` ${AsmRegex.filterAsmLine(matchGroups.disasm, filters)}`; const destMatch = line.match(this.destRe); if (destMatch) { const labelName = destMatch[2]; @@ -170,12 +170,12 @@ export class MadsAsmParser extends AsmParser { match = line.match(this.standAloneLabel); if (match) { - const address = parseInt(match[1], 16); + const address = Number.parseInt(match[1], 16); const label = match[2]; labelDefinitions[label] = asm.length; asm.push({ address: address, - text: label + ':', + text: `${label}:`, }); continue; } @@ -198,19 +198,19 @@ export class MadsAsmParser extends AsmParser { const label = match[3]; labelDefinitions[label] = asm.length; asm.push({ - text: match[3] + ' ' + match[4], + text: `${match[3]} ${match[4]}`, }); continue; } match = line.match(this.varAssignment); if (match) { - const address = parseInt(match[1], 16); + const address = Number.parseInt(match[1], 16); const label = match[3]; labelDefinitions[label] = asm.length; asm.push({ address: address, - text: match[2] + match[3] + ' ' + match[4], + text: `${match[2] + match[3]} ${match[4]}`, }); continue; } diff --git a/lib/parsers/asm-parser-spirv.ts b/lib/parsers/asm-parser-spirv.ts index e11bcfd5b..509df2086 100644 --- a/lib/parsers/asm-parser-spirv.ts +++ b/lib/parsers/asm-parser-spirv.ts @@ -35,7 +35,7 @@ export class SPIRVAsmParser extends AsmParser { for (const line of asmLines) { const match = line.match(opString); if (match) { - const lineNum = parseInt(match[1]); + const lineNum = Number.parseInt(match[1]); files[lineNum] = match[2]; } } @@ -118,7 +118,7 @@ export class SPIRVAsmParser extends AsmParser { let inString = false; let source: any = null; - let lastLine: string = ''; + let lastLine = ''; for (let line of asmLines) { if (inString) { @@ -132,12 +132,12 @@ export class SPIRVAsmParser extends AsmParser { const match = line.match(sourceTag); if (match) { source = { - file: utils.maskRootdir(opStrings[parseInt(match[1])]), - line: parseInt(match[2]), + file: utils.maskRootdir(opStrings[Number.parseInt(match[1])]), + line: Number.parseInt(match[2]), mainsource: true, }; - const sourceCol = parseInt(match[3]); - if (!isNaN(sourceCol) && sourceCol !== 0) { + const sourceCol = Number.parseInt(match[3]); + if (!Number.isNaN(sourceCol) && sourceCol !== 0) { source.column = sourceCol; } // generators will tend to go diff --git a/lib/parsers/asm-parser-turboc.ts b/lib/parsers/asm-parser-turboc.ts index 5846646ce..15c00bf9a 100644 --- a/lib/parsers/asm-parser-turboc.ts +++ b/lib/parsers/asm-parser-turboc.ts @@ -83,12 +83,12 @@ export class TurboCAsmParser extends AsmParser { if (filters.dontMaskFilenames) { source = { file: currentfile, - line: parseInt(currentline), + line: Number.parseInt(currentline), }; } else { source = { file: null, - line: parseInt(currentline), + line: Number.parseInt(currentline), }; } } diff --git a/lib/parsers/asm-parser-vc.ts b/lib/parsers/asm-parser-vc.ts index cea34668f..e97f2f6c2 100644 --- a/lib/parsers/asm-parser-vc.ts +++ b/lib/parsers/asm-parser-vc.ts @@ -113,17 +113,15 @@ export class VcAsmParser extends AsmParser { const matches = line.match(this.filenameComment); if (matches) { return matches[1]; - } else { - return null; } + return null; }; const getLineNumberFromComment = (line: string) => { const matches = line.match(this.lineNumberComment); if (matches) { - return parseInt(matches[1]); - } else { - return null; + return Number.parseInt(matches[1]); } + return null; }; const asmLines = utils.splitLines(asm); @@ -187,7 +185,7 @@ export class VcAsmParser extends AsmParser { const checkForDdefLabel = (line: string) => { const ddef = line.match(this.dataDefn); - if (ddef && ddef[1]) { + if (ddef?.[1]) { datadefLabels.push(ddef[1]); } }; @@ -320,10 +318,9 @@ export class VcAsmParser extends AsmParser { // order by name if (f1.initialLine === f2.initialLine) { return collator.compare(f1.name || '', f2.name || ''); - } else { - // NOTE: initialLine can be undefined here, that's ok - return (f1.initialLine as number) - (f2.initialLine as number); } + // NOTE: initialLine can be undefined here, that's ok + return (f1.initialLine as number) - (f2.initialLine as number); } // else, order by file diff --git a/lib/parsers/asm-parser-z88dk.ts b/lib/parsers/asm-parser-z88dk.ts index 5672fcf46..4f5ff49b7 100644 --- a/lib/parsers/asm-parser-z88dk.ts +++ b/lib/parsers/asm-parser-z88dk.ts @@ -61,7 +61,7 @@ export class AsmParserZ88dk extends AsmParser { const handleSource = (line: string) => { const match = line.match(this.sourceTag); if (match) { - const sourceLine = parseInt(match[1]); + const sourceLine = Number.parseInt(match[1]); const file = utils.maskRootdir(match[2]); if (file) { if (dontMaskFilenames) { @@ -76,8 +76,8 @@ export class AsmParserZ88dk extends AsmParser { line: sourceLine, }; } - const sourceCol = parseInt(match[3]); - if (!isNaN(sourceCol) && sourceCol !== 0) { + const sourceCol = Number.parseInt(match[3]); + if (!Number.isNaN(sourceCol) && sourceCol !== 0) { source.column = sourceCol; } } else { @@ -230,9 +230,9 @@ export class AsmParserZ88dk extends AsmParser { const match = line.match(this.asmOpcodeRe); if (match) { assert(match.groups); - const address = parseInt(match.groups.address, 16); + const address = Number.parseInt(match.groups.address, 16); const opcodes = (match.groups.opcodes || '').split(' ').filter(x => !!x); - const disassembly = ' ' + AsmRegex.filterAsmLine(match.groups.disasm.trim(), filters); + const disassembly = ` ${AsmRegex.filterAsmLine(match.groups.disasm.trim(), filters)}`; const destMatch = line.match(this.destRe); if (destMatch) { const labelName = destMatch[2]; diff --git a/lib/parsers/asm-parser.ts b/lib/parsers/asm-parser.ts index 70034d264..f581e6a56 100644 --- a/lib/parsers/asm-parser.ts +++ b/lib/parsers/asm-parser.ts @@ -169,7 +169,7 @@ export class AsmParser extends AsmRegex implements IAsmParser { return inVLIWpacket; } - hasOpcode(line: string, inNvccCode: boolean = false, inVLIWpacket: boolean = false) { + hasOpcode(line: string, inNvccCode = false, inVLIWpacket = false) { // Remove any leading label definition... const match = line.match(this.labelDef); if (match) { @@ -310,13 +310,13 @@ export class AsmParser extends AsmRegex implements IAsmParser { for (const line of asmLines) { const match = line.match(this.fileFind); if (match) { - const lineNum = parseInt(match[1]); + const lineNum = Number.parseInt(match[1]); if (match[4] && !line.includes('.cv_file')) { // Clang-style file directive '.file X "dir" "filename"' if (match[4].startsWith('/')) { files[lineNum] = match[4]; } else { - files[lineNum] = match[2] + '/' + match[4]; + files[lineNum] = `${match[2]}/${match[4]}`; } } else { files[lineNum] = match[2]; @@ -389,8 +389,8 @@ export class AsmParser extends AsmRegex implements IAsmParser { protected handleSource(context: ParsingContext, line: string) { let match = line.match(this.sourceTag); if (match) { - const file = utils.maskRootdir(context.files[parseInt(match[1])]); - const sourceLine = parseInt(match[2]); + const file = utils.maskRootdir(context.files[Number.parseInt(match[1])]); + const sourceLine = Number.parseInt(match[2]); if (file) { if (context.dontMaskFilenames) { context.source = { @@ -404,8 +404,8 @@ export class AsmParser extends AsmRegex implements IAsmParser { line: sourceLine, }; } - const sourceCol = parseInt(match[3]); - if (!isNaN(sourceCol) && sourceCol !== 0) { + const sourceCol = Number.parseInt(match[3]); + if (!Number.isNaN(sourceCol) && sourceCol !== 0) { context.source.column = sourceCol; } } else { @@ -414,7 +414,7 @@ export class AsmParser extends AsmRegex implements IAsmParser { } else { match = line.match(this.sourceD2Tag); if (match) { - const sourceLine = parseInt(match[1]); + const sourceLine = Number.parseInt(match[1]); context.source = { file: null, line: sourceLine, @@ -423,8 +423,8 @@ export class AsmParser extends AsmRegex implements IAsmParser { match = line.match(this.sourceCVTag); if (match) { // cv_loc reports: function file line column - const sourceLine = parseInt(match[3]); - const file = utils.maskRootdir(context.files[parseInt(match[2])]); + const sourceLine = Number.parseInt(match[3]); + const file = utils.maskRootdir(context.files[Number.parseInt(match[2])]); if (context.dontMaskFilenames) { context.source = { file: file, @@ -437,8 +437,8 @@ export class AsmParser extends AsmRegex implements IAsmParser { line: sourceLine, }; } - const sourceCol = parseInt(match[4]); - if (!isNaN(sourceCol) && sourceCol !== 0) { + const sourceCol = Number.parseInt(match[4]); + if (!Number.isNaN(sourceCol) && sourceCol !== 0) { context.source.column = sourceCol; } } @@ -450,9 +450,9 @@ export class AsmParser extends AsmRegex implements IAsmParser { const match = line.match(this.sourceStab); if (!match) return; // cf http://www.math.utah.edu/docs/info/stabs_11.html#SEC48 - switch (parseInt(match[1])) { + switch (Number.parseInt(match[1])) { case 68: { - context.source = {file: null, line: parseInt(match[2])}; + context.source = {file: null, line: Number.parseInt(match[2])}; break; } case 132: @@ -468,7 +468,7 @@ export class AsmParser extends AsmRegex implements IAsmParser { const match = line.match(this.source6502Dbg); if (match) { const file = utils.maskRootdir(match[1]); - const sourceLine = parseInt(match[2]); + const sourceLine = Number.parseInt(match[2]); if (context.dontMaskFilenames) { context.source = { file: file, @@ -682,9 +682,8 @@ export class AsmParser extends AsmRegex implements IAsmParser { const match = line.match(this.indentedLabelDef); if (match) { return line.replace(/^\s+/, ''); - } else { - return line; } + return line; } isUserFunction(func: string) { @@ -735,11 +734,11 @@ export class AsmParser extends AsmRegex implements IAsmParser { if (dontMaskFilenames) { source = { file: utils.maskRootdir(match[1]), - line: parseInt(match.groups.line), + line: Number.parseInt(match.groups.line), mainsource: true, }; } else { - source = {file: null, line: parseInt(match.groups.line), mainsource: true}; + source = {file: null, line: Number.parseInt(match.groups.line), mainsource: true}; } continue; } @@ -749,7 +748,7 @@ export class AsmParser extends AsmRegex implements IAsmParser { func = match[2]; if (func && this.isUserFunction(func)) { asm.push({ - text: func + ':', + text: `${func}:`, source: null, labels: labelsInLine, }); @@ -776,16 +775,15 @@ export class AsmParser extends AsmRegex implements IAsmParser { mayRemovePreviousLabel = false; } continue; - } else { - mayRemovePreviousLabel = true; } + mayRemovePreviousLabel = true; match = line.match(this.asmOpcodeRe); if (match) { assert(match.groups); - const address = parseInt(match.groups.address, 16); + const address = Number.parseInt(match.groups.address, 16); const opcodes = (match.groups.opcodes || '').split(' ').filter(x => !!x); - const disassembly = ' ' + AsmRegex.filterAsmLine(match.groups.disasm, filters); + const disassembly = ` ${AsmRegex.filterAsmLine(match.groups.disasm, filters)}`; const destMatch = line.match(this.destRe); if (destMatch) { const labelName = destMatch[2]; @@ -810,7 +808,7 @@ export class AsmParser extends AsmRegex implements IAsmParser { match = line.match(this.relocationRe); if (match) { assert(match.groups); - const address = parseInt(match.groups.address, 16); + const address = Number.parseInt(match.groups.address, 16); const relocname = match.groups.relocname; const relocdata = match.groups.relocdata; // value/addend matched but not used yet. diff --git a/lib/parsers/asm-raw.ts b/lib/parsers/asm-raw.ts index 8c9c99ab3..b8e66f782 100644 --- a/lib/parsers/asm-raw.ts +++ b/lib/parsers/asm-raw.ts @@ -43,21 +43,20 @@ export class AsmRaw extends AsmRegex { for (const line of asmLines) { let match = line.match(labelRe); if (match) { - result.push({text: match[2] + ':', source: null}); + result.push({text: `${match[2]}:`, source: null}); + continue; + } + match = line.match(this.labelDef); + if (match) { + result.push({text: `${match[1]}:`, source: null}); continue; - } else { - match = line.match(this.labelDef); - if (match) { - result.push({text: match[1] + ':', source: null}); - continue; - } } match = line.match(asmOpcodeRe); if (match) { - const address = parseInt(match[1], 16); + const address = Number.parseInt(match[1], 16); const opcodes = match[2].split(' ').filter(Boolean); - const disassembly = ' ' + AsmRegex.filterAsmLine(match[4], filters); + const disassembly = ` ${AsmRegex.filterAsmLine(match[4], filters)}`; let links: AsmResultLink[] | undefined; const destMatch = line.match(destRe); if (destMatch) { @@ -65,7 +64,7 @@ export class AsmRaw extends AsmRegex { { offset: disassembly.indexOf(destMatch[1]), length: destMatch[1].length, - to: parseInt(destMatch[1], 16), + to: Number.parseInt(destMatch[1], 16), }, ]; } diff --git a/lib/parsers/asmregex.ts b/lib/parsers/asmregex.ts index a5c2d8ff4..714bde8e5 100644 --- a/lib/parsers/asmregex.ts +++ b/lib/parsers/asmregex.ts @@ -38,9 +38,9 @@ export class AsmRegex { const quotes = line.match(findQuotes); if (quotes) { return ( - this.squashHorizontalWhitespace(quotes[1], atStart) + + AsmRegex.squashHorizontalWhitespace(quotes[1], atStart) + quotes[2] + - this.squashHorizontalWhitespace(quotes[3], false) + AsmRegex.squashHorizontalWhitespace(quotes[3], false) ); } return utils.squashHorizontalWhitespace(line, atStart); @@ -48,6 +48,6 @@ export class AsmRegex { static filterAsmLine(line: string, filters: ParseFiltersAndOutputOptions): string { if (!filters.trim) return line; - return this.squashHorizontalWhitespace(line, true); + return AsmRegex.squashHorizontalWhitespace(line, true); } } diff --git a/lib/parsers/dex2oat-pass-dump-parser.ts b/lib/parsers/dex2oat-pass-dump-parser.ts index 9d46a30ef..55e526743 100644 --- a/lib/parsers/dex2oat-pass-dump-parser.ts +++ b/lib/parsers/dex2oat-pass-dump-parser.ts @@ -130,7 +130,7 @@ export class Dex2OatPassDumpParser { pass.after = currentDump.lines; i++; } else if (currentDump.name.endsWith(' (before)')) { - if (nextDump !== null && nextDump.name.endsWith(' (after)')) { + if (nextDump?.name.endsWith(' (after)')) { assert(passesMatch(currentDump.name, nextDump.name), '', currentDump.name, nextDump.name); pass.name = currentDump.name.slice(0, currentDump.name.length - ' (before)'.length); pass.before = currentDump.lines; diff --git a/lib/parsers/llvm-pass-dump-parser.ts b/lib/parsers/llvm-pass-dump-parser.ts index e9038eea5..661c471fe 100644 --- a/lib/parsers/llvm-pass-dump-parser.ts +++ b/lib/parsers/llvm-pass-dump-parser.ts @@ -205,7 +205,7 @@ export class LlvmPassDumpParser { name: string; lines: ResultLine[]; } | null = null; - let isMachineFunctionOpen: boolean = false; + let isMachineFunctionOpen = false; for (const line of dump.lines) { const irFnMatch = line.text.match(this.functionDefine); const machineFnMatch = line.text.match(this.machineFunctionBegin); @@ -249,11 +249,10 @@ export class LlvmPassDumpParser { if (line.text.trim() === '') { // may be a blank line continue; - } else { - ///console.log('ignoring ------>', line.text); - // ignore - continue; } + ///console.log('ignoring ------>', line.text); + // ignore + continue; } func.lines.push(line); } @@ -383,7 +382,7 @@ export class LlvmPassDumpParser { pass.after = current_dump.lines; i++; } else if (current_dump.header.startsWith('IR Dump Before ')) { - if (next_dump !== null && next_dump.header.startsWith('IR Dump After ')) { + if (next_dump?.header.startsWith('IR Dump After ')) { assert( passesMatch(current_dump.header, next_dump.header), '', @@ -437,15 +436,14 @@ export class LlvmPassDumpParser { const passDumpsByFunction = this.associateFullDumpsWithFunctions(raw_passes); // Match before / after pass dumps and we're done return this.matchPassDumps(passDumpsByFunction); - } else { - // Further break down by functions in each dump - const passDumps = raw_passes.map(this.breakdownPassDumpsIntoFunctions.bind(this)); - // Transform array of passes containing multiple functions into a map from functions to arrays of passes on - // those functions - const passDumpsByFunction = this.breakdownIntoPassDumpsByFunction(passDumps); - // Match before / after pass dumps and we're done - return this.matchPassDumps(passDumpsByFunction); } + // Further break down by functions in each dump + const passDumps = raw_passes.map(this.breakdownPassDumpsIntoFunctions.bind(this)); + // Transform array of passes containing multiple functions into a map from functions to arrays of passes on + // those functions + const passDumpsByFunction = this.breakdownIntoPassDumpsByFunction(passDumps); + // Match before / after pass dumps and we're done + return this.matchPassDumps(passDumpsByFunction); } applyIrFilters(ir: ResultLine[], optPipelineOptions: OptPipelineBackendOptions) { @@ -475,9 +473,8 @@ export class LlvmPassDumpParser { } if (newLine === line) { break; - } else { - line = newLine; } + line = newLine; } _line.text = line; return _line; diff --git a/lib/parsers/racket-pass-dump-parser.ts b/lib/parsers/racket-pass-dump-parser.ts index 5dda6a5bf..5c63c742c 100644 --- a/lib/parsers/racket-pass-dump-parser.ts +++ b/lib/parsers/racket-pass-dump-parser.ts @@ -116,7 +116,7 @@ export class RacketPassDumpParser { } const linkletPhaseMatch = line.text.match(this.linkletPhaseHeader); if (linkletPhaseMatch) { - linkletPhase = parseInt(linkletPhaseMatch[1]); + linkletPhase = Number.parseInt(linkletPhaseMatch[1]); continue; } const stepMatch = line.text.match(this.stepHeader); @@ -277,9 +277,8 @@ export class RacketPassDumpParser { } if (newLine === line) { break; - } else { - line = newLine; } + line = newLine; } resultLine.text = line; return resultLine; diff --git a/lib/pe32-support.ts b/lib/pe32-support.ts index 127b7427c..bdbb5b9c7 100644 --- a/lib/pe32-support.ts +++ b/lib/pe32-support.ts @@ -119,7 +119,8 @@ export class PELabelReconstructor { } } } else { - let idx, info; + let idx; + let info; for (idx = 0; idx < this.mapFileReader.segments.length; idx++) { info = this.mapFileReader.segments[idx]; if (info.unitName !== unitName) { @@ -139,7 +140,8 @@ export class PELabelReconstructor { deleteSystemUnits() { const systemUnits = new Set(['SysInit.pas', 'System.pas', 'SysUtils.pas', 'Classes.pas']); - let idx, info; + let idx; + let info; for (idx = 0; idx < this.mapFileReader.segments.length; idx++) { info = this.mapFileReader.segments[idx]; if (info.unitName && systemUnits.has(info.unitName)) { @@ -165,7 +167,7 @@ export class PELabelReconstructor { const matches = line.match(this.addressRegex); if (matches) { - const lineAddr = parseInt(matches[1], 16); + const lineAddr = Number.parseInt(matches[1], 16); if (startIdx === -1 && lineAddr >= beginAddress) { startIdx = lineIdx; if (line.endsWith(':') || line.endsWith('<.text>:') || line.endsWith('<.itext>:')) { @@ -196,16 +198,16 @@ export class PELabelReconstructor { if (matches) { const address = matches[3]; if (!address.includes('+') && !address.includes('-')) { - let labelName = 'L' + address; - const namedAddr = this.mapFileReader.getSymbolAt(undefined, parseInt(address, 16)); - if (namedAddr && namedAddr.displayName) { + let labelName = `L${address}`; + const namedAddr = this.mapFileReader.getSymbolAt(undefined, Number.parseInt(address, 16)); + if (namedAddr?.displayName) { labelName = namedAddr.displayName; } if (!this.dontLabelUnmappedAddresses || namedAddr) { this.addressesToLabel.push(address); - this.asmLines[lineIdx] = line.replace(regex, ' ' + matches[1] + matches[2] + labelName); + this.asmLines[lineIdx] = line.replace(regex, ` ${matches[1]}${matches[2]}${labelName}`); } } } @@ -236,7 +238,7 @@ export class PELabelReconstructor { const matches = line.match(this.addressRegex); if (matches) { const addressStr = matches[1]; - const address = parseInt(addressStr, 16); + const address = Number.parseInt(addressStr, 16); const segmentInfo = this.mapFileReader.getSegmentInfoByStartingAddress(undefined, address); if (segmentInfo) { @@ -254,17 +256,17 @@ export class PELabelReconstructor { // todo: the call might be in <.itext>, should we include that part of the assembly? namedAddr = this.mapFileReader.getSymbolAt(undefined, address); if (namedAddr) { - labelLine = matches[1] + ' <' + namedAddr.displayName + '>:'; + labelLine = `${matches[1]} <${namedAddr.displayName}>:`; this.asmLines.splice(lineIdx, 0, labelLine); lineIdx++; } } else { - labelLine = matches[1] + ' :'; + labelLine = `${matches[1]} :`; namedAddr = this.mapFileReader.getSymbolAt(undefined, address); if (namedAddr) { - labelLine = matches[1] + ' <' + namedAddr.displayName + '>:'; + labelLine = `${matches[1]} <${namedAddr.displayName}>:`; } if (!this.dontLabelUnmappedAddresses || namedAddr) { @@ -275,10 +277,10 @@ export class PELabelReconstructor { const lineInfo = this.mapFileReader.getLineInfoByAddress(undefined, address); if (lineInfo && currentSegment && currentSegment.unitName) { - this.asmLines.splice(lineIdx, 0, '/app/' + currentSegment.unitName + ':' + lineInfo.lineNumber); + this.asmLines.splice(lineIdx, 0, `/app/${currentSegment.unitName}:${lineInfo.lineNumber}`); lineIdx++; } else if (segmentChanged && currentSegment) { - this.asmLines.splice(lineIdx, 0, '/app/' + currentSegment.unitName + ':0'); + this.asmLines.splice(lineIdx, 0, `/app/${currentSegment.unitName}:0`); lineIdx++; } } diff --git a/lib/properties.ts b/lib/properties.ts index ae6efda7b..ea9fe34ab 100644 --- a/lib/properties.ts +++ b/lib/properties.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import fs from 'fs'; -import path from 'path'; +import fs from 'node:fs'; +import path from 'node:path'; import _ from 'underscore'; @@ -107,7 +107,7 @@ export function initialize(directory: string, hier: string[]) { for (let file of propertyFiles) { const baseName = file.replace(endsWith, ''); file = path.join(directory, file); - debug('Reading config from ' + file); + debug(`Reading config from ${file}`); properties[baseName] = parseProperties(fs.readFileSync(file, 'utf8'), file); } logger.debug('props.properties = ', properties); @@ -120,9 +120,7 @@ export function reset() { } export function propsFor(base: string): PropertyGetter { - return function (property: string, defaultValue: any) { - return get(base, property, defaultValue); - }; + return (property: string, defaultValue: any) => get(base, property, defaultValue); } // function mappedOf(fn, funcA, funcB) { @@ -264,16 +262,14 @@ export class CompilerProps { if (isString(langs)) { if (this.propsByLangId[langs]) { return map_fn(this.$getInternal(langs, key, defaultValue), this.languages[langs]); - } else { - logger.error(`Tried to pass ${langs} as a language ID`); - return map_fn(defaultValue); } - } else { - return _.chain(langs) - .map(lang => [lang.id, map_fn(this.$getInternal(lang.id, key, defaultValue), lang)]) - .object() - .value(); + logger.error(`Tried to pass ${langs} as a language ID`); + return map_fn(defaultValue); } + return _.chain(langs) + .map(lang => [lang.id, map_fn(this.$getInternal(lang.id, key, defaultValue), lang)]) + .object() + .value(); } } diff --git a/lib/runtime-tools/heaptrack-wrapper.ts b/lib/runtime-tools/heaptrack-wrapper.ts index 80e6effb2..89e3595ba 100644 --- a/lib/runtime-tools/heaptrack-wrapper.ts +++ b/lib/runtime-tools/heaptrack-wrapper.ts @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import * as fs from 'fs'; -import * as net from 'net'; +import * as fs from 'node:fs'; import {constants as fsConstants} from 'node:fs'; -import path from 'path'; -import {pipeline} from 'stream'; +import * as net from 'node:net'; +import path from 'node:path'; +import {pipeline} from 'node:stream'; import {ExecutionOptions} from '../../types/compilation/compilation.interfaces.js'; import { @@ -94,7 +94,7 @@ export class HeaptrackWrapper extends BaseRuntimeTool { if (!execOptions.env) execOptions.env = {}; if (execOptions.env.LD_PRELOAD) { - execOptions.env.LD_PRELOAD = this.preload + ':' + execOptions.env.LD_PRELOAD; + execOptions.env.LD_PRELOAD = `${this.preload}:${execOptions.env.LD_PRELOAD}`; } else { execOptions.env.LD_PRELOAD = this.preload; } diff --git a/lib/sentry.ts b/lib/sentry.ts index 5b46348f8..621b05f1d 100644 --- a/lib/sentry.ts +++ b/lib/sentry.ts @@ -32,7 +32,7 @@ import {PropertyGetter} from './properties.interfaces.js'; function shouldRedactRequestData(data: string) { try { const parsed = JSON.parse(data); - return !parsed['allowStoreCodeDebug']; + return !parsed.allowStoreCodeDebug; } catch (e) { return true; } @@ -55,7 +55,7 @@ export function SetupSentry( release: releaseBuildNumber || gitReleaseName, environment: sentryEnv || defArgs.env[0], beforeSend(event) { - if (event.request && event.request.data && shouldRedactRequestData(event.request.data)) { + if (event.request?.data && shouldRedactRequestData(event.request.data)) { event.request.data = JSON.stringify({redacted: true}); } return event; @@ -74,13 +74,9 @@ export function SentryCapture(value: unknown, context?: string) { const e = new Error(); // eslint-disable-line unicorn/error-message const trace = parse(e); Sentry.captureMessage( - `Non-Error capture:\n` + - (context ? `Context: ${context}\n` : '') + - `Data:\n${JSON.stringify(value)}\n` + - `Trace:\n` + - trace - .map(frame => `${frame.functionName} ${frame.fileName}:${frame.lineNumber}:${frame.columnNumber}`) - .join('\n'), + `Non-Error capture:\n${context ? `Context: ${context}\n` : ''}Data:\n${JSON.stringify(value)}\nTrace:\n${trace + .map(frame => `${frame.functionName} ${frame.fileName}:${frame.lineNumber}:${frame.columnNumber}`) + .join('\n')}`, ); } } diff --git a/lib/shortener/google.ts b/lib/shortener/google.ts index 3eb9459a1..ee75f204c 100644 --- a/lib/shortener/google.ts +++ b/lib/shortener/google.ts @@ -36,7 +36,7 @@ export class ShortLinkResolver { reject(`Got response ${res.statusCode}`); return; } - const targetLocation = res.headers['location']; + const targetLocation = res.headers.location; if (!targetLocation) { reject(`Missing location url in ${targetLocation}`); return; diff --git a/lib/shortener/tinyurl.ts b/lib/shortener/tinyurl.ts index 8e37036be..a27377e0c 100644 --- a/lib/shortener/tinyurl.ts +++ b/lib/shortener/tinyurl.ts @@ -31,7 +31,7 @@ export class TinyUrlShortener extends BaseShortener { override handle(req: express.Request, res: express.Response) { const url = `${req.protocol}://${req.get('host')}#${req.body.config}`; const options = { - url: 'https://tinyurl.com/api-create.php?url=' + encodeURIComponent(url), + url: `https://tinyurl.com/api-create.php?url=${encodeURIComponent(url)}`, method: 'GET', }; const callback = (err: any, resp: request.Response, body: any) => { diff --git a/lib/sources/builtin.ts b/lib/sources/builtin.ts index 73531b0c0..bc51c142c 100644 --- a/lib/sources/builtin.ts +++ b/lib/sources/builtin.ts @@ -22,16 +22,16 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import fs from 'fs'; -import fsp from 'fs/promises'; -import path from 'path'; +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; import * as props from '../properties.js'; import type {Source, SourceEntry} from './index.js'; const EXAMPLES_PATH = props.get('builtin', 'sourcePath', './examples/') as string; -const NAME_SUBSTUTION_PATTERN = new RegExp('_', 'g'); +const NAME_SUBSTUTION_PATTERN = /_/g; const ALL_EXAMPLES: SourceEntry[] = fs.readdirSync(EXAMPLES_PATH).flatMap(folder => { // Recurse through the language folders const folderPath = path.join(EXAMPLES_PATH, folder); diff --git a/lib/sponsors.ts b/lib/sponsors.ts index e4c96c954..8ab8c457a 100644 --- a/lib/sponsors.ts +++ b/lib/sponsors.ts @@ -27,7 +27,7 @@ import yaml from 'yaml'; import type {Level, Sponsor, Sponsors} from './sponsors.interfaces.js'; export function parse(mapOrString: Record | string): Sponsor { - if (typeof mapOrString == 'string') mapOrString = {name: mapOrString}; + if (typeof mapOrString === 'string') mapOrString = {name: mapOrString}; const displayType = mapOrString.displayType || 'Above'; const style: Record = {}; if (mapOrString.bgColour) { @@ -80,7 +80,7 @@ function sponsorIconSetsOk( ): boolean { const countsByShowEvery: Map = new Map(); for (const [icon, count] of sponsorAppearanceCount.entries()) { - const seenEvery = count > 0 ? totalAppearances / count : Infinity; + const seenEvery = count > 0 ? totalAppearances / count : Number.POSITIVE_INFINITY; if (seenEvery > icon.topIconShowEvery) { return false; } diff --git a/lib/stack-usage-transformer.ts b/lib/stack-usage-transformer.ts index 15becdb84..89782cf8c 100644 --- a/lib/stack-usage-transformer.ts +++ b/lib/stack-usage-transformer.ts @@ -47,8 +47,8 @@ export function parse(suText: string): StackUsageInfo[] { DebugLoc: {File: pathLocName[0], Line: lineNumber, Column: 0}, Function: pathLocName.at(-1), Qualifier: qualifier, - BytesUsed: parseInt(c[1]), - displayString: c[1] + ' bytes, ' + qualifier, + BytesUsed: Number.parseInt(c[1]), + displayString: `${c[1]} bytes, ${qualifier}`, }; output.push(su as StackUsageInfo); } diff --git a/lib/stats.ts b/lib/stats.ts index 7ea59c2e4..69412096c 100644 --- a/lib/stats.ts +++ b/lib/stats.ts @@ -102,7 +102,7 @@ export function makeSafe( ), ).map(item => `${item[0]}=${item[1] ? '1' : '0'}`), bypassCache: !!request.bypassCache, - libraries: (request.libraries || []).map((lib: SelectedLibraryVersion) => lib.id + '/' + lib.version), + libraries: (request.libraries || []).map((lib: SelectedLibraryVersion) => `${lib.id}/${lib.version}`), tools: (request.tools || []).map(tool => tool.id), overrides: ((request.backendOptions.overrides || []) as CompilerOverrideOptions) .filter(item => item.name !== 'env' && item.value) diff --git a/lib/storage/base.ts b/lib/storage/base.ts index f332fc76d..93968f244 100644 --- a/lib/storage/base.ts +++ b/lib/storage/base.ts @@ -95,7 +95,8 @@ export abstract class StorageBase { static configFor(req: express.Request) { if (req.body.config) { return req.body.config; - } else if (req.body.sessions) { + } + if (req.body.sessions) { return req.body; } return null; @@ -119,16 +120,15 @@ export abstract class StorageBase { ); if (result.alreadyPresent) { return result; - } else { - const storedObject: StoredObject = { - prefix: result.prefix, - uniqueSubHash: result.uniqueSubHash, - fullHash: configHash, - config: config, - }; - - return this.storeItem(storedObject, req); } + const storedObject: StoredObject = { + prefix: result.prefix, + uniqueSubHash: result.uniqueSubHash, + fullHash: configHash, + config: config, + }; + + return this.storeItem(storedObject, req); }) .then(result => { res.send({url: `${req.protocol}://${req.get('host')}${this.httpRootDir}z/${result.uniqueSubHash}`}); diff --git a/lib/storage/local.ts b/lib/storage/local.ts index 6846d0912..b921a2840 100644 --- a/lib/storage/local.ts +++ b/lib/storage/local.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; import _ from 'underscore'; @@ -81,19 +81,18 @@ export class StorageLocal extends StorageBase { uniqueSubHash: subHash, alreadyPresent: false, }; - } else { - const expectedPath = path.join(this.storageFolder, subHash); - const item = await fs.readJson(expectedPath); - /* If the hashes coincide, it means this config has already been stored. - * Else, keep looking - */ - if (item.fullHash === hash) { - return { - prefix: prefix, - uniqueSubHash: subHash, - alreadyPresent: true, - }; - } + } + const expectedPath = path.join(this.storageFolder, subHash); + const item = await fs.readJson(expectedPath); + /* If the hashes coincide, it means this config has already been stored. + * Else, keep looking + */ + if (item.fullHash === hash) { + return { + prefix: prefix, + uniqueSubHash: subHash, + alreadyPresent: true, + }; } } } catch (err) { diff --git a/lib/storage/remote.ts b/lib/storage/remote.ts index 340167c04..7028a3214 100644 --- a/lib/storage/remote.ts +++ b/lib/storage/remote.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import {promisify} from 'util'; +import {promisify} from 'node:util'; import * as express from 'express'; import request from 'request'; diff --git a/lib/storage/s3.ts b/lib/storage/s3.ts index 2130c88ac..340948384 100644 --- a/lib/storage/s3.ts +++ b/lib/storage/s3.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import assert from 'assert'; +import assert from 'node:assert'; import {DynamoDB} from '@aws-sdk/client-dynamodb'; import * as express from 'express'; @@ -142,18 +142,17 @@ export class StorageS3 extends StorageBase { uniqueSubHash: subHash, alreadyPresent: false, }; - } else { - const itemHash = fullHashes[index]; - /* If the hashes coincide, it means this config has already been stored. - * Else, keep looking - */ - if (itemHash === hash) { - return { - prefix: prefix, - uniqueSubHash: subHash, - alreadyPresent: true, - }; - } + } + const itemHash = fullHashes[index]; + /* If the hashes coincide, it means this config has already been stored. + * Else, keep looking + */ + if (itemHash === hash) { + return { + prefix: prefix, + uniqueSubHash: subHash, + alreadyPresent: true, + }; } } throw new Error(`Could not find unique subhash for hash "${hash}"`); @@ -185,7 +184,7 @@ export class StorageS3 extends StorageBase { if (attributes.named_metadata) link.specialMetadata = attributes.named_metadata.M; - if (attributes.creation_date && attributes.creation_date.S) link.created = new Date(attributes.creation_date.S); + if (attributes.creation_date?.S) link.created = new Date(attributes.creation_date.S); return link; } diff --git a/lib/symbol-store.ts b/lib/symbol-store.ts index da6645486..df9f2e92b 100644 --- a/lib/symbol-store.ts +++ b/lib/symbol-store.ts @@ -63,7 +63,7 @@ export class SymbolStore { softExclude(otherStore: SymbolStore) { for (const symbol in otherStore.uniqueSymbols) { let shouldExclude = false; - let checksymbol: string = ''; + let checksymbol = ''; for (checksymbol in this.uniqueSymbols) { if (checksymbol.endsWith(symbol)) { shouldExclude = true; diff --git a/lib/toolchain-utils.ts b/lib/toolchain-utils.ts index b0a621ba5..50b4c6973 100644 --- a/lib/toolchain-utils.ts +++ b/lib/toolchain-utils.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -42,11 +42,11 @@ export function getToolchainPathWithOptionsArr(compilerExe: string | null, optio const gxxname = options.find(elem => elem.includes(icc_style_toolchain_flag)); if (gxxname) { return path.resolve(path.dirname(gxxname.substring(11)), '..'); - } else if (typeof compilerExe === 'string' && (compilerExe.includes('/g++') || compilerExe.endsWith('-g++'))) { - return path.resolve(path.dirname(compilerExe), '..'); - } else { - return false; } + if (typeof compilerExe === 'string' && (compilerExe.includes('/g++') || compilerExe.endsWith('-g++'))) { + return path.resolve(path.dirname(compilerExe), '..'); + } + return false; } export function getToolchainPath(compilerExe: string | null, compilerOptions?: string): string | false { @@ -68,7 +68,8 @@ export function replaceToolchainArg(compilerOptions: string[], newPath: string): return compilerOptions.map(elem => { if (elem.includes(clang_style_toolchain_flag)) { return clang_style_toolchain_flag + path.normalize(newPath); - } else if (elem.includes(icc_style_toolchain_flag)) { + } + if (elem.includes(icc_style_toolchain_flag)) { return icc_style_toolchain_flag + path.normalize(newPath); } diff --git a/lib/tooling/base-tool.ts b/lib/tooling/base-tool.ts index e236e57e5..f747b280e 100755 --- a/lib/tooling/base-tool.ts +++ b/lib/tooling/base-tool.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import PromClient from 'prom-client'; import _ from 'underscore'; @@ -62,8 +62,8 @@ export class BaseTool implements ITool { getUniqueFilePrefix() { const timestamp = process.hrtime(); - const timestamp_str = '_' + timestamp[0] * 1000000 + timestamp[1] / 1000; - return this.tool.id.replaceAll(/[^\da-z]/gi, '_') + timestamp_str + '_'; + const timestamp_str = `_${timestamp[0] * 1000000}${timestamp[1] / 1000}`; + return `${this.tool.id.replaceAll(/[^\da-z]/gi, '_') + timestamp_str}_`; } isCompilerExcluded(compilerId: string, compilerProps: ToolEnv['compilerProps']): boolean { diff --git a/lib/tooling/bloaty-tool.ts b/lib/tooling/bloaty-tool.ts index 13d2c4a69..f325f43ca 100644 --- a/lib/tooling/bloaty-tool.ts +++ b/lib/tooling/bloaty-tool.ts @@ -39,8 +39,7 @@ export class BloatyTool extends BaseTool { if (await fileExists(compilationInfo.executableFilename)) { return super.runTool(compilationInfo, compilationInfo.executableFilename, args); - } else { - return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } + return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } } diff --git a/lib/tooling/clang-format-tool.ts b/lib/tooling/clang-format-tool.ts index 6662c0765..db4bfc7e5 100644 --- a/lib/tooling/clang-format-tool.ts +++ b/lib/tooling/clang-format-tool.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; diff --git a/lib/tooling/clang-query-tool.ts b/lib/tooling/clang-query-tool.ts index 772adb2b9..8ad68c441 100644 --- a/lib/tooling/clang-query-tool.ts +++ b/lib/tooling/clang-query-tool.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -54,7 +54,7 @@ export class ClangQueryTool extends BaseTool { compileFlags.concat(this.tool.options); } - const query_commands_file = this.getUniqueFilePrefix() + 'query_commands.txt'; + const query_commands_file = `${this.getUniqueFilePrefix()}query_commands.txt`; await fs.writeFile(path.join(dir, 'compile_flags.txt'), compileFlags.join('\n')); await fs.writeFile(path.join(dir, query_commands_file), stdin); diff --git a/lib/tooling/clang-tidy-tool.ts b/lib/tooling/clang-tidy-tool.ts index 5d674d63c..dd44dbda0 100644 --- a/lib/tooling/clang-tidy-tool.ts +++ b/lib/tooling/clang-tidy-tool.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; diff --git a/lib/tooling/compiler-dropin-tool.ts b/lib/tooling/compiler-dropin-tool.ts index 0acff3118..37206f7db 100644 --- a/lib/tooling/compiler-dropin-tool.ts +++ b/lib/tooling/compiler-dropin-tool.ts @@ -70,8 +70,8 @@ export class CompilerDropinTool extends BaseTool { if (toolchainPath) { // note: needs toolchain argument twice as the first time its sometimes ignored - compileFlags = compileFlags.concat(['--gcc-toolchain=' + toolchainPath]); - compileFlags = compileFlags.concat(['--gcc-toolchain=' + toolchainPath]); + compileFlags = compileFlags.concat([`--gcc-toolchain=${toolchainPath}`]); + compileFlags = compileFlags.concat([`--gcc-toolchain=${toolchainPath}`]); compilerOptions = compilerOptions.filter(option => { return !(option.indexOf('--gcc-toolchain=') === 0 || option.indexOf('--gxx-name=') === 0); diff --git a/lib/tooling/llvm-cov-tool.ts b/lib/tooling/llvm-cov-tool.ts index 8cef9e9ec..f9970173a 100644 --- a/lib/tooling/llvm-cov-tool.ts +++ b/lib/tooling/llvm-cov-tool.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {CompilationInfo, ExecutionOptions} from '../../types/compilation/compilation.interfaces.js'; @@ -38,7 +38,7 @@ export class LLVMCovTool extends BaseTool { compilationExecOptions.customCwd = path.dirname(inputFilepath); compilationExecOptions.input = stdin; try { - const generatedExecutableName = this.getUniqueFilePrefix() + '-coverage.a'; + const generatedExecutableName = `${this.getUniqueFilePrefix()}-coverage.a`; let skipNext = false; const options: string[] = []; @@ -87,17 +87,17 @@ export class LLVMCovTool extends BaseTool { const runExecOptions = this.getDefaultExecOptions() as ExecutionOptions; runExecOptions.customCwd = path.dirname(inputFilepath); - await this.exec('./' + generatedExecutableName, [], { + await this.exec(`./${generatedExecutableName}`, [], { ...runExecOptions, input: stdin, }); const profdataPath = path.join(compilerPath, 'llvm-profdata'); - const generatedProfdataName = this.getUniqueFilePrefix() + '.profdata'; + const generatedProfdataName = `${this.getUniqueFilePrefix()}.profdata`; const profdataResult = await this.exec( profdataPath, - ['merge', '-sparse', './default.profraw', '-o', './' + generatedProfdataName], + ['merge', '-sparse', './default.profraw', '-o', `./${generatedProfdataName}`], runExecOptions, ); if (profdataResult.code !== 0) { @@ -110,8 +110,8 @@ export class LLVMCovTool extends BaseTool { path.join(compilerPath, 'llvm-cov'), [ 'show', - './' + generatedExecutableName, - '-instr-profile=./' + generatedProfdataName, + `./${generatedExecutableName}`, + `-instr-profile=./${generatedProfdataName}`, '-format', 'text', '-use-color', @@ -122,9 +122,8 @@ export class LLVMCovTool extends BaseTool { ); if (covResult.code === 0) { return this.convertResult(covResult, inputFilepath, path.dirname(this.tool.exe)); - } else { - return this.createErrorResponse(`\n${covResult.stdout}\n${covResult.stderr}`); } + return this.createErrorResponse(`\n${covResult.stdout}\n${covResult.stderr}`); } catch (e) { return this.createErrorResponse(``); } diff --git a/lib/tooling/llvm-dwarfdump-tool.ts b/lib/tooling/llvm-dwarfdump-tool.ts index 92074392c..51c6d3f0f 100644 --- a/lib/tooling/llvm-dwarfdump-tool.ts +++ b/lib/tooling/llvm-dwarfdump-tool.ts @@ -41,8 +41,7 @@ export class LLVMDWARFDumpTool extends BaseTool { if (await fileExists(compilationInfo.executableFilename)) { return super.runTool(compilationInfo, compilationInfo.executableFilename, args); - } else { - return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } + return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } } diff --git a/lib/tooling/llvm-mca-tool.ts b/lib/tooling/llvm-mca-tool.ts index 364d21319..5058c8b54 100644 --- a/lib/tooling/llvm-mca-tool.ts +++ b/lib/tooling/llvm-mca-tool.ts @@ -63,7 +63,7 @@ export class LLVMMcaTool extends BaseTool { if (arg === '-target') argIsTarget = true; } - if (target) prependArgs.push('-mtriple=' + target); + if (target) prependArgs.push(`-mtriple=${target}`); let haveCPU = false; let haveM32 = false; @@ -100,7 +100,7 @@ export class LLVMMcaTool extends BaseTool { // ones above). const newArgs: string[] = prependArgs.concat(args || []); - const rewrittenOutputFilename = compilationInfo.outputFilename + '.mca'; + const rewrittenOutputFilename = `${compilationInfo.outputFilename}.mca`; await this.writeAsmFile(compilationInfo.asm as string, rewrittenOutputFilename); return super.runTool(compilationInfo, rewrittenOutputFilename, newArgs); } diff --git a/lib/tooling/microsoft-analysis-tool.ts b/lib/tooling/microsoft-analysis-tool.ts index 8be7a9041..3be0941b5 100644 --- a/lib/tooling/microsoft-analysis-tool.ts +++ b/lib/tooling/microsoft-analysis-tool.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {ToolInfo} from '../../types/tool.interfaces.js'; import {unwrap} from '../assert.js'; @@ -58,10 +58,10 @@ export class MicrosoftAnalysisTool extends BaseTool { execOptions.env = Object.assign({}, execOptions.env); if (compilationInfo.compiler.includePath) { - execOptions.env['INCLUDE'] = compilationInfo.compiler.includePath; + execOptions.env.INCLUDE = compilationInfo.compiler.includePath; } if (compilationInfo.compiler.libPath) { - execOptions.env['LIB'] = compilationInfo.compiler.libPath.join(';'); + execOptions.env.LIB = compilationInfo.compiler.libPath.join(';'); } for (const [env, to] of compilationInfo.compiler.envVars) { execOptions.env[env] = to; diff --git a/lib/tooling/nm-tool.ts b/lib/tooling/nm-tool.ts index 51653545e..a1296f9bd 100644 --- a/lib/tooling/nm-tool.ts +++ b/lib/tooling/nm-tool.ts @@ -39,8 +39,7 @@ export class NmTool extends BaseTool { if (await fileExists(compilationInfo.executableFilename)) { return super.runTool(compilationInfo, compilationInfo.executableFilename, args); - } else { - return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } + return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } } diff --git a/lib/tooling/osaca-tool.ts b/lib/tooling/osaca-tool.ts index 97938d7f3..a9323205e 100644 --- a/lib/tooling/osaca-tool.ts +++ b/lib/tooling/osaca-tool.ts @@ -38,9 +38,7 @@ export class OSACATool extends BaseTool { async writeAsmFile(asmParser: IAsmParser, asm: string, filters: ParseFiltersAndOutputOptions, destination: string) { // Applying same filters as applied to compiler outpu - const filteredAsm = asmParser.process(asm, filters).asm.reduce(function (acc, line) { - return acc + line.text + '\n'; - }, ''); + const filteredAsm = asmParser.process(asm, filters).asm.reduce((acc, line) => `${acc + line.text}\n`, ''); return fs.writeFile(destination, filteredAsm); } @@ -53,7 +51,7 @@ export class OSACATool extends BaseTool { return this.createErrorResponse(''); } - const rewrittenOutputFilename = compilationInfo.outputFilename + '.osaca'; + const rewrittenOutputFilename = `${compilationInfo.outputFilename}.osaca`; await this.writeAsmFile( compilationInfo.asmParser, compilationInfo.asm as string, diff --git a/lib/tooling/pvs-studio-tool.ts b/lib/tooling/pvs-studio-tool.ts index d28107143..2dfdec52e 100644 --- a/lib/tooling/pvs-studio-tool.ts +++ b/lib/tooling/pvs-studio-tool.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import fs from 'fs-extra'; @@ -71,9 +71,7 @@ export class PvsStudioTool extends BaseTool { const manualCompileFlags = compilationInfo.options.filter((option: string) => option !== inputFilepath); compileFlags = compileFlags.concat(manualCompileFlags); - compileFlags = compileFlags.filter(function (flag) { - return flag !== ''; - }); + compileFlags = compileFlags.filter(flag => flag !== ''); // Deal with args args = []; @@ -90,7 +88,7 @@ export class PvsStudioTool extends BaseTool { '-e', '/usr', '--pvs-studio-path', - path.dirname(this.tool.exe) + '/pvs-studio', + `${path.dirname(this.tool.exe)}/pvs-studio`, // TODO: expand this to switch() for all supported compilers: // visualcpp, clang, gcc, bcc, bcc_clang64, iar, keil5, keil5_gnu '--preprocessor', @@ -144,7 +142,7 @@ export class PvsStudioTool extends BaseTool { // so let's just replace it with a source file name. const plogConverterOutput = plogRawOutput .toString() - .replace(sourceDir + '/example.PVS-Studio.i', inputFilepath); + .replace(`${sourceDir}/example.PVS-Studio.i`, inputFilepath); result.stdout = utils.parseOutput(plogConverterOutput, plogConverterResult.filenameTransform(inputFilepath)); @@ -165,7 +163,7 @@ export class PvsStudioTool extends BaseTool { const execOptions = super.getDefaultExecOptions(); execOptions.env = { ...execOptions.env, - PATH: process.env.PATH + ':/opt/compiler-explorer/pvs-studio-latest/bin', + PATH: `${process.env.PATH}:/opt/compiler-explorer/pvs-studio-latest/bin`, }; return execOptions; diff --git a/lib/tooling/readelf-tool.ts b/lib/tooling/readelf-tool.ts index 8d4c8b1f6..a9c1fe95b 100644 --- a/lib/tooling/readelf-tool.ts +++ b/lib/tooling/readelf-tool.ts @@ -39,8 +39,7 @@ export class ReadElfTool extends BaseTool { if (await fileExists(compilationInfo.executableFilename)) { return super.runTool(compilationInfo, compilationInfo.executableFilename, args); - } else { - return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } + return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } } diff --git a/lib/tooling/sonar-tool.ts b/lib/tooling/sonar-tool.ts index 94bca8091..a97395b6c 100644 --- a/lib/tooling/sonar-tool.ts +++ b/lib/tooling/sonar-tool.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import path from 'path'; +import path from 'node:path'; import {CompilationInfo, ExecutionOptions} from '../../types/compilation/compilation.interfaces.js'; import type { @@ -95,7 +95,7 @@ export class SonarTool extends BaseTool { flow, }; output.push({ - text: `${(tag.line + ':' + tag.column).padEnd(6)} ${flow.length > 0 ? '\u2795 ' : ''}${text}`, + text: `${(`${tag.line}:${tag.column}`).padEnd(6)} ${flow.length > 0 ? '\u2795 ' : ''}${text}`, tag: cetag, }); if (fixes.length > 0) { @@ -106,7 +106,7 @@ export class SonarTool extends BaseTool { ...flow .filter(f => f.text) .map((f, i) => ({ - text: `\t\u21B3 ${flow.length > 1 ? ' ' + (i + 1) : ''} ${f.text}`, + text: `\t\u21B3 ${flow.length > 1 ? ` ${i + 1}` : ''} ${f.text}`, })), ); } @@ -130,9 +130,7 @@ export class SonarTool extends BaseTool { try { const results = JSON.parse(this.simplifyPathes(lines, inputFilepath, pathPrefix)); if (results.header) { - output.push( - ...utils.splitLines('\u001B[3m\u001B[32m' + results.header + '\u001B[0m').map(s => ({text: s})), - ); + output.push(...utils.splitLines(`\u001B[3m\u001B[32m${results.header}\u001B[0m`).map(s => ({text: s}))); } if (results.parsingErrors && results.parsingErrors.length > 0) { output.push( diff --git a/lib/tooling/strings-tool.ts b/lib/tooling/strings-tool.ts index 4e351380a..0e1b032ff 100644 --- a/lib/tooling/strings-tool.ts +++ b/lib/tooling/strings-tool.ts @@ -38,8 +38,7 @@ export class StringsTool extends BaseTool { } if (await fileExists(compilationInfo.executableFilename)) { return super.runTool(compilationInfo, compilationInfo.executableFilename, args); - } else { - return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } + return super.runTool(compilationInfo, compilationInfo.outputFilename, args); } } diff --git a/lib/tooling/x86to6502-tool.ts b/lib/tooling/x86to6502-tool.ts index 98e3f7576..30fda9cfc 100644 --- a/lib/tooling/x86to6502-tool.ts +++ b/lib/tooling/x86to6502-tool.ts @@ -56,11 +56,11 @@ export class x86to6502Tool extends BaseTool { .map(obj => { if (typeof obj.text !== 'string' || obj.text.trim() === '') { return ''; - } else if (/.*:/.test(obj.text)) { - return obj.text.replace(/^\s*/, ''); - } else { - return obj.text.replace(/^\s*/, '\t'); } + if (/.*:/.test(obj.text)) { + return obj.text.replace(/^\s*/, ''); + } + return obj.text.replace(/^\s*/, '\t'); }) .join('\n'); diff --git a/lib/utils.ts b/lib/utils.ts index f97c19fe3..6a950eb84 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -23,10 +23,10 @@ // POSSIBILITY OF SUCH DAMAGE. import {Buffer} from 'buffer'; -import crypto from 'crypto'; -import os from 'os'; -import path from 'path'; -import {fileURLToPath} from 'url'; +import crypto from 'node:crypto'; +import os from 'node:os'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; import fs from 'fs-extra'; import {ComponentConfig, ItemConfigType} from 'golden-layout'; @@ -51,7 +51,7 @@ export function splitLines(text: string): string[] { return result; } -export function eachLine(text: string, func: (line: string) => ResultLine | void): (ResultLine | void)[] { +export function eachLine(text: string, func: (line: string) => ResultLine | undefined): (ResultLine | undefined)[] { return splitLines(text).map(func); } @@ -67,7 +67,7 @@ export function expandTabs(line: string): string { function getRegexForTempdir(): RegExp { const tmp = os.tmpdir(); - return new RegExp(tmp.replaceAll('/', '\\/') + '\\/' + ce_temp_prefix + '[\\w\\d-.]*\\/'); + return new RegExp(`${tmp.replaceAll('/', '\\/')}\\/${ce_temp_prefix}[\\w\\d-.]*\\/`); } /** @@ -81,13 +81,11 @@ export function maskRootdir(filepath: string): string { return filepath .replace(/^C:\/Users\/[\w\d-.]*\/AppData\/Local\/Temp\/compiler-explorer-compiler[\w\d-.]*\//, '/app/') .replace(/^\/app\//, ''); - } else { - const re = getRegexForTempdir(); - return filepath.replace(re, '/app/').replace(/^\/app\//, ''); } - } else { - return filepath; + const re = getRegexForTempdir(); + return filepath.replace(re, '/app/').replace(/^\/app\//, ''); } + return filepath; } export function changeExtension(filename: string, newExtension: string): string { @@ -105,8 +103,8 @@ function _parseOutputLine(line: string, inputFilename?: string, pathPrefix?: str line = line.split(inputFilename).join(''); if (inputFilename.indexOf('./') === 0) { - line = line.split('/home/ubuntu/' + inputFilename.substring(2)).join(''); - line = line.split('/home/ce/' + inputFilename.substring(2)).join(''); + line = line.split(`/home/ubuntu/${inputFilename.substring(2)}`).join(''); + line = line.split(`/home/ce/${inputFilename.substring(2)}`).join(''); } } return line; @@ -123,11 +121,11 @@ const SOURCE_WITH_FILENAME = /^\s*([\w.]+)[(:](\d+)(:?,?(\d+):?)?[):]*\s*(.*)/; const ATFILELINE_RE = /\s*at ([\w-/.]+):(\d+)/; export enum LineParseOption { - SourceMasking, - RootMasking, - SourceWithLineMessage, - FileWithLineMessage, - AtFileLine, + SourceMasking = 0, + RootMasking = 1, + SourceWithLineMessage = 2, + FileWithLineMessage = 3, + AtFileLine = 4, } export type LineParseOptions = LineParseOption[]; @@ -144,8 +142,8 @@ function applyParse_SourceWithLine(lineObj: ResultLine, filteredLine: string, in if (match) { const message = match[4].trim(); lineObj.tag = { - line: parseInt(match[1]), - column: parseInt(match[3] || '0'), + line: Number.parseInt(match[1]), + column: Number.parseInt(match[3] || '0'), text: message, severity: parseSeverity(message), file: inputFilename ? path.basename(inputFilename) : undefined, @@ -159,8 +157,8 @@ function applyParse_FileWithLine(lineObj: ResultLine, filteredLine: string) { const message = match[5].trim(); lineObj.tag = { file: match[1], - line: parseInt(match[2]), - column: parseInt(match[4] || '0'), + line: Number.parseInt(match[2]), + column: Number.parseInt(match[4] || '0'), text: message, severity: parseSeverity(message), }; @@ -173,7 +171,7 @@ function applyParse_AtFileLine(lineObj: ResultLine, filteredLine: string) { if (match[1].startsWith('/app/')) { lineObj.tag = { file: match[1].replace(/^\/app\//, ''), - line: parseInt(match[2]), + line: Number.parseInt(match[2]), column: 0, text: filteredLine, severity: 3, @@ -181,7 +179,7 @@ function applyParse_AtFileLine(lineObj: ResultLine, filteredLine: string) { } else if (!match[1].startsWith('/')) { lineObj.tag = { file: match[1], - line: parseInt(match[2]), + line: Number.parseInt(match[2]), column: 0, text: filteredLine, severity: 3, @@ -233,8 +231,8 @@ export function parseRustOutput(lines: string, inputFilename?: string, pathPrefi const match = line.replaceAll(ansiColoursRe, '').match(re); if (match) { - const line = parseInt(match[1]); - const column = parseInt(match[3] || '0'); + const line = Number.parseInt(match[1]); + const column = Number.parseInt(match[3] || '0'); const previous = result.pop(); if (previous !== undefined) { @@ -272,13 +270,13 @@ export function parseRustOutput(lines: string, inputFilename?: string, pathPrefi export function anonymizeIp(ip: string): string { if (ip.includes('localhost')) { return ip; - } else if (ip.includes(':')) { + } + if (ip.includes(':')) { // IPv6 return ip.replace(/(?::[\dA-Fa-f]{0,4}){3}$/, ':0:0:0'); - } else { - // IPv4 - return ip.replace(/\.\d{1,3}$/, '.0'); } + // IPv4 + return ip.replace(/\.\d{1,3}$/, '.0'); } /*** @@ -379,8 +377,8 @@ export function squashHorizontalWhitespace(line: string, atStart = true): string export function toProperty(prop: string): boolean | number | string { if (prop === 'true' || prop === 'yes') return true; if (prop === 'false' || prop === 'no') return false; - if (/^-?(0|[1-9]\d*)$/.test(prop)) return parseInt(prop); - if (/^-?\d*\.\d+$/.test(prop)) return parseFloat(prop); + if (/^-?(0|[1-9]\d*)$/.test(prop)) return Number.parseInt(prop); + if (/^-?\d*\.\d+$/.test(prop)) return Number.parseFloat(prop); return prop; } @@ -432,9 +430,8 @@ export function base32Encode(buffer: Buffer): string { export function splitIntoArray(input?: string, defaultArray: string[] = []): string[] { if (input === undefined) { return defaultArray; - } else { - return input.split(':'); } + return input.split(':'); } export function splitArguments(options = ''): string[] { diff --git a/package.json b/package.json index e2090d152..c4ca98348 100644 --- a/package.json +++ b/package.json @@ -89,7 +89,7 @@ "yaml": "^2.6.0" }, "devDependencies": { - "@biomejs/biome": "^1.9.4", + "@biomejs/biome": "^1.9.4", "@sentry/types": "^8.36.0", "@smithy/util-stream": "^3.2.1", "@types/body-parser": "^1.19.5", diff --git a/shared/common-utils.ts b/shared/common-utils.ts index f4654575a..b2829fb91 100644 --- a/shared/common-utils.ts +++ b/shared/common-utils.ts @@ -54,11 +54,11 @@ export function remove(arr: U[], v: V) { export function basic_comparator(a: T, b: T) { if (a < b) { return -1; - } else if (a > b) { - return 1; - } else { - return 0; } + if (a > b) { + return 1; + } + return 0; } // https://stackoverflow.com/questions/41253310/typescript-retrieve-element-type-information-from-array-type @@ -91,7 +91,7 @@ function splitIntoChunks(s: string, chunkSize: number): string[] { chunks.push(s.slice(i, i + chunkSize)); } if (isNegative) { - chunks[0] = '-' + (chunks[0] ?? ''); + chunks[0] = `-${chunks[0] ?? ''}`; } return chunks; } diff --git a/shared/stacktrace.ts b/shared/stacktrace.ts index df51a49f5..a12842f18 100644 --- a/shared/stacktrace.ts +++ b/shared/stacktrace.ts @@ -35,8 +35,8 @@ type StackFrame = { }; enum TraceFormat { - V8, - Firefox, + V8 = 0, + Firefox = 1, } export function parse(err: Error) { @@ -112,64 +112,63 @@ export function parse(err: Error) { return { fileName: lineMatch[2] || undefined, - lineNumber: parseInt(lineMatch[3], 10) || undefined, + lineNumber: Number.parseInt(lineMatch[3], 10) || undefined, functionName: functionName, typeName: typeName, methodName: methodName, - columnNumber: parseInt(lineMatch[4], 10) || undefined, + columnNumber: Number.parseInt(lineMatch[4], 10) || undefined, native: isNative, }; }) .filter(frame => frame !== undefined) as StackFrame[]; - } else { - return err.stack - .split('\n') - .map((line): StackFrame | undefined => { - const lineMatch = line.match(/(.*)@(.*):(\d+):(\d+)/); - if (!lineMatch) { - return; - } + } + return err.stack + .split('\n') + .map((line): StackFrame | undefined => { + const lineMatch = line.match(/(.*)@(.*):(\d+):(\d+)/); + if (!lineMatch) { + return; + } - let object: string | undefined; - let method: string | undefined; - let functionName: string | undefined; - let typeName: string | undefined; - let methodName: string | undefined; + let object: string | undefined; + let method: string | undefined; + let functionName: string | undefined; + let typeName: string | undefined; + let methodName: string | undefined; - if (lineMatch[1]) { - functionName = lineMatch[1]; - let methodStart = functionName.lastIndexOf('.'); - if (functionName[methodStart - 1] === '.') methodStart--; - if (methodStart > 0) { - object = functionName.substring(0, methodStart); - method = functionName.substring(methodStart + 1); - const objectEnd = object.indexOf('.Module'); - if (objectEnd > 0) { - functionName = functionName.substring(objectEnd + 1); - object = object.substring(0, objectEnd); - } + if (lineMatch[1]) { + functionName = lineMatch[1]; + let methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart - 1] === '.') methodStart--; + if (methodStart > 0) { + object = functionName.substring(0, methodStart); + method = functionName.substring(methodStart + 1); + const objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.substring(objectEnd + 1); + object = object.substring(0, objectEnd); } } + } - if (method) { - typeName = object; - methodName = method; - } + if (method) { + typeName = object; + methodName = method; + } - if (method === '') { - methodName = undefined; - functionName = undefined; - } + if (method === '') { + methodName = undefined; + functionName = undefined; + } - return { - fileName: lineMatch[2] || undefined, - lineNumber: parseInt(lineMatch[3], 10) || undefined, - functionName: functionName, - typeName: typeName, - methodName: methodName, - columnNumber: parseInt(lineMatch[4], 10) || undefined, - }; - }) - .filter(frame => frame !== undefined) as StackFrame[]; - } + return { + fileName: lineMatch[2] || undefined, + lineNumber: Number.parseInt(lineMatch[3], 10) || undefined, + functionName: functionName, + typeName: typeName, + methodName: methodName, + columnNumber: Number.parseInt(lineMatch[4], 10) || undefined, + }; + }) + .filter(frame => frame !== undefined) as StackFrame[]; } diff --git a/static/ansi-to-html.ts b/static/ansi-to-html.ts index dfad84cbc..2e9aa3420 100644 --- a/static/ansi-to-html.ts +++ b/static/ansi-to-html.ts @@ -28,9 +28,9 @@ // Converted to typescript by MarkusJx import _ from 'underscore'; +import {isString} from '../shared/common-utils.js'; import {AnsiToHtmlOptions, ColorCodes} from './ansi-to-html.interfaces.js'; import {assert, unwrap} from './assert.js'; -import {isString} from '../shared/common-utils.js'; const defaults: AnsiToHtmlOptions = { fg: '#FFF', @@ -98,7 +98,7 @@ function toHexString(num: number): string { let str = num.toString(16); while (str.length < 2) { - str = '0' + str; + str = `0${str}`; } return str; @@ -117,19 +117,22 @@ function toColorHexString(ref: number[]): string { results.push(toHexString(ref[j])); } - return '#' + results.join(''); + return `#${results.join('')}`; } function generateOutput(stack: string[], token: string, data: string | number, options: AnsiToHtmlOptions): string { if (token === 'text') { assert(isString(data), "Param 'data' must be a string at this point"); return pushText(data, options); - } else if (token === 'display') { + } + if (token === 'display') { return handleDisplay(stack, data, options); - } else if (token === 'xterm256') { + } + if (token === 'xterm256') { assert(isString(data), "Param 'data' must be a string at this point"); return handleXterm256(stack, data, options); - } else if (token === 'rgb') { + } + if (token === 'rgb') { assert(isString(data), "Param 'data' must be a string at this point"); return handleRgb(stack, data, options); } @@ -143,7 +146,7 @@ function handleRgb(stack: string[], data: string, options: AnsiToHtmlOptions) { const color = data.substring(5).split(';'); const rgb = color .map(value => { - return ('0' + Number(value).toString(16)).slice(-2); + return `0${Number(value).toString(16)}`.slice(-2); }) .join(''); @@ -156,13 +159,12 @@ function handleXterm256(stack: string[], data: string, options: AnsiToHtmlOption const color = +data.substring(5); if (operation === 38) { return pushForegroundColor(stack, options.colors[color]); - } else { - return pushBackgroundColor(stack, options.colors[color]); } + return pushBackgroundColor(stack, options.colors[color]); } function handleDisplay(stack: string[], code: string | number, options: AnsiToHtmlOptions): string { - code = isString(code) ? parseInt(code, 10) : code; + code = isString(code) ? Number.parseInt(code, 10) : code; const codeMap: Record string> = { '-1': () => '
', 0: () => (stack.length ? resetStyles(stack) : ''), @@ -181,17 +183,23 @@ function handleDisplay(stack: string[], code: string | number, options: AnsiToHt if (code in codeMap) { return codeMap[code](); - } else if (4 < code && code < 7) { + } + if (4 < code && code < 7) { return pushTag(stack, 'blink'); - } else if (code === 7) { + } + if (code === 7) { return ''; - } else if (29 < code && code < 38) { + } + if (29 < code && code < 38) { return pushForegroundColor(stack, options.colors[code - 30]); - } else if (39 < code && code < 48) { + } + if (39 < code && code < 48) { return pushBackgroundColor(stack, options.colors[code - 40]); - } else if (89 < code && code < 98) { + } + if (89 < code && code < 98) { return pushForegroundColor(stack, options.colors[8 + (code - 90)]); - } else if (99 < code && code < 108) { + } + if (99 < code && code < 108) { return pushBackgroundColor(stack, options.colors[8 + (code - 100)]); } return 'Unknown code'; @@ -244,22 +252,29 @@ function notCategory(category: string): (e: StickyStackElement) => boolean { * @returns the ansi token type */ function categoryForCode(code: string | number): string { - code = isString(code) ? parseInt(code, 10) : code; + code = isString(code) ? Number.parseInt(code, 10) : code; if (code === 0) { return 'all'; - } else if (code === 1) { + } + if (code === 1) { return 'bold'; - } else if (2 < code && code < 5) { + } + if (2 < code && code < 5) { return 'underline'; - } else if (4 < code && code < 7) { + } + if (4 < code && code < 7) { return 'blink'; - } else if (code === 8) { + } + if (code === 8) { return 'hide'; - } else if (code === 9) { + } + if (code === 9) { return 'strike'; - } else if ((29 < code && code < 38) || code === 39 || (89 < code && code < 98)) { + } + if ((29 < code && code < 38) || code === 39 || (89 < code && code < 98)) { return 'foreground-color'; - } else if ((39 < code && code < 48) || code === 49 || (99 < code && code < 108)) { + } + if ((39 < code && code < 48) || code === 49 || (99 < code && code < 108)) { return 'background-color'; } return ''; @@ -280,7 +295,7 @@ function pushTag(stack: string[], tag: string, style?: string): string { stack.push(tag); - return ['<' + tag, style ? ' style="' + style + '"' : void 0, '>'].join(''); + return [`<${tag}`, style ? ` style="${style}"` : void 0, '>'].join(''); } function pushStyle(stack: string[], style: string): string { @@ -288,11 +303,11 @@ function pushStyle(stack: string[], style: string): string { } function pushForegroundColor(stack: string[], color: string): string { - return pushTag(stack, 'span', 'color:' + color); + return pushTag(stack, 'span', `color:${color}`); } function pushBackgroundColor(stack: string[], color: string): string { - return pushTag(stack, 'span', 'background-color:' + color); + return pushTag(stack, 'span', `background-color:${color}`); } function closeTag(stack: string[], style: string): string { @@ -303,7 +318,7 @@ function closeTag(stack: string[], style: string): string { } if (last) { - return ''; + return ``; } return ''; } @@ -429,9 +444,8 @@ function tokenize(text: string, options: AnsiToHtmlOptions, callback: TokenizeCa if (text.length === length) { break; - } else { - results1.push(0); } + results1.push(0); length = text.length; } diff --git a/static/api/api.ts b/static/api/api.ts index 1206b6a31..e676d0958 100644 --- a/static/api/api.ts +++ b/static/api/api.ts @@ -25,8 +25,8 @@ import _ from 'underscore'; import { - AssemblyDocumentationResponse, AssemblyDocumentationRequest, + AssemblyDocumentationResponse, } from '../../types/features/assembly-documentation.interfaces.js'; import {FormattingRequest, FormattingResponse} from './formatting.interfaces.js'; diff --git a/static/assert.ts b/static/assert.ts index d41465213..ed43f82d1 100644 --- a/static/assert.ts +++ b/static/assert.ts @@ -55,16 +55,15 @@ function fail(fail_message: string, user_message: string | undefined, args: any[ } if (args.length > 0) { try { - assert_line += ', ' + JSON.stringify(args); + assert_line += `, ${JSON.stringify(args)}`; } catch (e) {} } const diagnostic = get_diagnostic(); if (diagnostic) { - throw new Error(assert_line + `, at ${diagnostic.file}:${diagnostic.line}`); - } else { - throw new Error(assert_line); + throw new Error(`${assert_line}, at ${diagnostic.file}:${diagnostic.line}`); } + throw new Error(assert_line); } export function assert(c: unknown, message?: string, ...extra_info: any[]): asserts c { diff --git a/static/codelens-handler.ts b/static/codelens-handler.ts index bde64c5a0..8edf814cb 100644 --- a/static/codelens-handler.ts +++ b/static/codelens-handler.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import _ from 'underscore'; import * as monaco from 'monaco-editor'; +import _ from 'underscore'; interface RegisteredCodeLens { compilerId: number; @@ -62,14 +62,13 @@ function provide(model: monaco.editor.ITextModel): monaco.languages.CodeLensList if (item) { return { lenses: item.lenses, - dispose: function () {}, - }; - } else { - return { - lenses: [], - dispose: function () {}, + dispose: () => {}, }; } + return { + lenses: [], + dispose: () => {}, + }; } export function unregister(compilerId: number): void { diff --git a/static/colour.ts b/static/colour.ts index 6f9abd7e6..592a2b0ea 100644 --- a/static/colour.ts +++ b/static/colour.ts @@ -93,12 +93,12 @@ export function applyColours( ): void { const scheme = schemes.find(scheme => scheme.name === schemeName) ?? schemes[0]; const newDecorations: monaco.editor.IModelDeltaDecoration[] = Object.entries(colours).map(([line, index]) => { - const realLineNumber = parseInt(line) + 1; + const realLineNumber = Number.parseInt(line) + 1; return { range: new monaco.Range(realLineNumber, 1, realLineNumber, 1), options: { isWholeLine: true, - className: 'line-linkage ' + scheme.name + '-' + (index % scheme.count), + className: `line-linkage ${scheme.name}-${index % scheme.count}`, }, }; }); diff --git a/static/compiler-service.ts b/static/compiler-service.ts index 8afb470e8..204e2cb62 100644 --- a/static/compiler-service.ts +++ b/static/compiler-service.ts @@ -22,10 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import $ from 'jquery'; -import _ from 'underscore'; -import {LRUCache} from 'lru-cache'; import {EventEmitter} from 'golden-layout'; +import $ from 'jquery'; +import {LRUCache} from 'lru-cache'; +import _ from 'underscore'; import {options} from './options.js'; @@ -33,8 +33,8 @@ import {ResultLine} from '../types/resultline/resultline.interfaces.js'; import jqXHR = JQuery.jqXHR; import ErrorTextStatus = JQuery.Ajax.ErrorTextStatus; -import {CompilerInfo} from '../types/compiler.interfaces.js'; import {CompilationResult, FiledataPair} from '../types/compilation/compilation.interfaces.js'; +import {CompilerInfo} from '../types/compiler.interfaces.js'; import {CompilationStatus} from './compiler-service.interfaces.js'; import {IncludeDownloads, SourceAndFiles} from './download-service.js'; import {SentryCapture} from './sentry.js'; @@ -90,20 +90,19 @@ export class CompilerService { compiler: compilers[0], langId: langId, }; - } else { - return { - // There were no compilers, so return null, the selection will show up empty - compiler: null, - langId: langId, - }; } - } else { return { - compiler: foundCompiler, + // There were no compilers, so return null, the selection will show up empty + compiler: null, langId: langId, }; } - } else if (compilerId) { + return { + compiler: foundCompiler, + langId: langId, + }; + } + if (compilerId) { const matchingCompilers = Object.values(options.languages).map(lang => { const compiler = this.findCompiler(lang.id, compilerId); if (compiler) { @@ -116,16 +115,14 @@ export class CompilerService { }); // Ensure that if no compiler is present, we return null instead of undefined return matchingCompilers.find(compiler => compiler !== null) ?? null; - } else { - const languages = Object.values(options.languages); - if (languages.length > 0) { - const firstLang = languages[0]; - return this.processFromLangAndCompiler(firstLang.id, compilerId); - } else { - // TODO: What now? No languages loaded - return null; - } } + const languages = Object.values(options.languages); + if (languages.length > 0) { + const firstLang = languages[0]; + return this.processFromLangAndCompiler(firstLang.id, compilerId); + } + // TODO: What now? No languages loaded + return null; } catch (e) { SentryCapture(e, 'processFromLangAndCompiler'); } @@ -195,7 +192,7 @@ export class CompilerService { error = 'Request failed: gateway timeout'; break; default: - error = 'Request failed: HTTP error code ' + xhr.status; + error = `Request failed: HTTP error code ${xhr.status}`; break; } break; @@ -236,7 +233,7 @@ export class CompilerService { contentType: 'application/json', data: jsonRequest, success: result => { - if (result && result.okToCache && options.doCache) { + if (result?.okToCache && options.doCache) { this.cache.set(jsonRequest, result); } resolve({ @@ -274,7 +271,7 @@ export class CompilerService { contentType: 'application/json', data: jsonRequest, success: result => { - if (result && result.okToCache && options.doCache) { + if (result?.okToCache && options.doCache) { this.cache.set(jsonRequest, result); } resolve({ @@ -363,7 +360,7 @@ export class CompilerService { let code = 1; if (result.code !== 0) { code = 3; - } else if (this.doesCompilationResultHaveWarnings(result)) { + } else if (CompilerService.doesCompilationResultHaveWarnings(result)) { code = 2; } return {code: code, compilerOut: result.code}; @@ -378,13 +375,12 @@ export class CompilerService { // StdOut.length > 0 if (status.code === 2) return 'Compilation succeeded with warnings'; return 'Compilation succeeded'; - } else { - // StdErr.length > 0 - if (status.code === 3) return 'Compilation failed with errors'; - // StdOut.length > 0 - if (status.code === 2) return 'Compilation failed with warnings'; - return 'Compilation failed'; } + // StdErr.length > 0 + if (status.code === 3) return 'Compilation failed with errors'; + // StdOut.length > 0 + if (status.code === 2) return 'Compilation failed with warnings'; + return 'Compilation failed'; } private static getColor(status: CompilationStatus) { @@ -396,13 +392,12 @@ export class CompilerService { // StdOut.length > 0 if (status.code === 2) return '#FF6500'; return '#12BB12'; - } else { - // StdErr.length > 0 - if (status.code === 3) return '#FF1212'; - // StdOut.length > 0 - if (status.code === 2) return '#BB8700'; - return '#FF6645'; } + // StdErr.length > 0 + if (status.code === 3) return '#FF1212'; + // StdOut.length > 0 + if (status.code === 2) return '#BB8700'; + return '#FF6645'; } public static handleCompilationStatus( @@ -418,9 +413,9 @@ export class CompilerService { statusIcon .removeClass() .addClass('status-icon fas') - .css('color', this.getColor(status)) + .css('color', CompilerService.getColor(status)) .toggle(status.code !== 0) - .attr('aria-label', this.getAriaLabel(status)) + .attr('aria-label', CompilerService.getAriaLabel(status)) .toggleClass('fa-spinner fa-spin', status.code === 4) .toggleClass('fa-times-circle', status.code === 3) .toggleClass('fa-check-circle', status.code === 1 || status.code === 2); diff --git a/static/compiler-shared.ts b/static/compiler-shared.ts index 5dc660f03..b440c4c94 100644 --- a/static/compiler-shared.ts +++ b/static/compiler-shared.ts @@ -22,13 +22,13 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import type {ICompilerShared} from './compiler-shared.interfaces.js'; -import {CompilerOverridesWidget} from './widgets/compiler-overrides.js'; -import type {CompilerState} from './panes/compiler.interfaces.js'; import type {ConfiguredOverrides} from './compilation/compiler-overrides.interfaces.js'; -import type {ExecutorState} from './panes/executor.interfaces.js'; -import {RuntimeToolsWidget} from './widgets/runtime-tools.js'; +import type {ICompilerShared} from './compiler-shared.interfaces.js'; import {ConfiguredRuntimeTools} from './execution/execution.interfaces.js'; +import type {CompilerState} from './panes/compiler.interfaces.js'; +import type {ExecutorState} from './panes/executor.interfaces.js'; +import {CompilerOverridesWidget} from './widgets/compiler-overrides.js'; +import {RuntimeToolsWidget} from './widgets/runtime-tools.js'; export class CompilerShared implements ICompilerShared { private domRoot: JQuery; diff --git a/static/components.interfaces.ts b/static/components.interfaces.ts index 4ec3cd41f..5aa9cf04a 100644 --- a/static/components.interfaces.ts +++ b/static/components.interfaces.ts @@ -23,13 +23,13 @@ // POSSIBILITY OF SUCH DAMAGE. import {CompilerOutputOptions} from '../types/features/filters.interfaces.js'; -import {CfgState} from './panes/cfg-view.interfaces.js'; -import {ClangirState} from './panes/clangir-view.interfaces.js'; -import {OptPipelineViewState} from './panes/opt-pipeline.interfaces.js'; -import {GccDumpViewState} from './panes/gccdump-view.interfaces.js'; import {ConfiguredOverrides} from './compilation/compiler-overrides.interfaces.js'; import {ConfiguredRuntimeTools} from './execution/execution.interfaces.js'; +import {CfgState} from './panes/cfg-view.interfaces.js'; +import {ClangirState} from './panes/clangir-view.interfaces.js'; +import {GccDumpViewState} from './panes/gccdump-view.interfaces.js'; import {IrState} from './panes/ir-view.interfaces.js'; +import {OptPipelineViewState} from './panes/opt-pipeline.interfaces.js'; import {MonacoPaneState} from './panes/pane.interfaces.js'; export const COMPILER_COMPONENT_NAME = 'compiler'; export const EXECUTOR_COMPONENT_NAME = 'executor'; diff --git a/static/components.ts b/static/components.ts index ec11f67db..02e508435 100644 --- a/static/components.ts +++ b/static/components.ts @@ -25,92 +25,92 @@ import {ParseFiltersAndOutputOptions} from '../types/features/filters.interfaces.js'; import {GccDumpViewState} from './panes/gccdump-view.interfaces.js'; +import {ConfiguredOverrides} from './compilation/compiler-overrides.interfaces.js'; import { - EmptyCompilerState, - ComponentConfig, - PopulatedCompilerState, - CompilerForTreeState, - EmptyExecutorState, - PopulatedExecutorState, - ExecutorForTreeState, - EmptyEditorState, - PopulatedEditorState, - EmptyTreeState, - OutputState, - ToolViewState, - EmptyToolInputViewState, - PopulatedToolInputViewState, - PopulatedOptViewState, - EmptyOptViewState, - EmptyFlagsViewState, - PopulatedFlagsViewState, - EmptyDiffViewState, - PopulatedDiffViewState, - EmptyPpViewState, - PopulatedPpViewState, - EmptyAstViewState, - PopulatedAstViewState, - EmptyGccDumpViewState, - PopulatedGccDumpViewState, - EmptyCfgViewState, - PopulatedCfgViewState, - PopulatedConformanceViewState, - EmptyIrViewState, - PopulatedIrViewState, - EmptyClangirViewState, - PopulatedClangirViewState, - EmptyRustMirViewState, - PopulatedRustMirViewState, - EmptyHaskellCoreViewState, - PopulatedHaskellCoreViewState, - EmptyHaskellStgViewState, - PopulatedHaskellStgViewState, - EmptyHaskellCmmViewState, - PopulatedHaskellCmmViewState, - EmptyGnatDebugTreeViewState, - PopulatedGnatDebugTreeViewState, - EmptyGnatDebugViewState, - PopulatedGnatDebugViewState, - EmptyRustMacroExpViewState, - PopulatedRustMacroExpViewState, - EmptyRustHirViewState, - PopulatedRustHirViewState, - EmptyDeviceViewState, - PopulatedDeviceViewState, - COMPILER_COMPONENT_NAME, - EXECUTOR_COMPONENT_NAME, - EDITOR_COMPONENT_NAME, - TREE_COMPONENT_NAME, - OUTPUT_COMPONENT_NAME, - TOOL_COMPONENT_NAME, - TOOL_INPUT_VIEW_COMPONENT_NAME, - DIFF_VIEW_COMPONENT_NAME, - OPT_VIEW_COMPONENT_NAME, - STACK_USAGE_VIEW_COMPONENT_NAME, - FLAGS_VIEW_COMPONENT_NAME, - PP_VIEW_COMPONENT_NAME, AST_VIEW_COMPONENT_NAME, - GCC_DUMP_VIEW_COMPONENT_NAME, CFG_VIEW_COMPONENT_NAME, - CONFORMANCE_VIEW_COMPONENT_NAME, - IR_VIEW_COMPONENT_NAME, CLANGIR_VIEW_COMPONENT_NAME, - RUST_MIR_VIEW_COMPONENT_NAME, - HASKELL_CORE_VIEW_COMPONENT_NAME, - HASKELL_STG_VIEW_COMPONENT_NAME, - HASKELL_CMM_VIEW_COMPONENT_NAME, + COMPILER_COMPONENT_NAME, + CONFORMANCE_VIEW_COMPONENT_NAME, + CompilerForTreeState, + ComponentConfig, + DEVICE_VIEW_COMPONENT_NAME, + DIFF_VIEW_COMPONENT_NAME, + EDITOR_COMPONENT_NAME, + EXECUTOR_COMPONENT_NAME, + EmptyAstViewState, + EmptyCfgViewState, + EmptyClangirViewState, + EmptyCompilerState, + EmptyDeviceViewState, + EmptyDiffViewState, + EmptyEditorState, + EmptyExecutorState, + EmptyFlagsViewState, + EmptyGccDumpViewState, + EmptyGnatDebugTreeViewState, + EmptyGnatDebugViewState, + EmptyHaskellCmmViewState, + EmptyHaskellCoreViewState, + EmptyHaskellStgViewState, + EmptyIrViewState, + EmptyOptPipelineViewState, + EmptyOptViewState, + EmptyPpViewState, + EmptyRustHirViewState, + EmptyRustMacroExpViewState, + EmptyRustMirViewState, + EmptyStackUsageViewState, + EmptyToolInputViewState, + EmptyTreeState, + ExecutorForTreeState, + FLAGS_VIEW_COMPONENT_NAME, + GCC_DUMP_VIEW_COMPONENT_NAME, GNAT_DEBUG_TREE_VIEW_COMPONENT_NAME, GNAT_DEBUG_VIEW_COMPONENT_NAME, - RUST_MACRO_EXP_VIEW_COMPONENT_NAME, - RUST_HIR_VIEW_COMPONENT_NAME, - DEVICE_VIEW_COMPONENT_NAME, + HASKELL_CMM_VIEW_COMPONENT_NAME, + HASKELL_CORE_VIEW_COMPONENT_NAME, + HASKELL_STG_VIEW_COMPONENT_NAME, + IR_VIEW_COMPONENT_NAME, OPT_PIPELINE_VIEW_COMPONENT_NAME, - EmptyOptPipelineViewState, + OPT_VIEW_COMPONENT_NAME, + OUTPUT_COMPONENT_NAME, + OutputState, + PP_VIEW_COMPONENT_NAME, + PopulatedAstViewState, + PopulatedCfgViewState, + PopulatedClangirViewState, + PopulatedCompilerState, + PopulatedConformanceViewState, + PopulatedDeviceViewState, + PopulatedDiffViewState, + PopulatedEditorState, + PopulatedExecutorState, + PopulatedFlagsViewState, + PopulatedGccDumpViewState, + PopulatedGnatDebugTreeViewState, + PopulatedGnatDebugViewState, + PopulatedHaskellCmmViewState, + PopulatedHaskellCoreViewState, + PopulatedHaskellStgViewState, + PopulatedIrViewState, PopulatedOptPipelineViewState, + PopulatedOptViewState, + PopulatedPpViewState, + PopulatedRustHirViewState, + PopulatedRustMacroExpViewState, + PopulatedRustMirViewState, PopulatedStackUsageViewState, - EmptyStackUsageViewState, + PopulatedToolInputViewState, + RUST_HIR_VIEW_COMPONENT_NAME, + RUST_MACRO_EXP_VIEW_COMPONENT_NAME, + RUST_MIR_VIEW_COMPONENT_NAME, + STACK_USAGE_VIEW_COMPONENT_NAME, + TOOL_COMPONENT_NAME, + TOOL_INPUT_VIEW_COMPONENT_NAME, + TREE_COMPONENT_NAME, + ToolViewState, } from './components.interfaces.js'; -import {ConfiguredOverrides} from './compilation/compiler-overrides.interfaces.js'; import {ConfiguredRuntimeTools} from './execution/execution.interfaces.js'; import {LanguageKey} from './languages.interfaces.js'; diff --git a/static/event-map.ts b/static/event-map.ts index 0c06bf5ce..c76811294 100644 --- a/static/event-map.ts +++ b/static/event-map.ts @@ -22,19 +22,19 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +import {CompilationResult} from '../types/compilation/compilation.interfaces.js'; +import {CompilerInfo} from '../types/compiler.interfaces.js'; import {Language, LanguageKey} from '../types/languages.interfaces.js'; import {MessageWithLocation} from '../types/resultline/resultline.interfaces.js'; +import {ClangirBackendOptions} from './compilation/clangir.interfaces.js'; +import {LLVMIrBackendOptions} from './compilation/ir.interfaces.js'; +import {OptPipelineBackendOptions} from './compilation/opt-pipeline-output.interfaces.js'; +import {NewToolSettings, ToolState} from './components.interfaces.js'; +import {Motd} from './motd.interfaces.js'; +import {GccDumpFiltersState, GccDumpViewSelectedPass} from './panes/gccdump-view.interfaces.js'; +import {PPOptions} from './panes/pp-view.interfaces.js'; import {SiteSettings} from './settings.js'; import {Theme} from './themes.js'; -import {PPOptions} from './panes/pp-view.interfaces.js'; -import {GccDumpFiltersState, GccDumpViewSelectedPass} from './panes/gccdump-view.interfaces.js'; -import {Motd} from './motd.interfaces.js'; -import {CompilerInfo} from '../types/compiler.interfaces.js'; -import {CompilationResult} from '../types/compilation/compilation.interfaces.js'; -import {OptPipelineBackendOptions} from './compilation/opt-pipeline-output.interfaces.js'; -import {LLVMIrBackendOptions} from './compilation/ir.interfaces.js'; -import {ClangirBackendOptions} from './compilation/clangir.interfaces.js'; -import {NewToolSettings, ToolState} from './components.interfaces.js'; // This list comes from executing // grep -rPo "eventHub\.(on|emit)\('.*'," static/ | cut -d "'" -f2 | sort | uniq diff --git a/static/formatter-registry.ts b/static/formatter-registry.ts index d4cc5cf95..f4b04bc61 100644 --- a/static/formatter-registry.ts +++ b/static/formatter-registry.ts @@ -24,11 +24,11 @@ import * as monaco from 'monaco-editor'; -import {Alert} from './widgets/alert.js'; -import {Settings} from './settings.js'; -import {FormattingRequest} from './api/formatting.interfaces.js'; import {getFormattedCode} from './api/api.js'; +import {FormattingRequest} from './api/formatting.interfaces.js'; import {unwrap} from './assert.js'; +import {Settings} from './settings.js'; +import {Alert} from './widgets/alert.js'; // Proxy function to emit the error to the alert system const onFormatError = (cause: string, source: string) => { diff --git a/static/global.ts b/static/global.ts index ac67a1c5a..a807b1232 100644 --- a/static/global.ts +++ b/static/global.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import {IFrontendTesting} from './tests/frontend-testing.interfaces.js'; import {Options} from './options.interfaces.js'; +import {IFrontendTesting} from './tests/frontend-testing.interfaces.js'; export type CompilerExplorerOptions = Record & Options; @@ -38,7 +38,3 @@ declare global { onSponsorClick: (sponsorUrl: string) => void; } } - -// Necessary because we're not exporting any actual symbols from this file -// See https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html -export {}; diff --git a/static/graph-layout-core.ts b/static/graph-layout-core.ts index 3709a0b74..ad249ba02 100644 --- a/static/graph-layout-core.ts +++ b/static/graph-layout-core.ts @@ -34,19 +34,18 @@ import IntervalTree from '@flatten-js/interval-tree'; function assert(condition: boolean, message?: string, ...args: any[]): asserts condition { if (!condition) { const stack = new Error('Assertion Error').stack; - throw ( + throw `${ (message ? `Assertion error in llvm-print-after-all-parser: ${message}` - : `Assertion error in llvm-print-after-all-parser`) + - (args.length > 0 ? `\n${JSON.stringify(args)}\n` : '') + - `\n${stack}` - ); + : 'Assertion error in llvm-print-after-all-parser') + + (args.length > 0 ? `\n${JSON.stringify(args)}\n` : '') + }\n${stack}`; } } enum SegmentType { - Horizontal, - Vertical, + Horizontal = 0, + Vertical = 1, } type Coordinate = { @@ -95,9 +94,9 @@ type Block = { }; enum DfsState { - NotVisited, - Pending, - Visited, + NotVisited = 0, + Pending = 1, + Visited = 2, } type ColumnDescriptor = { @@ -403,9 +402,8 @@ export class GraphLayoutCore { events.sort((a: Event, b: Event) => { if (a.row === b.row) { return a.type - b.type; - } else { - return a.row - b.row; } + return a.row - b.row; }); // const blockedColumns = Array(this.columnCount + 1).fill(-1); @@ -450,7 +448,8 @@ export class GraphLayoutCore { ) { edge.mainColumn = sourceColumn + 1; continue; - } else if ( + } + if ( targetColumn > sourceColumn && blockedColumns[sourceColumn - 1] < topRow && targetColumn - sourceColumn <= distanceRight + 2 @@ -581,7 +580,6 @@ export class GraphLayoutCore { prevSegment.end = segment.end; edge.path.splice(i, 1); movement = true; - continue; } } } while (movement); @@ -618,7 +616,7 @@ export class GraphLayoutCore { VERTICAL = 0, RIGHTCORNER = 1, RIGHTU = 2, - NULL = NaN, + NULL = Number.NaN, } const segments: { segment: EdgeSegment; @@ -700,26 +698,22 @@ export class GraphLayoutCore { segments.sort((a, b) => { if (a.kind !== b.kind) { return a.kind - b.kind; - } else { - const kind = a.kind; // a.kind == b.kind - if (a.length !== b.length) { - if (kind <= 0) { - // shortest first if coming from the left - return a.length - b.length; - } else { - // coming from the right, shortest last - // reverse edge length order - return b.length - a.length; - } - } else { - if (kind <= 0) { - return a.tiebreaker - b.tiebreaker; - } else { - // coming from the right, reverse - return b.tiebreaker - a.tiebreaker; - } - } } + const kind = a.kind; // a.kind == b.kind + if (a.length !== b.length) { + if (kind <= 0) { + // shortest first if coming from the left + return a.length - b.length; + } + // coming from the right, shortest last + // reverse edge length order + return b.length - a.length; + } + if (kind <= 0) { + return a.tiebreaker - b.tiebreaker; + } + // coming from the right, reverse + return b.tiebreaker - a.tiebreaker; }); for (const segmentEntry of segments) { const {segment} = segmentEntry; diff --git a/static/highlight.ts b/static/highlight.ts index 7c53744ad..4940537eb 100644 --- a/static/highlight.ts +++ b/static/highlight.ts @@ -25,7 +25,7 @@ type Interval = {start: number; length: number}; function regexExecAll(base_re: RegExp, s: string) { - const re = new RegExp(base_re.source, base_re.flags + 'gd'); + const re = new RegExp(base_re.source, `${base_re.flags}gd`); let m: any; const matches: Interval[] = []; while ((m = re.exec(s)) != null) { diff --git a/static/history.ts b/static/history.ts index d4bc09338..976f9fe97 100644 --- a/static/history.ts +++ b/static/history.ts @@ -23,8 +23,8 @@ // POSSIBILITY OF SUCH DAMAGE. import _ from 'underscore'; -import {Sharing} from './sharing.js'; import {localStorage} from './local.js'; +import {Sharing} from './sharing.js'; const maxHistoryEntries = 30; type Source = {dt: number; source: string}; diff --git a/static/hub.ts b/static/hub.ts index 5f200acef..cebdbd111 100644 --- a/static/hub.ts +++ b/static/hub.ts @@ -29,6 +29,7 @@ import {CompilerService} from './compiler-service.js'; import { AST_VIEW_COMPONENT_NAME, CFG_VIEW_COMPONENT_NAME, + CLANGIR_VIEW_COMPONENT_NAME, COMPILER_COMPONENT_NAME, CONFORMANCE_VIEW_COMPONENT_NAME, DEVICE_VIEW_COMPONENT_NAME, @@ -43,52 +44,51 @@ import { HASKELL_CORE_VIEW_COMPONENT_NAME, HASKELL_STG_VIEW_COMPONENT_NAME, IR_VIEW_COMPONENT_NAME, - CLANGIR_VIEW_COMPONENT_NAME, - OPT_PIPELINE_VIEW_COMPONENT_NAME, LLVM_OPT_PIPELINE_VIEW_COMPONENT_NAME, + OPT_PIPELINE_VIEW_COMPONENT_NAME, OPT_VIEW_COMPONENT_NAME, - STACK_USAGE_VIEW_COMPONENT_NAME, OUTPUT_COMPONENT_NAME, PP_VIEW_COMPONENT_NAME, RUST_HIR_VIEW_COMPONENT_NAME, RUST_MACRO_EXP_VIEW_COMPONENT_NAME, RUST_MIR_VIEW_COMPONENT_NAME, + STACK_USAGE_VIEW_COMPONENT_NAME, TOOL_COMPONENT_NAME, TOOL_INPUT_VIEW_COMPONENT_NAME, TREE_COMPONENT_NAME, } from './components.interfaces.js'; import {EventHub} from './event-hub.js'; -import {Editor} from './panes/editor.js'; -import {Tree} from './panes/tree.js'; -import {Compiler} from './panes/compiler.js'; -import {Executor} from './panes/executor.js'; -import {Output} from './panes/output.js'; -import {Tool} from './panes/tool.js'; -import {Diff} from './panes/diff.js'; -import {ToolInputView} from './panes/tool-input-view.js'; -import {Opt as OptView} from './panes/opt-view.js'; -import {StackUsage as StackUsageView} from './panes/stack-usage-view.js'; -import {Flags as FlagsView} from './panes/flags-view.js'; -import {PP as PreProcessorView} from './panes/pp-view.js'; +import {EventMap} from './event-map.js'; +import {IdentifierSet} from './identifier-set.js'; +import {LanguageKey} from './languages.interfaces.js'; import {Ast as AstView} from './panes/ast-view.js'; -import {Ir as IrView} from './panes/ir-view.js'; +import {Cfg as CfgView} from './panes/cfg-view.js'; import {Clangir as ClangirView} from './panes/clangir-view.js'; -import {OptPipeline} from './panes/opt-pipeline.js'; +import {Compiler} from './panes/compiler.js'; +import {Conformance as ConformanceView} from './panes/conformance-view.js'; import {DeviceAsm as DeviceView} from './panes/device-view.js'; +import {Diff} from './panes/diff.js'; +import {Editor} from './panes/editor.js'; +import {Executor} from './panes/executor.js'; +import {Flags as FlagsView} from './panes/flags-view.js'; +import {GccDump as GCCDumpView} from './panes/gccdump-view.js'; import {GnatDebug as GnatDebugView} from './panes/gnatdebug-view.js'; -import {RustMir as RustMirView} from './panes/rustmir-view.js'; -import {RustHir as RustHirView} from './panes/rusthir-view.js'; +import {GnatDebugTree as GnatDebugTreeView} from './panes/gnatdebugtree-view.js'; +import {HaskellCmm as HaskellCmmView} from './panes/haskellcmm-view.js'; import {HaskellCore as HaskellCoreView} from './panes/haskellcore-view.js'; import {HaskellStg as HaskellStgView} from './panes/haskellstg-view.js'; -import {HaskellCmm as HaskellCmmView} from './panes/haskellcmm-view.js'; -import {GccDump as GCCDumpView} from './panes/gccdump-view.js'; -import {Cfg as CfgView} from './panes/cfg-view.js'; -import {Conformance as ConformanceView} from './panes/conformance-view.js'; -import {GnatDebugTree as GnatDebugTreeView} from './panes/gnatdebugtree-view.js'; +import {Ir as IrView} from './panes/ir-view.js'; +import {OptPipeline} from './panes/opt-pipeline.js'; +import {Opt as OptView} from './panes/opt-view.js'; +import {Output} from './panes/output.js'; +import {PP as PreProcessorView} from './panes/pp-view.js'; +import {RustHir as RustHirView} from './panes/rusthir-view.js'; import {RustMacroExp as RustMacroExpView} from './panes/rustmacroexp-view.js'; -import {IdentifierSet} from './identifier-set.js'; -import {EventMap} from './event-map.js'; -import {LanguageKey} from './languages.interfaces.js'; +import {RustMir as RustMirView} from './panes/rustmir-view.js'; +import {StackUsage as StackUsageView} from './panes/stack-usage-view.js'; +import {ToolInputView} from './panes/tool-input-view.js'; +import {Tool} from './panes/tool.js'; +import {Tree} from './panes/tree.js'; type EventDescriptorMap = { [E in keyof EventMap]: [E, ...Parameters]; @@ -345,11 +345,10 @@ export class Hub { // property if (child.componentName === 'codeEditor') { return this.findParentRowOrColumnOrStack(child); - } else { - if (child.isRow || child.isColumn || child.isStack) { - const editor = this.findEditorInChildren(child); - if (editor) return editor; - } + } + if (child.isRow || child.isColumn || child.isStack) { + const editor = this.findEditorInChildren(child); + if (editor) return editor; } index++; } diff --git a/static/lib-utils.ts b/static/lib-utils.ts index 093de7f88..ce1a8152a 100644 --- a/static/lib-utils.ts +++ b/static/lib-utils.ts @@ -22,15 +22,15 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import {options} from './options.js'; -import {LanguageLibs, Library} from './options.interfaces.js'; import {Remote} from './compiler.interfaces.js'; +import {LanguageLibs, Library} from './options.interfaces.js'; +import {options} from './options.js'; const LIB_MATCH_RE = /([\w-]*)\.([\w-]*)/i; function getRemoteId(language: string, remoteUrl: string): string { const url: URL = new URL(remoteUrl); - return url.host.replace(/\./g, '_') + '_' + language; + return `${url.host.replace(/\./g, '_')}_${language}`; } function getRemoteLibraries(language: string, remoteUrl: string): LanguageLibs { @@ -77,11 +77,10 @@ export function getSupportedLibraries( return copyAndFilterLibraries(allLibs, supportedLibrariesArr); } return allLibs; - } else { - const allLibs = getRemoteLibraries(langId, remote.target); - if (supportedLibrariesArr && supportedLibrariesArr.length > 0) { - return copyAndFilterLibraries(allLibs, supportedLibrariesArr); - } - return allLibs; } + const allLibs = getRemoteLibraries(langId, remote.target); + if (supportedLibrariesArr && supportedLibrariesArr.length > 0) { + return copyAndFilterLibraries(allLibs, supportedLibrariesArr); + } + return allLibs; } diff --git a/static/line-colouring.ts b/static/line-colouring.ts index 7a2491b57..731160cc1 100644 --- a/static/line-colouring.ts +++ b/static/line-colouring.ts @@ -103,7 +103,7 @@ export class LineColouring { let colourIdx = 0; for (const editorIdStr of _.keys(this.colouredSourceLinesByEditor)) { - const editorId = parseInt(editorIdStr); + const editorId = Number.parseInt(editorIdStr); const lines = this.getUniqueLinesForEditor(editorId); for (const line of lines) { @@ -116,7 +116,7 @@ export class LineColouring { const editorIds = _.keys(this.linesAndColourByEditor); for (const compilerIdStr of compilerIds) { - const compilerId = parseInt(compilerIdStr); + const compilerId = Number.parseInt(compilerIdStr); for (const editorId of _.keys(this.colouredSourceLinesByEditor)) { for (const info of this.colouredSourceLinesByEditor[editorId]) { if (info.compilerId === compilerId && info.colourIdx >= 0) { @@ -138,16 +138,14 @@ export class LineColouring { public getColoursForCompiler(compilerId: number): Record { if (compilerId in this.linesAndColourByCompiler) { return this.linesAndColourByCompiler[compilerId]; - } else { - return {}; } + return {}; } public getColoursForEditor(editorId: number): Record { if (editorId in this.linesAndColourByEditor) { return this.linesAndColourByEditor[editorId]; - } else { - return {}; } + return {}; } } diff --git a/static/main.ts b/static/main.ts index 8f75398a7..e1983ab69 100644 --- a/static/main.ts +++ b/static/main.ts @@ -23,7 +23,7 @@ // POSSIBILITY OF SUCH DAMAGE. // Setup sentry before anything else so we can capture errors -import {SetupSentry, SentryCapture, setSentryLayout} from './sentry.js'; +import {SentryCapture, SetupSentry, setSentryLayout} from './sentry.js'; SetupSentry(); @@ -34,38 +34,38 @@ import 'bootstrap'; import $ from 'jquery'; import _ from 'underscore'; +import clipboard from 'clipboard'; import GoldenLayout from 'golden-layout'; import JsCookie from 'js-cookie'; -import clipboard from 'clipboard'; // We re-assign this let jsCookie = JsCookie; -import {Sharing} from './sharing.js'; -import * as Components from './components.js'; -import * as url from './url.js'; -import {Hub} from './hub.js'; -import {Settings, SiteSettings} from './settings.js'; -import {Alert} from './widgets/alert.js'; -import {Themer} from './themes.js'; -import * as motd from './motd.js'; -import {SimpleCook} from './widgets/simplecook.js'; -import {HistoryWidget} from './widgets/history-widget.js'; -import * as History from './history.js'; -import {Presentation} from './presentation.js'; -import {setupSiteTemplateWidgetButton} from './widgets/site-templates-widget.js'; -import {options} from './options.js'; import {unwrap} from './assert.js'; +import * as Components from './components.js'; +import * as History from './history.js'; +import {Hub} from './hub.js'; +import * as motd from './motd.js'; +import {options} from './options.js'; +import {Presentation} from './presentation.js'; +import {Settings, SiteSettings} from './settings.js'; +import {Sharing} from './sharing.js'; +import {Themer} from './themes.js'; +import * as url from './url.js'; +import {Alert} from './widgets/alert.js'; +import {HistoryWidget} from './widgets/history-widget.js'; +import {SimpleCook} from './widgets/simplecook.js'; +import {setupSiteTemplateWidgetButton} from './widgets/site-templates-widget.js'; import {Language, LanguageKey} from '../types/languages.interfaces.js'; -import {CompilerExplorerOptions} from './global.js'; import {ComponentConfig, EmptyCompilerState, StateWithId, StateWithLanguage} from './components.interfaces.js'; +import {CompilerExplorerOptions} from './global.js'; import * as utils from '../shared/common-utils.js'; -import {Printerinator} from './print-view.js'; -import {formatISODate, updateAndCalcTopBarHeight} from './utils.js'; import {localStorage, sessionThenLocalStorage} from './local.js'; +import {Printerinator} from './print-view.js'; import {setupRealDark, takeUsersOutOfRealDark} from './real-dark.js'; +import {formatISODate, updateAndCalcTopBarHeight} from './utils.js'; const logos = require.context('../views/resources/logos', false, /\.(png|svg)$/); @@ -141,10 +141,7 @@ function setupButtons(options: CompilerExplorerOptions, hub: Hub) { // so we instead trigger a click here when we want it to open with this effect. Sorry! if (options.policies.privacy.enabled) { $('#privacy').on('click', (event, data) => { - const modal = alertSystem.alert( - data && data.title ? data.title : 'Privacy policy', - policyDocuments.privacy.text, - ); + const modal = alertSystem.alert(data?.title ? data.title : 'Privacy policy', policyDocuments.privacy.text); calcLocaleChangedDate(modal); // I can't remember why this check is here as it seems superfluous if (options.policies.privacy.enabled) { @@ -158,13 +155,7 @@ function setupButtons(options: CompilerExplorerOptions, hub: Hub) { if (options.policies.cookies.enabled) { const getCookieTitle = () => { - return ( - 'Cookies & related technologies policy

Current consent status: ' + - (hasCookieConsented(options) ? 'Granted' : 'Denied') + - '

' - ); + return `Cookies & related technologies policy

Current consent status: ${hasCookieConsented(options) ? 'Granted' : 'Denied'}

`; }; $('#cookies').on('click', () => { const modal = alertSystem.ask(getCookieTitle(), policyDocuments.cookies.text, { @@ -197,7 +188,7 @@ function setupButtons(options: CompilerExplorerOptions, hub: Hub) { alertSystem.alert('Changelog', $(require('./generated/changelog.pug').default.text) as any); }); - $.get(window.location.origin + window.httpRoot + 'bits/icons.html') + $.get(`${window.location.origin + window.httpRoot}bits/icons.html`) .done(data => { $('#ces .ces-icons').html(data); }) @@ -206,7 +197,7 @@ function setupButtons(options: CompilerExplorerOptions, hub: Hub) { }); $('#ces').on('click', () => { - $.get(window.location.origin + window.httpRoot + 'bits/sponsors.html') + $.get(`${window.location.origin + window.httpRoot}bits/sponsors.html`) .done(data => { alertSystem.alert('Compiler Explorer Sponsors', data); }) @@ -214,7 +205,7 @@ function setupButtons(options: CompilerExplorerOptions, hub: Hub) { const result = err.responseText || JSON.stringify(err); alertSystem.alert( 'Compiler Explorer Sponsors', - '
Unable to fetch sponsors:
' + result + '
', + `
Unable to fetch sponsors:
${result}
`, ); }); }); @@ -255,7 +246,7 @@ function configFromEmbedded(embeddedUrl: string, defaultLangId: string) { ); throw new Error('Embed url decode error'); } - if (params && params.source && params.compiler) { + if (params?.source && params.compiler) { const filters = Object.fromEntries(((params.filters as string) || '').split(',').map(o => [o, true])); // TODO(jeremy-rifkin): Fix types return { @@ -269,9 +260,8 @@ function configFromEmbedded(embeddedUrl: string, defaultLangId: string) { }, ], }; - } else { - return url.deserialiseState(embeddedUrl); } + return url.deserialiseState(embeddedUrl); } // TODO(jeremy-rifkin): Unsure of the type, just typing enough for `content` at the moment @@ -485,9 +475,9 @@ function setupLanguageLogos(languages: Partial>) { for (const lang of Object.values(languages)) { try { if (lang.logoUrl !== null) { - lang.logoData = logos('./' + lang.logoUrl); + lang.logoData = logos(`./${lang.logoUrl}`); if (lang.logoUrlDark !== null) { - lang.logoDataDark = logos('./' + lang.logoUrlDark); + lang.logoDataDark = logos(`./${lang.logoUrlDark}`); } } } catch (ignored) { @@ -526,9 +516,9 @@ function showShortlinkInfoButton() { } function initShortlinkInfoButton() { - if (options.metadata && options.metadata['ogCreated']) { + if (options.metadata?.ogCreated) { const buttonText = $('.shortlinkInfoText'); - const dt = new Date(options.metadata['ogCreated']); + const dt = new Date(options.metadata.ogCreated); buttonText.html(''); const button = $('.shortlinkInfo'); @@ -581,7 +571,7 @@ function start() { // We allow this to be configurable so that (for example), gcc.godbolt.org and d.godbolt.org // share the same cookie domain for some settings. const cookieDomain = new RegExp(options.cookieDomainRe).exec(window.location.hostname); - if (cookieDomain && cookieDomain[0]) { + if (cookieDomain?.[0]) { jsCookie = jsCookie.withAttributes({domain: cookieDomain[0]}); } @@ -721,7 +711,7 @@ function start() { const release = window.compilerExplorerOptions.gitReleaseCommit; let versionLink = 'https://github.com/compiler-explorer/compiler-explorer/'; if (release) { - versionLink += 'tree/' + release; + versionLink += `tree/${release}`; } $('#version-tree').prop('href', versionLink); } @@ -742,7 +732,7 @@ function start() { .map((_, value) => value.dataset.statsid) .get() .join(','); - $.post(options.pageloadUrl + '?icons=' + encodeURIComponent(visibleIcons)); + $.post(`${options.pageloadUrl}?icons=${encodeURIComponent(visibleIcons)}`); }, 5000); } diff --git a/static/modes/ada-mode.ts b/static/modes/ada-mode.ts index 8d56e2c92..819c263d4 100644 --- a/static/modes/ada-mode.ts +++ b/static/modes/ada-mode.ts @@ -225,5 +225,3 @@ export function definition(): monaco.languages.IMonarchLanguage { } monaco.languages.register({id: 'ada'}); monaco.languages.setMonarchTokensProvider('ada', definition()); - -export {}; diff --git a/static/modes/c3-mode.ts b/static/modes/c3-mode.ts index 0a00c19db..e30eb97f5 100644 --- a/static/modes/c3-mode.ts +++ b/static/modes/c3-mode.ts @@ -331,5 +331,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'c3'}); monaco.languages.setMonarchTokensProvider('c3', definition()); - -export {}; diff --git a/static/modes/clean-mode.ts b/static/modes/clean-mode.ts index 9ea31bcdd..3225350b1 100644 --- a/static/modes/clean-mode.ts +++ b/static/modes/clean-mode.ts @@ -98,5 +98,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'clean'}); monaco.languages.setMonarchTokensProvider('clean', definition()); - -export {}; diff --git a/static/modes/cmake-mode.ts b/static/modes/cmake-mode.ts index 7d5aea642..8c86e75e3 100644 --- a/static/modes/cmake-mode.ts +++ b/static/modes/cmake-mode.ts @@ -101,5 +101,3 @@ function configuration(): monaco.languages.LanguageConfiguration { monaco.languages.register({id: 'cmake'}); monaco.languages.setMonarchTokensProvider('cmake', definition()); monaco.languages.setLanguageConfiguration('cmake', configuration()); - -export {}; diff --git a/static/modes/cobol-mode.ts b/static/modes/cobol-mode.ts index 49012a830..c1e6ef78e 100644 --- a/static/modes/cobol-mode.ts +++ b/static/modes/cobol-mode.ts @@ -1172,5 +1172,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'cobol'}); monaco.languages.setMonarchTokensProvider('cobol', definition()); - -export {}; diff --git a/static/modes/cpp-for-opencl-mode.ts b/static/modes/cpp-for-opencl-mode.ts index 398757d95..a1765d20d 100644 --- a/static/modes/cpp-for-opencl-mode.ts +++ b/static/modes/cpp-for-opencl-mode.ts @@ -45,7 +45,7 @@ function definition(): monaco.languages.IMonarchLanguage { } function vectorTypes(basename) { - return [basename + '2', basename + '3', basename + '4', basename + '8', basename + '16']; + return [`${basename}2`, `${basename}3`, `${basename}4`, `${basename}8`, `${basename}16`]; } // Keywords for C++ for OpenCL addKeywords([ @@ -113,5 +113,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'cpp-for-opencl'}); monaco.languages.setLanguageConfiguration('cpp-for-opencl', cpp.conf); monaco.languages.setMonarchTokensProvider('cpp-for-opencl', definition()); - -export {}; diff --git a/static/modes/cppcircle-mode.ts b/static/modes/cppcircle-mode.ts index 270d6a7f7..c73928427 100644 --- a/static/modes/cppcircle-mode.ts +++ b/static/modes/cppcircle-mode.ts @@ -138,5 +138,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'cppcircle'}); monaco.languages.setLanguageConfiguration('cppcircle', cpp.conf); monaco.languages.setMonarchTokensProvider('cppcircle', definition()); - -export {}; diff --git a/static/modes/cppfront-mode.ts b/static/modes/cppfront-mode.ts index 50f65dad4..7fd5c1d1f 100644 --- a/static/modes/cppfront-mode.ts +++ b/static/modes/cppfront-mode.ts @@ -55,10 +55,10 @@ function definition(): monaco.languages.IMonarchLanguage { // Generic parsers. function parseCpp2Balanced(delimiters: string, delimiter: string, opener: RegExp, closer: RegExp) { - return (cppfront.tokenizer['parse_cpp2_balanced_' + delimiters] = [ + return (cppfront.tokenizer[`parse_cpp2_balanced_${delimiters}`] = [ {include: '@whitespace'}, - [opener, 'delimiter.' + delimiter, '$S2.$S3.$S4'], - [closer, 'delimiter.' + delimiter, '@pop'], + [opener, `delimiter.${delimiter}`, '$S2.$S3.$S4'], + [closer, `delimiter.${delimiter}`, '@pop'], [/./, 'invalid', '@pop'], ]); } @@ -859,5 +859,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'cpp2-cppfront'}); monaco.languages.setLanguageConfiguration('cpp2-cppfront', cpp.conf); monaco.languages.setMonarchTokensProvider('cpp2-cppfront', definition()); - -export {}; diff --git a/static/modes/cppx-blue-mode.ts b/static/modes/cppx-blue-mode.ts index d83ddce13..3d2addf7e 100644 --- a/static/modes/cppx-blue-mode.ts +++ b/static/modes/cppx-blue-mode.ts @@ -46,5 +46,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'cppx-blue'}); monaco.languages.setLanguageConfiguration('cppx-blue', cpp.conf); monaco.languages.setMonarchTokensProvider('cppx-blue', definition()); - -export {}; diff --git a/static/modes/cppx-gold-mode.ts b/static/modes/cppx-gold-mode.ts index 344447468..8dfbe20db 100644 --- a/static/modes/cppx-gold-mode.ts +++ b/static/modes/cppx-gold-mode.ts @@ -305,5 +305,3 @@ function configuration(): monaco.languages.LanguageConfiguration { monaco.languages.register({id: 'cppx-gold'}); monaco.languages.setMonarchTokensProvider('cppx-gold', definition()); monaco.languages.setLanguageConfiguration('cppx-gold', configuration()); - -export {}; diff --git a/static/modes/cuda-mode.ts b/static/modes/cuda-mode.ts index c07d3ef88..b266b0c68 100644 --- a/static/modes/cuda-mode.ts +++ b/static/modes/cuda-mode.ts @@ -62,5 +62,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'cuda'}); monaco.languages.setLanguageConfiguration('cuda', cpp.conf); monaco.languages.setMonarchTokensProvider('cuda', definition()); - -export {}; diff --git a/static/modes/d-mode.ts b/static/modes/d-mode.ts index c2578debb..d9efbae94 100644 --- a/static/modes/d-mode.ts +++ b/static/modes/d-mode.ts @@ -336,5 +336,3 @@ function configuration(): monaco.languages.LanguageConfiguration { monaco.languages.register({id: 'd'}); monaco.languages.setMonarchTokensProvider('d', definition()); monaco.languages.setLanguageConfiguration('d', configuration()); - -export {}; diff --git a/static/modes/gccdump-rtl-gimple-mode.ts b/static/modes/gccdump-rtl-gimple-mode.ts index c56060ca6..0cef40beb 100644 --- a/static/modes/gccdump-rtl-gimple-mode.ts +++ b/static/modes/gccdump-rtl-gimple-mode.ts @@ -351,5 +351,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'gccdump-rtl-gimple'}); monaco.languages.setMonarchTokensProvider('gccdump-rtl-gimple', definition()); - -export {}; diff --git a/static/modes/glsl-mode.ts b/static/modes/glsl-mode.ts index 68861f23c..b5a47ed98 100644 --- a/static/modes/glsl-mode.ts +++ b/static/modes/glsl-mode.ts @@ -737,5 +737,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'glsl'}); monaco.languages.setMonarchTokensProvider('glsl', definition()); - -export {}; diff --git a/static/modes/haskell-mode.ts b/static/modes/haskell-mode.ts index 8251f94f7..6d9fa96cd 100644 --- a/static/modes/haskell-mode.ts +++ b/static/modes/haskell-mode.ts @@ -94,5 +94,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'haskell'}); monaco.languages.setMonarchTokensProvider('haskell', definition()); - -export {}; diff --git a/static/modes/hlsl-mode.ts b/static/modes/hlsl-mode.ts index 0f2ff76bc..b0caa066d 100644 --- a/static/modes/hlsl-mode.ts +++ b/static/modes/hlsl-mode.ts @@ -321,5 +321,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'hlsl'}); monaco.languages.setMonarchTokensProvider('hlsl', definition()); - -export {}; diff --git a/static/modes/hook-mode.ts b/static/modes/hook-mode.ts index e267e8a57..9c20fcae4 100644 --- a/static/modes/hook-mode.ts +++ b/static/modes/hook-mode.ts @@ -180,5 +180,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'hook'}); monaco.languages.setMonarchTokensProvider('hook', definition()); - -export {}; diff --git a/static/modes/hylo-mode.ts b/static/modes/hylo-mode.ts index 974a9fced..60e0e66b0 100644 --- a/static/modes/hylo-mode.ts +++ b/static/modes/hylo-mode.ts @@ -179,5 +179,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'hylo'}); monaco.languages.setMonarchTokensProvider('hylo', definition()); monaco.languages.setLanguageConfiguration('hylo', swift.conf); - -export {}; diff --git a/static/modes/ispc-mode.ts b/static/modes/ispc-mode.ts index 35a671db9..e1be636f8 100644 --- a/static/modes/ispc-mode.ts +++ b/static/modes/ispc-mode.ts @@ -86,5 +86,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'ispc'}); monaco.languages.setLanguageConfiguration('ispc', cpp.conf); monaco.languages.setMonarchTokensProvider('ispc', definition()); - -export {}; diff --git a/static/modes/jakt-mode.ts b/static/modes/jakt-mode.ts index d9ddac65a..1b503cf54 100644 --- a/static/modes/jakt-mode.ts +++ b/static/modes/jakt-mode.ts @@ -206,5 +206,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'jakt'}); monaco.languages.setMonarchTokensProvider('jakt', definition()); - -export {}; diff --git a/static/modes/llvm-ir-mode.ts b/static/modes/llvm-ir-mode.ts index 5d605195a..7d61c6960 100644 --- a/static/modes/llvm-ir-mode.ts +++ b/static/modes/llvm-ir-mode.ts @@ -392,5 +392,3 @@ const config: monaco.languages.LanguageConfiguration = { monaco.languages.register({id: 'llvm-ir'}); monaco.languages.setMonarchTokensProvider('llvm-ir', definition()); monaco.languages.setLanguageConfiguration('llvm-ir', config); - -export {}; diff --git a/static/modes/mlir-mode.ts b/static/modes/mlir-mode.ts index 8c98aa268..2119b3442 100644 --- a/static/modes/mlir-mode.ts +++ b/static/modes/mlir-mode.ts @@ -30,5 +30,3 @@ import {definition} from './llvm-ir-mode.js'; monaco.languages.register({id: 'mlir'}); monaco.languages.setMonarchTokensProvider('mlir', definition()); - -export {}; diff --git a/static/modes/modula2-mode.ts b/static/modes/modula2-mode.ts index a2911c1c5..c382c5b03 100644 --- a/static/modes/modula2-mode.ts +++ b/static/modes/modula2-mode.ts @@ -119,5 +119,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'modula2'}); monaco.languages.setMonarchTokensProvider('modula2', definition()); - -export {}; diff --git a/static/modes/nim-mode.ts b/static/modes/nim-mode.ts index ab927d857..dc88d68ee 100644 --- a/static/modes/nim-mode.ts +++ b/static/modes/nim-mode.ts @@ -179,5 +179,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'nim'}); monaco.languages.setMonarchTokensProvider('nim', definition()); - -export {}; diff --git a/static/modes/ocaml-mode.ts b/static/modes/ocaml-mode.ts index e6de48015..fcdf18b1a 100644 --- a/static/modes/ocaml-mode.ts +++ b/static/modes/ocaml-mode.ts @@ -126,5 +126,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'ocaml'}); monaco.languages.setMonarchTokensProvider('ocaml', definition()); - -export {}; diff --git a/static/modes/openclc-mode.ts b/static/modes/openclc-mode.ts index b27ccc2e8..5454fee91 100644 --- a/static/modes/openclc-mode.ts +++ b/static/modes/openclc-mode.ts @@ -58,7 +58,7 @@ function definition(): monaco.languages.IMonarchLanguage { } function vectorTypes(basename) { - return [basename + '2', basename + '3', basename + '4', basename + '8', basename + '16']; + return [`${basename}2`, `${basename}3`, `${basename}4`, `${basename}8`, `${basename}16`]; } removeKeywords([ @@ -143,5 +143,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'openclc'}); monaco.languages.setLanguageConfiguration('openclc', cpp.conf); monaco.languages.setMonarchTokensProvider('openclc', definition()); - -export {}; diff --git a/static/modes/ptx-mode.ts b/static/modes/ptx-mode.ts index 1bcdc7cfe..e13867d77 100644 --- a/static/modes/ptx-mode.ts +++ b/static/modes/ptx-mode.ts @@ -60,5 +60,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'ptx'}); monaco.languages.setMonarchTokensProvider('ptx', definition()); - -export {}; diff --git a/static/modes/spirv-mode.ts b/static/modes/spirv-mode.ts index 34fd2fd84..4c72be841 100644 --- a/static/modes/spirv-mode.ts +++ b/static/modes/spirv-mode.ts @@ -49,5 +49,3 @@ export function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'spirv'}); monaco.languages.setMonarchTokensProvider('spirv', definition()); - -export {}; diff --git a/static/modes/tablegen-mode.ts b/static/modes/tablegen-mode.ts index 7dd0183a4..c526994cd 100644 --- a/static/modes/tablegen-mode.ts +++ b/static/modes/tablegen-mode.ts @@ -190,5 +190,3 @@ export function definition(): monaco.languages.IMonarchLanguage { } monaco.languages.register({id: 'tablegen'}); monaco.languages.setMonarchTokensProvider('tablegen', definition()); - -export {}; diff --git a/static/modes/vala-mode.ts b/static/modes/vala-mode.ts index f28d7a44d..b2f1751a3 100644 --- a/static/modes/vala-mode.ts +++ b/static/modes/vala-mode.ts @@ -288,5 +288,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'vala'}); monaco.languages.setMonarchTokensProvider('vala', definition()); - -export {}; diff --git a/static/modes/zig-mode.ts b/static/modes/zig-mode.ts index d6bb8b39d..11c8b7a12 100644 --- a/static/modes/zig-mode.ts +++ b/static/modes/zig-mode.ts @@ -230,5 +230,3 @@ function definition(): monaco.languages.IMonarchLanguage { monaco.languages.register({id: 'zig'}); monaco.languages.setMonarchTokensProvider('zig', definition()); - -export {}; diff --git a/static/monaco-config.ts b/static/monaco-config.ts index 25fb92a11..3aa0faec7 100644 --- a/static/monaco-config.ts +++ b/static/monaco-config.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import _ from 'underscore'; import * as monaco from 'monaco-editor'; +import _ from 'underscore'; import {SiteSettings} from './settings.js'; diff --git a/static/multifile-service.ts b/static/multifile-service.ts index 9fb525b7e..c3fb1bf02 100644 --- a/static/multifile-service.ts +++ b/static/multifile-service.ts @@ -22,14 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import _ from 'underscore'; +import JSZip from 'jszip'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import path from 'path-browserify'; -import JSZip from 'jszip'; -import {Hub} from './hub.js'; -import {unwrap} from './assert.js'; +import _ from 'underscore'; import {FiledataPair} from '../types/compilation/compilation.interfaces.js'; +import {unwrap} from './assert.js'; +import {Hub} from './hub.js'; import {LanguageKey} from './languages.interfaces.js'; import {Alert} from './widgets/alert.js'; const languages = require('./options').options.languages; @@ -140,7 +140,7 @@ export class MultifileService { zip.forEach(async (relativePath, zipEntry) => { if (!zipEntry.dir) { let removeFromName = 0; - if (relativePath.indexOf(zipFilename + '/') === 0) { + if (relativePath.indexOf(`${zipFilename}/`) === 0) { removeFromName = zipFilename.length + 1; } @@ -243,9 +243,8 @@ export class MultifileService { if (file.isOpen) { const editor = this.hub.getEditorById(file.editorId); return editor?.getSource() ?? ''; - } else { - return file.content; } + return file.content; } public isEditorPartOfProject(editorId: number) { @@ -323,9 +322,8 @@ export class MultifileService { if (mainFile) { return this.getFileContents(mainFile); - } else { - return ''; } + return ''; } public getFileByEditorId(editorId: number): MultifileFile | undefined { @@ -423,9 +421,8 @@ export class MultifileService { const file = this.getFileByEditorId(editorId); if (file) { return this.includeByFileId(file.fileId); - } else { - return Promise.reject('File not found'); } + return Promise.reject('File not found'); } public forEachOpenFile(callback: (File) => void) { @@ -449,7 +446,7 @@ export class MultifileService { private static getDefaultMainSourceFilename(langId) { const lang = languages[langId]; const ext0 = lang.extensions[0]; - return 'example' + ext0; + return `example${ext0}`; } private getSuggestedFilename(file: MultifileFile, editor: any): string { @@ -548,8 +545,7 @@ export class MultifileService { const file = this.getFileByEditorId(editorId); if (file) { return this.renameFile(file.fileId); - } else { - return Promise.reject('File not found'); } + return Promise.reject('File not found'); } } diff --git a/static/options.interfaces.ts b/static/options.interfaces.ts index 1b3c1c889..4d54a3c7b 100644 --- a/static/options.interfaces.ts +++ b/static/options.interfaces.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import {Language, LanguageKey} from '../types/languages.interfaces.js'; import {CompilerInfo} from '../types/compiler.interfaces.js'; +import {Language, LanguageKey} from '../types/languages.interfaces.js'; import {Tool} from '../types/tool.interfaces.js'; export type LibraryVersion = { diff --git a/static/panes/ast-view.ts b/static/panes/ast-view.ts index 796c91ed9..aaa10a93b 100644 --- a/static/panes/ast-view.ts +++ b/static/panes/ast-view.ts @@ -22,21 +22,21 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import $ from 'jquery'; -import _ from 'underscore'; -import * as monaco from 'monaco-editor'; import {Container} from 'golden-layout'; +import $ from 'jquery'; +import * as monaco from 'monaco-editor'; +import _ from 'underscore'; -import {MonacoPane} from './pane.js'; -import {AstState} from './ast-view.interfaces.js'; -import {MonacoPaneState} from './pane.interfaces.js'; import * as colour from '../colour.js'; import * as monacoConfig from '../monaco-config.js'; +import {AstState} from './ast-view.interfaces.js'; +import {MonacoPaneState} from './pane.interfaces.js'; +import {MonacoPane} from './pane.js'; -import {Hub} from '../hub.js'; import {unwrap} from '../assert.js'; -import {CompilerInfo} from '../compiler.interfaces.js'; import {CompilationResult} from '../compilation/compilation.interfaces.js'; +import {CompilerInfo} from '../compiler.interfaces.js'; +import {Hub} from '../hub.js'; type DecorationEntry = { linkedCode: any[]; @@ -233,8 +233,7 @@ export class Ast extends MonacoPane = {}; for (const [index, code] of this.astCode.entries()) { if ( - code.source && - code.source.from?.line && + code.source?.from?.line && code.source.to?.line && code.source.from.line <= code.source.to.line && code.source.to.line < code.source.from.line + 100 diff --git a/static/panes/cfg-view.ts b/static/panes/cfg-view.ts index c561d2a11..c57f71b78 100644 --- a/static/panes/cfg-view.ts +++ b/static/panes/cfg-view.ts @@ -22,31 +22,31 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import {Pane} from './pane.js'; -import * as monaco from 'monaco-editor'; -import $ from 'jquery'; -import _ from 'underscore'; import * as fileSaver from 'file-saver'; +import $ from 'jquery'; +import * as monaco from 'monaco-editor'; +import _ from 'underscore'; +import {Pane} from './pane.js'; -import {CfgState} from './cfg-view.interfaces.js'; -import {Hub} from '../hub.js'; import {Container} from 'golden-layout'; -import {PaneState} from './pane.interfaces.js'; +import {Hub} from '../hub.js'; import * as utils from '../utils.js'; +import {CfgState} from './cfg-view.interfaces.js'; +import {PaneState} from './pane.interfaces.js'; +import TomSelect from 'tom-select'; +import {escapeHTML} from '../../shared/common-utils.js'; import { AnnotatedCfgDescriptor, AnnotatedNodeDescriptor, - CfgDescriptor, CFGResult, + CfgDescriptor, } from '../../types/compilation/cfg.interfaces.js'; -import {GraphLayoutCore} from '../graph-layout-core.js'; -import * as MonacoConfig from '../monaco-config.js'; -import TomSelect from 'tom-select'; import {assert, unwrap} from '../assert.js'; import {CompilationResult} from '../compilation/compilation.interfaces.js'; import {CompilerInfo} from '../compiler.interfaces.js'; -import {escapeHTML} from '../../shared/common-utils.js'; +import {GraphLayoutCore} from '../graph-layout-core.js'; +import * as MonacoConfig from '../monaco-config.js'; const ColorTable = { red: '#FE5D5D', @@ -76,26 +76,23 @@ function special_round(x: number) { if (x === 0) { return 0; } - const p = Math.pow(10, Math.floor(Math.log10(x))); + const p = 10 ** Math.floor(Math.log10(x)); // prettier-ignore - const candidates = [ - Math.round(x / p) * p - p / 2, - Math.round(x / p) * p, - Math.round(x / p) * p + p / 2, - ]; + const candidates = [Math.round(x / p) * p - p / 2, Math.round(x / p) * p, Math.round(x / p) * p + p / 2]; return Math.trunc(candidates.sort((a, b) => Math.abs(x - a) - Math.abs(x - b))[0]); } function size_to_human(bytes: number) { if (bytes < 1000) { - return special_round(bytes) + ' B'; - } else if (bytes < 1_000_000) { - return special_round(bytes / 1_000) + ' KB'; - } else if (bytes < 1_000_000_000) { - return special_round(bytes / 1_000_000) + ' MB'; - } else { - return special_round(bytes / 1_000_000_000) + ' GB'; + return `${special_round(bytes)} B`; } + if (bytes < 1_000_000) { + return `${special_round(bytes / 1_000)} KB`; + } + if (bytes < 1_000_000_000) { + return `${special_round(bytes / 1_000_000)} MB`; + } + return `${special_round(bytes / 1_000_000_000)} GB`; } export class Cfg extends Pane { @@ -158,11 +155,10 @@ export class Cfg extends Pane { // We need to check if this.state exists because this is called in the super constructor before this is actually // constructed // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (this.state && this.state.isircfg) { - return `IR CFG`; - } else { - return `CFG`; + if (this.state?.isircfg) { + return 'IR CFG'; } + return 'CFG'; } override registerButtons() { @@ -368,10 +364,9 @@ export class Cfg extends Pane { .map((line, i) => { if (line.length <= 100) { return line; - } else { - folded_lines.push(i); - return line.slice(0, 100); } + folded_lines.push(i); + return line.slice(0, 100); }) .join('\n'), this.contentsAreIr ? 'llvm-ir' : 'asm', @@ -484,18 +479,18 @@ export class Cfg extends Pane { const height = this.layout.getHeight(); this.graphDimensions.width = width; this.graphDimensions.height = height; - this.graphDiv.style.height = height + 'px'; - this.graphDiv.style.width = width + 'px'; - this.svg.style.height = height + 'px'; - this.svg.style.width = width + 'px'; - this.blockContainer.style.height = height + 'px'; - this.blockContainer.style.width = width + 'px'; + this.graphDiv.style.height = `${height}px`; + this.graphDiv.style.width = `${width}px`; + this.svg.style.height = `${height}px`; + this.svg.style.width = `${width}px`; + this.blockContainer.style.height = `${height}px`; + this.blockContainer.style.width = `${width}px`; for (const block of this.layout.blocks) { const elem = this.bbMap[block.data.id]; - elem.style.top = block.coordinates.y + 'px'; - elem.style.left = block.coordinates.x + 'px'; - elem.style.width = block.data.width + 'px'; - elem.style.height = block.data.height + 'px'; + elem.style.top = `${block.coordinates.y}px`; + elem.style.left = `${block.coordinates.x}px`; + elem.style.width = `${block.data.width}px`; + elem.style.height = `${block.data.height}px`; } } @@ -569,8 +564,8 @@ export class Cfg extends Pane { setPan(p: Coordinate) { this.currentPosition = p; - this.graphElement.style.left = this.currentPosition.x + 'px'; - this.graphElement.style.top = this.currentPosition.y + 'px'; + this.graphElement.style.left = `${this.currentPosition.x}px`; + this.graphElement.style.top = `${this.currentPosition.y}px`; } createSVG() { @@ -621,7 +616,7 @@ export class Cfg extends Pane { const left = span_box.left - block_bounding_box.left; doc += `${escapeHTML(text)}`; diff --git a/static/panes/clangir-view.ts b/static/panes/clangir-view.ts index 4bacfb229..9312e15fb 100644 --- a/static/panes/clangir-view.ts +++ b/static/panes/clangir-view.ts @@ -22,21 +22,21 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import $ from 'jquery'; -import _ from 'underscore'; -import * as monaco from 'monaco-editor'; import {Container} from 'golden-layout'; +import $ from 'jquery'; +import * as monaco from 'monaco-editor'; +import _ from 'underscore'; -import {MonacoPane} from './pane.js'; -import {MonacoPaneState} from './pane.interfaces.js'; import {ClangirState} from './clangir-view.interfaces.js'; +import {MonacoPaneState} from './pane.interfaces.js'; +import {MonacoPane} from './pane.js'; -import {extendConfig} from '../monaco-config.js'; -import {Hub} from '../hub.js'; +import {ClangirBackendOptions} from '../../types/compilation/clangir.interfaces.js'; import {CompilationResult} from '../compilation/compilation.interfaces.js'; import {CompilerInfo} from '../compiler.interfaces.js'; +import {Hub} from '../hub.js'; +import {extendConfig} from '../monaco-config.js'; import {Toggles} from '../widgets/toggles.js'; -import {ClangirBackendOptions} from '../../types/compilation/clangir.interfaces.js'; export class Clangir extends MonacoPane { private options: Toggles; diff --git a/static/panes/compiler.ts b/static/panes/compiler.ts index 632117969..03d7eb114 100644 --- a/static/panes/compiler.ts +++ b/static/panes/compiler.ts @@ -22,66 +22,66 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import _ from 'underscore'; -import $ from 'jquery'; import {Buffer} from 'buffer'; -import * as colour from '../colour.js'; -import {Toggles} from '../widgets/toggles.js'; -import * as Components from '../components.js'; -import {LRUCache} from 'lru-cache'; -import {options} from '../options.js'; -import * as monaco from 'monaco-editor'; -import {Alert} from '../widgets/alert.js'; -import {LibsWidget} from '../widgets/libs-widget.js'; -import * as codeLensHandler from '../codelens-handler.js'; -import * as monacoConfig from '../monaco-config.js'; -import * as TimingWidget from '../widgets/timing-info-widget.js'; -import {CompilerPicker} from '../widgets/compiler-picker.js'; -import {CompilerService} from '../compiler-service.js'; -import {SiteSettings} from '../settings.js'; -import * as LibUtils from '../lib-utils.js'; -import {getAssemblyDocumentation} from '../api/api.js'; -import {MonacoPane} from './pane.js'; -import {CompilerInfo} from '../../types/compiler.interfaces.js'; -import {MonacoPaneState} from './pane.interfaces.js'; -import {Hub} from '../hub.js'; import {Container} from 'golden-layout'; -import {CompilerCurrentState, CompilerState} from './compiler.interfaces.js'; -import {ComponentConfig, NewToolSettings, ToolViewState} from '../components.interfaces.js'; -import {LanguageLibs} from '../options.interfaces.js'; -import {GccDumpFiltersState, GccDumpViewSelectedPass} from './gccdump-view.interfaces.js'; +import $ from 'jquery'; +import {LRUCache} from 'lru-cache'; +import * as monaco from 'monaco-editor'; +import {editor} from 'monaco-editor'; +import _ from 'underscore'; import {AssemblyInstructionInfo} from '../../lib/asm-docs/base.js'; -import {PPOptions} from './pp-view.interfaces.js'; -import {CompilationStatus} from '../compiler-service.interfaces.js'; -import {WidgetState} from '../widgets/libs-widget.interfaces.js'; -import {OptPipelineBackendOptions} from '../compilation/opt-pipeline-output.interfaces.js'; import { ActiveTool, BypassCache, CompilationRequest, CompilationRequestOptions, CompilationResult, - GccDumpFlags, FiledataPair, + GccDumpFlags, } from '../../types/compilation/compilation.interfaces.js'; +import {CompilerInfo} from '../../types/compiler.interfaces.js'; import {ResultLine} from '../../types/resultline/resultline.interfaces.js'; +import {getAssemblyDocumentation} from '../api/api.js'; +import * as codeLensHandler from '../codelens-handler.js'; +import * as colour from '../colour.js'; +import {OptPipelineBackendOptions} from '../compilation/opt-pipeline-output.interfaces.js'; +import {CompilationStatus} from '../compiler-service.interfaces.js'; +import {CompilerService} from '../compiler-service.js'; +import {ComponentConfig, NewToolSettings, ToolViewState} from '../components.interfaces.js'; +import * as Components from '../components.js'; +import {Hub} from '../hub.js'; +import * as LibUtils from '../lib-utils.js'; +import * as monacoConfig from '../monaco-config.js'; +import {LanguageLibs} from '../options.interfaces.js'; +import {options} from '../options.js'; +import {SiteSettings} from '../settings.js'; import * as utils from '../utils.js'; -import {editor} from 'monaco-editor'; +import {Alert} from '../widgets/alert.js'; +import {CompilerPicker} from '../widgets/compiler-picker.js'; +import {WidgetState} from '../widgets/libs-widget.interfaces.js'; +import {LibsWidget} from '../widgets/libs-widget.js'; +import * as TimingWidget from '../widgets/timing-info-widget.js'; +import {Toggles} from '../widgets/toggles.js'; +import {CompilerCurrentState, CompilerState} from './compiler.interfaces.js'; +import {GccDumpFiltersState, GccDumpViewSelectedPass} from './gccdump-view.interfaces.js'; +import {MonacoPaneState} from './pane.interfaces.js'; +import {MonacoPane} from './pane.js'; +import {PPOptions} from './pp-view.interfaces.js'; import IEditorMouseEvent = editor.IEditorMouseEvent; -import {Tool, ArtifactType, Artifact} from '../../types/tool.interfaces.js'; -import {assert, unwrap, unwrapString} from '../assert.js'; import {CompilerOutputOptions} from '../../types/features/filters.interfaces.js'; +import {Artifact, ArtifactType, Tool} from '../../types/tool.interfaces.js'; +import {assert, unwrap, unwrapString} from '../assert.js'; import {SourceAndFiles} from '../download-service.js'; import fileSaver = require('file-saver'); +import {escapeHTML} from '../../shared/common-utils.js'; +import {ClangirBackendOptions} from '../compilation/clangir.interfaces.js'; +import {LLVMIrBackendOptions} from '../compilation/ir.interfaces.js'; import {ICompilerShared} from '../compiler-shared.interfaces.js'; import {CompilerShared} from '../compiler-shared.js'; -import {SentryCapture} from '../sentry.js'; -import {LLVMIrBackendOptions} from '../compilation/ir.interfaces.js'; import {InstructionSet} from '../instructionsets.js'; -import {escapeHTML} from '../../shared/common-utils.js'; -import {CompilerVersionInfo, setCompilerVersionPopoverForPane} from '../widgets/compiler-version-info.js'; -import {ClangirBackendOptions} from '../compilation/clangir.interfaces.js'; import {LanguageKey} from '../languages.interfaces.js'; +import {SentryCapture} from '../sentry.js'; +import {CompilerVersionInfo, setCompilerVersionPopoverForPane} from '../widgets/compiler-version-info.js'; const toolIcons = require.context('../../views/resources/logos', false, /\.(png|svg)$/); @@ -91,9 +91,7 @@ type CachedOpcode = { }; const OpcodeCache = new LRUCache({ maxSize: 64 * 1024, - sizeCalculation: function (n) { - return JSON.stringify(n).length; - }, + sizeCalculation: n => JSON.stringify(n).length, }); function patchOldFilters(filters) { @@ -308,7 +306,7 @@ export class Compiler extends MonacoPane'), false); + this.onCMakeResponse(request, this.errorResult(``), false); }); } @@ -1460,7 +1457,7 @@ export class Compiler extends MonacoPane'), false); + onCompilerResponse(request, this.errorResult(``), false); }); } @@ -1483,9 +1480,8 @@ export class Compiler extends MonacoPane, filteredCount = 0) { @@ -1514,11 +1510,7 @@ export class Compiler extends MonacoPane 0) { - msg = - ''; + msg = ``; } // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition @@ -1663,7 +1655,7 @@ export class Compiler extends MonacoPane'); @@ -1693,26 +1685,23 @@ export class Compiler extends MonacoPane 0) { - infoLabelText += - ' ~' + result.filteredCount + (result.filteredCount === 1 ? ' line' : ' lines') + ' filtered'; + infoLabelText += ` ~${result.filteredCount}${result.filteredCount === 1 ? ' line' : ' lines'} filtered`; } this.compileInfoLabel.text(infoLabelText); if (result.result) { - const wasCmake = - result.buildsteps && - result.buildsteps.some(step => { - return step.step === 'cmake'; - }); + const wasCmake = result.buildsteps?.some(step => { + return step.step === 'cmake'; + }); this.postCompilationResult(request, result.result, wasCmake); } else { this.postCompilationResult(request, result); @@ -1752,7 +1741,7 @@ export class Compiler extends MonacoPane { - if (result && result.result) { + if (result?.result) { this.handlePopularArgumentsResult(result.result); } }); @@ -1796,27 +1785,16 @@ export class Compiler extends MonacoPanehere' + - ' to view ' + - artifact.title + - ' in Speedscope', + `Click here to view ${artifact.title} in Speedscope`, { group: artifact.type, collapseSimilar: false, dismissTime: 10000, - onBeforeShow: function (elem) { + onBeforeShow: elem => { elem.find('#download_link').on('click', () => { const tmstr = Date.now(); const live_url = 'https://static.ce-cdn.net/speedscope/index.html'; - const speedscope_url = - live_url + - '?' + - tmstr + - '#customFilename=' + - artifact.name + - '&b64data=' + - artifact.content; + const speedscope_url = `${live_url}?${tmstr}#customFilename=${artifact.name}&b64data=${artifact.content}`; window.open(speedscope_url); }); }, @@ -1826,16 +1804,12 @@ export class Compiler extends MonacoPanehere' + - ' to view ' + - artifact.title + - ' in Perfetto', + `Click here to view ${artifact.title} in Perfetto`, { group: artifact.type, collapseSimilar: false, dismissTime: 10000, - onBeforeShow: function (elem) { + onBeforeShow: elem => { elem.find('#download_link').on('click', () => { const perfetto_url = 'https://ui.perfetto.dev'; const win = window.open(perfetto_url); @@ -1874,7 +1848,7 @@ export class Compiler extends MonacoPane { elem.find('#miracle_emulink').on('click', () => { dialog.modal(); @@ -1883,7 +1857,7 @@ export class Compiler extends MonacoPane { elem.find('#emulink').on('click', () => { dialog.modal(); @@ -1965,8 +1937,7 @@ export class Compiler extends MonacoPane { elem.find('#emulink').on('click', () => { const tmstr = Date.now(); - const url = - 'https://static.ce-cdn.net/viciious/viciious.html?' + - tmstr + - '#filename=' + - prg.title + - '&b64c64=' + - prg.content; + const url = `https://static.ce-cdn.net/viciious/viciious.html?${tmstr}#filename=${prg.title}&b64c64=${prg.content}`; window.open(url, '_blank'); }); @@ -2103,7 +2068,7 @@ export class Compiler extends MonacoPane { - if (result && result.result) { + if (result?.result) { this.handlePopularArgumentsResult(result.result); } }); @@ -2591,7 +2556,7 @@ export class Compiler extends MonacoPane 0) { const texts = this.assembly.map(asm => asm.text ?? ''); const blob = new Blob([texts.join('\n')], {type: 'text/plain;charset=utf-8'}); - const fileName = this.getLanguageName() + '-' + this.getCompilerName() + '-' + this.id + '.asm'; + const fileName = `${this.getLanguageName()}-${this.getCompilerName()}-${this.id}.asm`; fileSaver.saveAs(blob, fileName); } } @@ -2636,9 +2601,8 @@ export class Compiler extends MonacoPane { const btn = $("