Another tsification batch. 347 to go and I'm running out of easy fixes
:(
This commit is contained in:
Ofek
2024-10-22 21:41:44 +03:00
committed by GitHub
parent 661957ba7e
commit 2df8d32758
63 changed files with 280 additions and 211 deletions

View File

@@ -95,7 +95,9 @@ function fail(fail_message: string, user_message: string | undefined, args: any[
}
}
export function assert<C>(c: C, message?: string, ...extra_info: any[]): asserts c {
// Using `unknown` instead of generic implementation due to:
// https://github.com/microsoft/TypeScript/issues/60130
export function assert(c: unknown, message?: string, ...extra_info: any[]): asserts c {
if (!c) {
fail('Assertion failed', message, extra_info);
}

View File

@@ -49,6 +49,7 @@ import {
CustomInputForTool,
ExecutionOptions,
ExecutionOptionsWithEnv,
ExecutionParams,
FiledataPair,
GccDumpOptions,
LibsAndOptions,
@@ -977,7 +978,7 @@ export class BaseCompiler implements ICompiler {
);
}
protected getSharedLibraryPathsAsLdLibraryPaths(libraries, dirPath?: string): string[] {
protected getSharedLibraryPathsAsLdLibraryPaths(libraries: CompileChildLibraries[], dirPath?: string): string[] {
let paths = '';
if (!this.alwaysResetLdPath) {
paths = process.env.LD_LIBRARY_PATH || '';
@@ -989,7 +990,7 @@ export class BaseCompiler implements ICompiler {
);
}
getSharedLibraryPathsAsLdLibraryPathsForExecution(libraries, dirPath: string): string[] {
getSharedLibraryPathsAsLdLibraryPathsForExecution(libraries: CompileChildLibraries[], dirPath: string): string[] {
let paths = '';
if (!this.alwaysResetLdPath) {
paths = process.env.LD_LIBRARY_PATH || '';
@@ -2001,7 +2002,7 @@ export class BaseCompiler implements ICompiler {
executeParameters: ExecutableExecutionOptions,
outputFilename: string,
) {
executeParameters.args.unshift(outputFilename);
(executeParameters.args as string[]).unshift(outputFilename);
}
async handleInterpreting(key: CacheKey, executeParameters: ExecutableExecutionOptions): Promise<CompilationResult> {
@@ -2239,7 +2240,7 @@ export class BaseCompiler implements ICompiler {
async doCompilation(
inputFilename: string,
dirPath: string,
key,
key: CacheKey,
options: string[],
filters: ParseFiltersAndOutputOptions,
backendOptions: Record<string, any>,
@@ -2338,7 +2339,7 @@ export class BaseCompiler implements ICompiler {
? await this.processGccDumpOutput(
backendOptions.produceGccDump,
asmResult,
this.compiler.removeEmptyGccDump,
!!this.compiler.removeEmptyGccDump,
outputFilename,
)
: '';
@@ -2434,7 +2435,7 @@ export class BaseCompiler implements ICompiler {
return this.processExecutionResult(result);
}
handleUserError(error, dirPath: string): CompilationResult {
handleUserError(error: any, dirPath: string): CompilationResult {
return {
dirPath,
okToCache: false,
@@ -2758,7 +2759,7 @@ export class BaseCompiler implements ICompiler {
filters: ParseFiltersAndOutputOptions,
bypassCache: BypassCache,
tools,
executeParameters,
executeParameters: ExecutionParams,
libraries: CompileChildLibraries[],
files: FiledataPair[],
) {
@@ -2886,13 +2887,13 @@ export class BaseCompiler implements ICompiler {
key: CacheKey,
executeOptions: ExecutableExecutionOptions,
tools,
backendOptions,
filters,
backendOptions: Record<string, any>,
filters: ParseFiltersAndOutputOptions,
options: string[],
optOutput,
stackUsageOutput,
bypassCache: BypassCache,
customBuildPath?,
customBuildPath?: string,
) {
// Start the execution as soon as we can, but only await it at the end.
const execPromise =
@@ -2996,7 +2997,7 @@ export class BaseCompiler implements ICompiler {
return result;
}
async processAsm(result, filters, options) {
async processAsm(result, filters: ParseFiltersAndOutputOptions, options: string[]) {
if ((options && options.includes('-emit-llvm')) || this.llvmIr.isLlvmIr(result.asm)) {
return await this.llvmIr.processFromFilters(result.asm, filters);
}
@@ -3024,7 +3025,7 @@ export class BaseCompiler implements ICompiler {
);
if (demangleResult.stdout.length > 0 && !demangleResult.truncated) {
try {
return JSON.parse(demangleResult.stdout);
return JSON.parse(demangleResult.stdout) as LLVMOptInfo[];
} catch (exception) {
// swallow exception and return non-demangled output
logger.warn(`Caught exception ${exception} during opt demangle parsing`);
@@ -3077,7 +3078,7 @@ export class BaseCompiler implements ICompiler {
);
}
async processGccDumpOutput(opts: GccDumpOptions, result, removeEmptyPasses, outputFilename) {
async processGccDumpOutput(opts: GccDumpOptions, result, removeEmptyPasses: boolean, outputFilename: string) {
const rootDir = path.dirname(result.inputFilename);
if (opts.treeDump === false && opts.rtlDump === false && opts.ipaDump === false) {
@@ -3189,11 +3190,11 @@ but nothing was dumped. Possible causes are:
}
// eslint-disable-next-line no-unused-vars
async extractDeviceCode(result: CompilationResult, filters, compilationInfo) {
async extractDeviceCode(result: CompilationResult, filters, compilationInfo: CompilationInfo) {
return result;
}
async execPostProcess(result, postProcesses, outputFilename, maxSize) {
async execPostProcess(result, postProcesses, outputFilename: string, maxSize: number) {
const postCommand = `cat "${outputFilename}" | ${postProcesses.join(' | ')}`;
return this.handlePostProcessResult(result, await this.exec('bash', ['-c', postCommand], {maxOutput: maxSize}));
}
@@ -3208,7 +3209,7 @@ but nothing was dumped. Possible causes are:
async postProcess(result, outputFilename: string, filters: ParseFiltersAndOutputOptions) {
const postProcess = _.compact(this.compiler.postProcess);
const maxSize = this.env.ceProps('max-asm-size', 64 * 1024 * 1024);
const optPromise = result.optPath ? this.processOptOutput(unwrap(result.optPath)) : '';
const optPromise = result.optPath ? this.processOptOutput(unwrap(result.optPath)) : ([] as LLVMOptInfo[]);
const stackUsagePromise = result.stackUsagePath ? this.processStackUsageOutput(result.stackUsagePath) : '';
const asmPromise =
(filters.binary || filters.binaryObject) && this.supportsObjdump()
@@ -3470,9 +3471,11 @@ but nothing was dumped. Possible causes are:
this.mtime = mtime;
if (this.buildenvsetup) {
await this.buildenvsetup.initialise(async (compiler, args, options) => {
return this.execCompilerCached(compiler, args, options);
});
await this.buildenvsetup.initialise(
async (compiler: string, args: string[], options: ExecutionOptionsWithEnv) => {
return this.execCompilerCached(compiler, args, options);
},
);
}
if (this.getRemote()) return this;

View File

@@ -26,8 +26,9 @@ import path from 'path';
import _ from 'underscore';
import {CacheKey} from '../../types/compilation/compilation.interfaces.js';
import {CacheKey, ExecutionOptionsWithEnv} from '../../types/compilation/compilation.interfaces.js';
import {CompilerInfo} from '../../types/compiler.interfaces.js';
import {UnprocessedExecResult} from '../../types/execution/execution.interfaces.js';
import {CompilationEnvironment} from '../compilation-env.js';
import {logger} from '../logger.js';
import {VersionInfo} from '../options-handler.js';
@@ -35,6 +36,12 @@ import * as utils from '../utils.js';
import type {BuildEnvDownloadInfo} from './buildenv.interfaces.js';
export type ExecCompilerCachedFunc = (
compiler: string,
args: string[],
options?: ExecutionOptionsWithEnv,
) => Promise<UnprocessedExecResult>;
export class BuildEnvSetupBase {
protected compiler: any;
protected env: any;
@@ -56,7 +63,7 @@ export class BuildEnvSetupBase {
this.defaultLibCxx = 'libstdc++';
}
async initialise(execCompilerCachedFunc) {
async initialise(execCompilerCachedFunc: ExecCompilerCachedFunc) {
if (this.compilerArch) return;
await this.hasSupportForArch(execCompilerCachedFunc, 'x86')
.then(res => (this.compilerSupportsX86 = res))
@@ -66,7 +73,7 @@ export class BuildEnvSetupBase {
});
}
async hasSupportForArch(execCompilerCached, arch) {
async hasSupportForArch(execCompilerCached: ExecCompilerCachedFunc, arch: string): Promise<boolean> {
let result: any;
let searchFor = arch;
if (this.compiler.exe.includes('icpx')) {

View File

@@ -22,6 +22,10 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import {CacheKey} from '../../types/compilation/compilation.interfaces.js';
import {CompilerInfo} from '../../types/compiler.interfaces.js';
import {CompilationEnvironment} from '../compilation-env.js';
import {BuildEnvSetupCeConanDirect, ConanBuildProperties} from './ceconan.js';
export class BuildEnvSetupCeConanCircleDirect extends BuildEnvSetupCeConanDirect {
@@ -32,14 +36,14 @@ export class BuildEnvSetupCeConanCircleDirect extends BuildEnvSetupCeConanDirect
return 'ceconan-circle';
}
constructor(compilerInfo, env) {
constructor(compilerInfo: CompilerInfo, env: CompilationEnvironment) {
super(compilerInfo, env);
this.linkedCompilerId = compilerInfo.buildenvsetup.props('linkedCompilerId');
this.linkedCompilerType = compilerInfo.buildenvsetup.props('linkedCompilerType');
this.linkedCompilerId = compilerInfo.buildenvsetup!.props('linkedCompilerId');
this.linkedCompilerType = compilerInfo.buildenvsetup!.props('linkedCompilerType');
}
override async getConanBuildProperties(key): Promise<ConanBuildProperties> {
override async getConanBuildProperties(key: CacheKey): Promise<ConanBuildProperties> {
const props = await super.getConanBuildProperties(key);
props['compiler'] = this.linkedCompilerType;
props['compiler.version'] = this.linkedCompilerId;

View File

@@ -26,6 +26,12 @@ import path from 'path';
import _ from 'underscore';
import {CacheKey} from '../../types/compilation/compilation.interfaces.js';
import {CompilerInfo} from '../../types/compiler.interfaces.js';
import {CompilationEnvironment} from '../compilation-env.js';
import {VersionInfo} from '../options-handler.js';
import {ExecCompilerCachedFunc} from './base.js';
import {BuildEnvSetupCeConanDirect} from './ceconan.js';
export class BuildEnvSetupCeConanRustDirect extends BuildEnvSetupCeConanDirect {
@@ -33,19 +39,19 @@ export class BuildEnvSetupCeConanRustDirect extends BuildEnvSetupCeConanDirect {
return 'ceconan-rust';
}
constructor(compilerInfo, env) {
constructor(compilerInfo: CompilerInfo, env: CompilationEnvironment) {
super(compilerInfo, env);
this.onlyonstaticliblink = false;
this.extractAllToRoot = false;
}
override async initialise(execCompilerCachedFunc) {
override async initialise(execCompilerCachedFunc: ExecCompilerCachedFunc) {
if (this.compilerArch) return;
this.compilerSupportsX86 = true;
}
override getLibcxx(key) {
override getLibcxx(key: CacheKey) {
return '';
}
@@ -54,7 +60,7 @@ export class BuildEnvSetupCeConanRustDirect extends BuildEnvSetupCeConanDirect {
return path.join(downloadPath, zippedPath);
}
getArchFromTriple(triple) {
getArchFromTriple(triple: string) {
if (triple && triple.split) {
const arr = triple.split('-');
if (arr && arr[0]) {
@@ -67,7 +73,7 @@ export class BuildEnvSetupCeConanRustDirect extends BuildEnvSetupCeConanDirect {
}
}
override getTarget(key) {
override getTarget(key: CacheKey) {
if (!this.compilerSupportsX86) return '';
if (this.compilerArch) return this.compilerArch;
@@ -89,11 +95,11 @@ export class BuildEnvSetupCeConanRustDirect extends BuildEnvSetupCeConanDirect {
return 'x86_64';
}
override hasBinariesToLink(details) {
override hasBinariesToLink(details: VersionInfo) {
return true;
}
override shouldDownloadPackage(details) {
override shouldDownloadPackage(details: VersionInfo) {
return true;
}
}

View File

@@ -50,6 +50,14 @@ export type ConanBuildProperties = {
flagcollection: string;
};
type LibVerBuild = {
id: string;
version: string;
lookupname: string;
lookupversion: string;
possibleBuilds: any;
};
export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase {
protected host: any;
protected onlyonstaticliblink: any;
@@ -69,7 +77,7 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase {
if (env.debug) request.debug = true;
}
async getAllPossibleBuilds(libid, version) {
async getAllPossibleBuilds(libid: string, version: string) {
return new Promise((resolve, reject) => {
const encLibid = encodeURIComponent(libid);
const encVersion = encodeURIComponent(version);
@@ -104,7 +112,7 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase {
json: true,
};
request(url, settings, (err, res, body) => {
request(url, settings, (err, res: request.Response, body) => {
if (err) {
reject(err);
return;
@@ -158,7 +166,7 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase {
next();
} else {
stream
.on('error', error => {
.on('error', (error: any) => {
logger.error(`Error in stream handling: ${error}`);
reject(error);
})
@@ -173,7 +181,7 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase {
});
extract
.on('error', error => {
.on('error', (error: any) => {
logger.error(`Error in tar handling: ${error}`);
reject(error);
})
@@ -200,11 +208,11 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase {
// https://stackoverflow.com/questions/49277790/how-to-pipe-npm-request-only-if-http-200-is-received
const req = request(packageUrl, settings)
.on('error', error => {
.on('error', (error: any) => {
logger.error(`Error in request handling: ${error}`);
reject(error);
})
.on('response', res => {
.on('response', (res: request.Response) => {
if (res.statusCode === 200) {
req.pipe(gunzip);
} else {
@@ -253,7 +261,7 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase {
libraryDetails: Record<string, VersionInfo>,
): Promise<BuildEnvDownloadInfo[]> {
const allDownloads: Promise<BuildEnvDownloadInfo>[] = [];
const allLibraryBuilds: any = [];
const allLibraryBuilds: LibVerBuild[] = [];
_.each(libraryDetails, (details: VersionInfo, libId: string) => {
if (details.packagedheaders || this.hasBinariesToLink(details)) {
@@ -262,9 +270,11 @@ export class BuildEnvSetupCeConanDirect extends BuildEnvSetupBase {
allLibraryBuilds.push({
id: libId,
version: details.version,
lookupname: details.lookupname,
lookupversion: details.lookupversion,
possibleBuilds: this.getAllPossibleBuilds(lookupname, lookupversion).catch(() => false),
lookupname: details.lookupname as string,
lookupversion: details.lookupversion as string,
possibleBuilds: this.getAllPossibleBuilds(lookupname as string, lookupversion as string).catch(
() => false,
),
});
}
});

View File

@@ -116,12 +116,12 @@ export class OatCFGParser extends BaseCFGParser {
return inst.trim().split(/\s+/)[1].toLowerCase();
}
isJmpTarget(inst, jmpAddrs) {
isJmpTarget(inst: string, jmpAddrs: string[]) {
return jmpAddrs.includes(this.shortenHex(this.getPc(inst)));
}
// '0x00004168' -> '0x4168'
shortenHex(pc) {
shortenHex(pc: string) {
const match = pc.match(this.hexRegex);
if (match) return '0x' + match[1];
return pc;

View File

@@ -36,6 +36,7 @@ import {basic_comparator, remove} from '../shared/common-utils.js';
import type {CompilerInfo, PreliminaryCompilerInfo} from '../types/compiler.interfaces.js';
import {InstructionSet, InstructionSetsList} from '../types/instructionsets.js';
import type {Language, LanguageKey} from '../types/languages.interfaces.js';
import {Tool, ToolInfo} from '../types/tool.interfaces.js';
import {assert, unwrap, unwrapString} from './assert.js';
import {InstanceFetcher} from './aws.js';
@@ -385,7 +386,7 @@ export class CompilerFinder {
if (compilerName.indexOf('&') === 0) {
const groupName = compilerName.substring(1);
const props: CompilerProps['get'] = (langId, name, def?): any => {
const props: CompilerProps['get'] = (langId, name: string, def?): any => {
if (name === 'group') {
return groupName;
}
@@ -462,7 +463,7 @@ export class CompilerFinder {
return langToCompilers;
}
addNdkExes(langToCompilers) {
addNdkExes(langToCompilers: Record<LanguageKey, string[]>) {
const ndkPaths = this.compilerProps(this.languages, 'androidNdk') as unknown as Record<string, string>;
for (const [langId, ndkPath] of Object.entries(ndkPaths)) {
if (ndkPath) {
@@ -471,7 +472,7 @@ export class CompilerFinder {
const path = `${ndkPath}/toolchains/${version}/prebuilt/linux-x86_64/bin`;
for (const exe of fs.readdirSync(path)) {
if (exe.endsWith('clang++') || exe.endsWith('g++')) {
langToCompilers[langId].push(`${path}/${exe}`);
langToCompilers[langId as LanguageKey].push(`${path}/${exe}`);
}
}
}
@@ -602,7 +603,7 @@ export class CompilerFinder {
}
if (compiler.externalparser) {
compiler.externalparser.props = (propName, def) => {
compiler.externalparser.props = (propName: string, def: any) => {
return this.compilerProps(langId, 'externalparser.' + propName, def);
};
}
@@ -610,7 +611,7 @@ export class CompilerFinder {
if (!compiler.remote && compiler.tools) {
const fullOptions = this.optionsHandler.get();
const toolinstances = {};
const toolinstances: Record<ToolInfo['id'], Tool> = {};
for (const toolId in compiler.tools) {
if (fullOptions.tools[langId][toolId]) {
toolinstances[toolId] = fullOptions.tools[langId][toolId];

View File

@@ -47,7 +47,11 @@ export class CarbonCompiler extends BaseCompiler {
return ['--color', `--trace_file=${outputFilename}`];
}
override async processAsm(result, filters, options): Promise<ParsedAsmResult> {
override async processAsm(
result,
filters: ParseFiltersAndOutputOptions,
options: string[],
): Promise<ParsedAsmResult> {
// Really should write a custom parser, but for now just don't filter anything.
return await super.processAsm(
result,

View File

@@ -31,6 +31,7 @@ import type {
BuildResult,
BypassCache,
CacheKey,
CompilationInfo,
CompilationResult,
ExecutionOptionsWithEnv,
} from '../../types/compilation/compilation.interfaces.js';
@@ -41,6 +42,7 @@ import {ArtifactType} from '../../types/tool.interfaces.js';
import {addArtifactToResult} from '../artifact-utils.js';
import {BaseCompiler} from '../base-compiler.js';
import {CompilationEnvironment} from '../compilation-env.js';
import {LLVMOptInfo} from '../llvm-opt-transformer.js';
import {AmdgpuAsmParser} from '../parsers/asm-parser-amdgpu.js';
import {HexagonAsmParser} from '../parsers/asm-parser-hexagon.js';
import {SassAsmParser} from '../parsers/asm-parser-sass.js';
@@ -116,7 +118,7 @@ export class ClangCompiler extends BaseCompiler {
}
}
override async afterBuild(key, dirPath: string, buildResult: BuildResult): Promise<BuildResult> {
override async afterBuild(key: CacheKey, dirPath: string, buildResult: BuildResult): Promise<BuildResult> {
const compilationInfo = this.getCompilationInfo(key, buildResult, dirPath);
const filename = path.basename(compilationInfo.outputFilename);
@@ -190,13 +192,13 @@ export class ClangCompiler extends BaseCompiler {
key: CacheKey,
executeParameters: ExecutableExecutionOptions,
tools,
backendOptions,
filters,
backendOptions: Record<string, any>,
filters: ParseFiltersAndOutputOptions,
options: string[],
optOutput,
optOutput: LLVMOptInfo[] | undefined,
stackUsageOutput,
bypassCache: BypassCache,
customBuildPath?,
customBuildPath?: string,
) {
const compilationInfo = this.getCompilationInfo(key, result, customBuildPath);
@@ -235,14 +237,14 @@ export class ClangCompiler extends BaseCompiler {
return await super.runCompiler(compiler, options, inputFilename, execOptions);
}
async splitDeviceCode(assembly) {
async splitDeviceCode(assembly: string) {
// Check to see if there is any offload code in the assembly file.
if (!offloadRegexp.test(assembly)) return null;
offloadRegexp.lastIndex = 0;
const matches = assembly.matchAll(offloadRegexp);
let prevStart = 0;
const devices = {};
const devices: Record<string, string> = {};
for (const match of matches) {
const [full, startOrEnd, triple] = match;
if (startOrEnd === '__START__') {
@@ -254,19 +256,19 @@ export class ClangCompiler extends BaseCompiler {
return devices;
}
override async extractDeviceCode(result: CompilationResult, filters, compilationInfo) {
override async extractDeviceCode(result, filters, compilationInfo: CompilationInfo) {
const split = await this.splitDeviceCode(result.asm);
if (!split) return result;
const devices = (result.devices = {});
result.devices = {};
for (const key of Object.keys(split)) {
if (key.indexOf('host-') === 0) result.asm = split[key];
else devices[key] = await this.processDeviceAssembly(key, split[key], filters, compilationInfo);
else result.devices[key] = await this.processDeviceAssembly(key, split[key], filters, compilationInfo);
}
return result;
}
async extractBitcodeFromBundle(bundlefile, devicename): Promise<string> {
async extractBitcodeFromBundle(bundlefile: string, devicename: string): Promise<string> {
const bcfile = path.join(path.dirname(bundlefile), devicename + '.bc');
const env = this.getDefaultExecOptions();
@@ -299,7 +301,7 @@ export class ClangCompiler extends BaseCompiler {
}
}
async processDeviceAssembly(deviceName, deviceAsm, filters, compilationInfo) {
async processDeviceAssembly(deviceName: string, deviceAsm: string, filters, compilationInfo: CompilationInfo) {
if (deviceAsm.startsWith('BC')) {
deviceAsm = await this.extractBitcodeFromBundle(compilationInfo.outputFilename, deviceName);
}
@@ -329,7 +331,7 @@ export class ClangCudaCompiler extends ClangCompiler {
return ['-o', this.filename(outputFilename), '-g1', filters.binary ? '-c' : '-S'];
}
override async objdump(outputFilename: string, result, maxSize) {
override async objdump(outputFilename: string, result, maxSize: number) {
// For nvdisasm.
const args = [...this.compiler.objdumperArgs, outputFilename, '-c', '-g', '-hex'];
const execOptions = {maxOutput: maxSize, customCwd: path.dirname(outputFilename)};

View File

@@ -46,6 +46,6 @@ export class CMakeScriptCompiler extends BaseCompiler {
executeParameters: ExecutableExecutionOptions,
outputFilename: string,
) {
executeParameters.args.push('-P', outputFilename);
(executeParameters.args as string[]).push('-P', outputFilename);
}
}

View File

@@ -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 = match[2];
versionPrefix = parseInt(match![2]);
} else if (this.latestVersionRegex.test(this.compiler.id)) {
isLatest = true;
}

View File

@@ -24,8 +24,14 @@
import _ from 'underscore';
import {BypassCache} from '../../types/compilation/compilation.interfaces.js';
import type {ICompiler} from '../../types/compiler.interfaces.js';
import {
BypassCache,
CompileChildLibraries,
ExecutionParams,
FiledataPair,
} from '../../types/compilation/compilation.interfaces.js';
import type {ICompiler, PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js';
import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js';
import {CompilerArguments} from '../compiler-arguments.js';
export class FakeCompiler implements ICompiler {
@@ -38,7 +44,7 @@ export class FakeCompiler implements ICompiler {
return 'fake-for-test';
}
constructor(info) {
constructor(info: Partial<PreliminaryCompilerInfo>) {
this.compiler = Object.assign(
{
id: 'fake-for-test',
@@ -54,7 +60,7 @@ export class FakeCompiler implements ICompiler {
initialise(mtime: Date, clientOptions: any, isPrediscovered: boolean) {
throw new Error('Method not implemented.');
return null;
return Promise.resolve(null);
}
getInfo() {
@@ -74,15 +80,15 @@ export class FakeCompiler implements ICompiler {
}
compile(
source,
options,
backendOptions,
filters,
source: string,
options: string[],
backendOptions: Record<string, any>,
filters: ParseFiltersAndOutputOptions,
bypassCache: BypassCache,
tools,
executeParameters,
libraries,
files,
executeParameters: ExecutionParams,
libraries: CompileChildLibraries[],
files?: FiledataPair[],
) {
const inputBody = {
input: {
@@ -90,16 +96,14 @@ export class FakeCompiler implements ICompiler {
options: options,
backendOptions: backendOptions,
filters: filters,
files: undefined,
files: files,
},
};
if (files) inputBody.input.files = files;
return Promise.resolve(_.extend(this.info.fakeResult || {}, inputBody));
}
cmake(files, options) {
cmake(files: FiledataPair[], options: string[]) {
return Promise.resolve(
_.extend(this.info.fakeResult || {}, {
input: {

View File

@@ -228,7 +228,7 @@ export class GolangCompiler extends BaseCompiler {
result.asm = this.convertNewGoL(out);
result.stderr = [];
result.stdout = utils.parseOutput(logging, result.inputFilename);
return Promise.all([result, '', '']);
return Promise.all([result, [], '']);
}
override getSharedLibraryPathsAsArguments() {

View File

@@ -95,7 +95,7 @@ export class HLSLCompiler extends BaseCompiler {
return options;
}
override async processAsm(result, filters, options) {
override async processAsm(result, filters: ParseFiltersAndOutputOptions, options: string[]) {
if (this.isSpirv(result.asm)) {
return this.spirvAsm.processAsm(result.asm, filters);
}

View File

@@ -79,7 +79,7 @@ export class HookCompiler extends BaseCompiler {
return super.runCompiler(compiler, options, inputFilename, execOptions);
}
override async processAsm(result, filters, options) {
override async processAsm(result, filters: ParseFiltersAndOutputOptions, options: string[]) {
// Ignoring `trim` filter because it is not supported by Hook.
filters.trim = false;
const _result = await super.processAsm(result, filters, options);

View File

@@ -75,7 +75,7 @@ export class JuliaCompiler extends BaseCompiler {
outputFilename: string,
) {
super.fixExecuteParametersForInterpreting(executeParameters, outputFilename);
executeParameters.args.unshift('--');
(executeParameters.args as string[]).unshift('--');
}
override async runCompiler(

View File

@@ -81,7 +81,7 @@ export class MLIRCompiler extends BaseCompiler {
return [];
}
override async processAsm(result, filters, options) {
override async processAsm(result, filters: ParseFiltersAndOutputOptions, options: string[]) {
// at some point maybe a custom parser can be written, for now just don't filter anything
return super.processAsm(
result,

View File

@@ -103,7 +103,7 @@ export class NvccCompiler extends BaseCompiler {
override async postProcess(result, outputFilename: string, filters: ParseFiltersAndOutputOptions) {
const maxSize = this.env.ceProps('max-asm-size', 64 * 1024 * 1024);
const optPromise = result.optPath ? this.processOptOutput(result.optPath) : Promise.resolve('');
const optPromise = result.optPath ? this.processOptOutput(result.optPath) : Promise.resolve([]);
const postProcess = _.compact(this.compiler.postProcess);
const asmPromise = (
filters.binary

View File

@@ -193,7 +193,7 @@ export class PascalWinCompiler extends BaseCompiler {
override optionsForFilter(filters: ParseFiltersAndOutputOptions) {
filters.binary = true;
filters.dontMaskFilenames = true;
(filters as any).preProcessBinaryAsmLines = (asmLines: string[]) => {
filters.preProcessBinaryAsmLines = (asmLines: string[]) => {
const mapFileReader = new MapFileReaderDelphi(unwrap(this.mapFilename));
const reconstructor = new PELabelReconstructor(asmLines, false, mapFileReader, false);
reconstructor.run('output');

View File

@@ -63,7 +63,7 @@ export class FPCCompiler extends BaseCompiler {
return [];
}
override async processAsm(result, filters) {
override async processAsm(result, filters: ParseFiltersAndOutputOptions) {
// TODO: Pascal doesn't have a demangler exe, it's the only compiler that's weird like this
this.demangler = new (unwrap(this.demanglerClass))(null as any, this);
return this.asm.process(result.asm, filters);

View File

@@ -175,7 +175,7 @@ export class RacketCompiler extends BaseCompiler {
return result;
}
override async processAsm(result: any, filters: any, options: any) {
override async processAsm(result: any, filters: ParseFiltersAndOutputOptions, options: string[]) {
// TODO: Process and highlight decompiled output
return {
asm: [{text: result.asm}],

View File

@@ -44,7 +44,7 @@ export class TinyCCompiler extends BaseCompiler {
}
}
override filterUserOptions(userOptions) {
override filterUserOptions(userOptions: string[]) {
return userOptions.filter(opt => opt !== '-run');
}
}

View File

@@ -26,7 +26,7 @@ import path from 'path';
import Semver from 'semver';
import {CacheKey} from '../../types/compilation/compilation.interfaces.js';
import {CacheKey, CompilationResult} from '../../types/compilation/compilation.interfaces.js';
import {LLVMIrBackendOptions} from '../../types/compilation/ir.interfaces.js';
import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js';
import {ExecutableExecutionOptions} from '../../types/execution/execution.interfaces.js';
@@ -112,7 +112,11 @@ export class TypeScriptNativeCompiler extends BaseCompiler {
return await super.generateIR(inputFilename, newOptions, irOptions, produceCfg, filters);
}
override async processIrOutput(output, irOptions: LLVMIrBackendOptions, filters: ParseFiltersAndOutputOptions) {
override async processIrOutput(
output: CompilationResult,
irOptions: LLVMIrBackendOptions,
filters: ParseFiltersAndOutputOptions,
) {
if (this.tscNewOutput) {
return await super.processIrOutput(output, irOptions, filters);
}

View File

@@ -68,7 +68,7 @@ export class VCompiler extends BaseCompiler {
return compilerOptions;
}
override async processAsm(result: any, filters, options: string[]): Promise<any> {
override async processAsm(result: any, filters: ParseFiltersAndOutputOptions, options: string[]): Promise<any> {
const backend = this.getBackendFromOptions(options);
switch (backend) {
case 'c':

View File

@@ -26,7 +26,11 @@ import path from 'path';
import _ from 'underscore';
import type {CompileChildLibraries, ExecutionOptions} from '../../types/compilation/compilation.interfaces.js';
import type {
CacheKey,
CompileChildLibraries,
ExecutionOptions,
} from '../../types/compilation/compilation.interfaces.js';
import type {ConfiguredOverrides} from '../../types/compilation/compiler-overrides.interfaces.js';
import type {PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js';
import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js';
@@ -55,7 +59,7 @@ export class Win32Compiler extends BaseCompiler {
return ['/std:<value>'];
}
override getExecutableFilename(dirPath: string, outputFilebase: string, key?) {
override getExecutableFilename(dirPath: string, outputFilebase: string, key?: CacheKey) {
return this.getOutputFilename(dirPath, outputFilebase, key) + '.exe';
}
@@ -81,7 +85,7 @@ export class Win32Compiler extends BaseCompiler {
);
}
override getStaticLibraryLinks(libraries) {
override getStaticLibraryLinks(libraries: CompileChildLibraries[]) {
return super.getSortedStaticLibraries(libraries).map(lib => {
return '"' + lib + '.lib"';
});
@@ -142,7 +146,7 @@ export class Win32Compiler extends BaseCompiler {
const mapFilename = outputFilename + '.map';
const mapFileReader = new MapFileReaderVS(mapFilename);
(filters as any).preProcessBinaryAsmLines = asmLines => {
filters.preProcessBinaryAsmLines = asmLines => {
const reconstructor = new PELabelReconstructor(asmLines, false, mapFileReader);
reconstructor.run('output.s.obj');
@@ -168,7 +172,7 @@ export class Win32Compiler extends BaseCompiler {
}
}
override async processAsm(result, filters /*, options*/) {
override async processAsm(result, filters: ParseFiltersAndOutputOptions) {
if (filters.binary) {
filters.dontMaskFilenames = true;
return this.binaryAsmParser.process(result.asm, filters);

View File

@@ -37,7 +37,7 @@ export class LLVMWin32Demangler extends Win32Demangler {
const translations: Record<string, string> = {};
const flags = ['--no-access-specifier', '--no-calling-convention'];
const demangleFromStdin = async stdin => {
const demangleFromStdin = async (stdin: string) => {
const args = [...flags];
const execOptions = this.compiler.getDefaultExecOptions();
execOptions.input = stdin;

View File

@@ -129,7 +129,7 @@ export function executeDirect(
streams.stderr += '\nKilled - processing time exceeded\n';
}, timeoutMs);
function setupStream(stream: Stream, name: string) {
function setupStream(stream: Stream, name: 'stdout' | 'stderr') {
if (stream === undefined) return;
stream.on('data', data => {
if (streams.truncated) return;
@@ -407,7 +407,7 @@ export async function sandbox(
): Promise<UnprocessedExecResult> {
checkExecOptions(options);
const type = execProps('sandboxType', 'firejail');
const dispatchEntry = sandboxDispatchTable[type];
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`);
return await dispatchEntry(command, args, options);

View File

@@ -231,7 +231,7 @@ export class LocalExecutionEnvironment implements IExecutionEnvironment {
return this.execBinaryMaybeWrapped(
executable,
executeParameters.args,
executeParameters.args as string[],
execOptions,
executeParameters,
homeDir,

View File

@@ -2,8 +2,10 @@ import fs from 'fs';
import path from 'path';
import type {ParsedAsmResult} from '../../types/asmresult/asmresult.interfaces.js';
import {CompilerInfo} from '../../types/compiler.interfaces.js';
import type {TypicalExecutionFunc, UnprocessedExecResult} from '../../types/execution/execution.interfaces.js';
import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js';
import {CompilationEnvironment} from '../compilation-env.js';
import {logger} from '../logger.js';
import {maskRootdir} from '../utils.js';
@@ -15,10 +17,10 @@ export class ExternalParserBase implements IExternalParser {
private readonly objdumperPath: string;
private readonly parserPath: string;
private readonly execFunc: TypicalExecutionFunc;
private compilerInfo;
private compilerInfo: CompilerInfo;
private envInfo;
constructor(compilerInfo, envInfo, execFunc: TypicalExecutionFunc) {
constructor(compilerInfo: CompilerInfo, envInfo: CompilationEnvironment, execFunc: TypicalExecutionFunc) {
this.compilerInfo = compilerInfo;
this.envInfo = envInfo;
this.objdumperPath = compilerInfo.objdumper;

View File

@@ -43,7 +43,7 @@ import {
FiledataPair,
} from '../../types/compilation/compilation.interfaces.js';
import {CompilerOverrideOptions} from '../../types/compilation/compiler-overrides.interfaces.js';
import {CompilerInfo, ICompiler, PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js';
import {CompilerInfo, PreliminaryCompilerInfo} from '../../types/compiler.interfaces.js';
import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js';
import {LanguageKey} from '../../types/languages.interfaces.js';
import {ResultLine} from '../../types/resultline/resultline.interfaces.js';
@@ -216,7 +216,7 @@ export class CompileHandler implements ICompileHandler {
}
}
async create(compiler: PreliminaryCompilerInfo): Promise<ICompiler | null> {
async create(compiler: PreliminaryCompilerInfo): Promise<BaseCompiler | null> {
const isPrediscovered = !!compiler.version;
const type = compiler.compilerType || 'default';
@@ -265,7 +265,7 @@ export class CompileHandler implements ICompileHandler {
return null;
}
} else {
return new compilerClass(compiler, this.compilerEnv);
return new compilerClass(compiler, this.compilerEnv) as BaseCompiler;
}
}
@@ -274,7 +274,7 @@ export class CompileHandler implements ICompileHandler {
clientOptions: ClientOptionsType,
): Promise<CompilerInfo[]> {
// Be careful not to update this.compilersById until we can replace it entirely.
const compilersById = {};
const compilersById: Partial<Record<LanguageKey, Record<string, BaseCompiler>>> = {};
try {
this.clientOptions = clientOptions;
logger.info('Creating compilers: ' + compilers.length);
@@ -313,7 +313,7 @@ export class CompileHandler implements ICompileHandler {
return compiler.compiler.id === compilerId || this.compilerAliasMatch(compiler, compilerId);
}
findCompiler(langId: string, compilerId: string): BaseCompiler | undefined {
findCompiler(langId: LanguageKey, compilerId: string): BaseCompiler | undefined {
if (!compilerId) return;
const langCompilers: Record<string, BaseCompiler> | undefined = this.compilersById[langId];
@@ -321,7 +321,7 @@ export class CompileHandler implements ICompileHandler {
if (langCompilers[compilerId]) {
return langCompilers[compilerId];
} else {
const compiler = _.find(langCompilers, compiler => {
const compiler = _.find(langCompilers, (compiler: BaseCompiler) => {
return this.compilerAliasMatch(compiler, compilerId);
});
@@ -331,9 +331,9 @@ export class CompileHandler implements ICompileHandler {
// If the lang is bad, try to find it in every language
let response: BaseCompiler | undefined;
_.each(this.compilersById, compilerInLang => {
_.each(this.compilersById, (compilerInLang: Record<string, BaseCompiler>) => {
if (!response) {
response = _.find(compilerInLang, compiler => {
response = _.find(compilerInLang, (compiler: BaseCompiler) => {
return this.compilerIdOrAliasMatch(compiler, compilerId);
});
}
@@ -467,7 +467,7 @@ export class CompileHandler implements ICompileHandler {
};
}
handlePopularArguments(req: express.Request, res) {
handlePopularArguments(req: express.Request, res: express.Response) {
const compiler = this.compilerFor(req);
if (!compiler) {
return res.sendStatus(404);
@@ -475,7 +475,7 @@ export class CompileHandler implements ICompileHandler {
res.send(compiler.possibleArguments.getPopularArguments(this.getUsedOptions(req)));
}
handleOptimizationArguments(req: express.Request, res) {
handleOptimizationArguments(req: express.Request, res: express.Response) {
const compiler = this.compilerFor(req);
if (!compiler) {
return res.sendStatus(404);
@@ -496,7 +496,7 @@ export class CompileHandler implements ICompileHandler {
return false;
}
handleApiError(error, res: express.Response, next: express.NextFunction) {
handleApiError(error: any, res: express.Response, next: express.NextFunction) {
if (error.message) {
return res.status(400).send({
error: true,
@@ -516,7 +516,7 @@ export class CompileHandler implements ICompileHandler {
const remote = compiler.getRemote();
if (remote) {
req.url = remote.cmakePath;
this.proxy.web(req, res, {target: remote.target, changeOrigin: true}, e => {
this.proxy.web(req, res, {target: remote.target, changeOrigin: true}, (e: any) => {
logger.error('Proxy error: ', e);
next(e);
});
@@ -560,7 +560,7 @@ export class CompileHandler implements ICompileHandler {
const remote = compiler.getRemote();
if (remote) {
req.url = remote.path;
this.proxy.web(req, res, {target: remote.target, changeOrigin: true}, e => {
this.proxy.web(req, res, {target: remote.target, changeOrigin: true}, (e: any) => {
logger.error('Proxy error: ', e);
next(e);
});

View File

@@ -26,6 +26,7 @@ import bodyParser from 'body-parser';
import express from 'express';
import {isString} from '../../shared/common-utils.js';
import {LanguageKey} from '../../types/languages.interfaces.js';
import {assert} from '../assert.js';
import {ClientStateNormalizer} from '../clientstate-normalizer.js';
import {ClientState} from '../clientstate.js';
@@ -133,7 +134,7 @@ export class NoScriptHandler {
});
}
createDefaultState(wantedLanguage: string) {
createDefaultState(wantedLanguage: LanguageKey) {
const options = this.clientOptionsHandler.get();
const state = new ClientState();
@@ -172,7 +173,7 @@ export class NoScriptHandler {
}
if (!state) {
state = this.createDefaultState(wantedLanguage);
state = this.createDefaultState(wantedLanguage as LanguageKey);
}
res.render(

View File

@@ -45,7 +45,7 @@ export const logger = winston.createLogger({
// Creates a log stream, suitable to passing to something that writes complete lines of output to a stream, for example
// morgan's http logger. We look for complete text lines and output each as a winston log entry.
export function makeLogStream(level: string, logger_: winston.Logger = logger): {write: (string) => void} {
export function makeLogStream(level: string, logger_: winston.Logger = logger): {write: (chunk: string) => void} {
let buffer = '';
return new Writable({
write: (chunk: string, encoding, callback: () => void) => {

View File

@@ -373,13 +373,13 @@ export class ClientOptionsHandler {
return libraries;
}
getRemoteId(remoteUrl, language) {
getRemoteId(remoteUrl: string, language: LanguageKey) {
const url = new URL(remoteUrl);
return url.host.replaceAll('.', '_') + '_' + language;
}
libArrayToObject(libsArr) {
const libs = {};
libArrayToObject(libsArr: any[]) {
const libs: Record<string, any> = {};
for (const lib of libsArr) {
libs[lib.id] = lib;
@@ -422,8 +422,8 @@ export class ClientOptionsHandler {
return this.remoteLibs[remoteId];
}
async fetchRemoteLibrariesIfNeeded(language: LanguageKey, remote) {
await this.getRemoteLibraries(language, remote.target);
async fetchRemoteLibrariesIfNeeded(language: LanguageKey, target: string) {
await this.getRemoteLibraries(language, target);
}
async setCompilers(compilers: CompilerInfo[]) {
@@ -457,7 +457,7 @@ export class ClientOptionsHandler {
}
if (compiler.remote) {
await this.fetchRemoteLibrariesIfNeeded(compiler.lang, compiler.remote);
await this.fetchRemoteLibrariesIfNeeded(compiler.lang, compiler.remote.target);
}
for (const propKey of Object.keys(compiler)) {

View File

@@ -24,6 +24,7 @@
import {AsmResultLabel, ParsedAsmResultLine} from '../../types/asmresult/asmresult.interfaces.js';
import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js';
import {PropertyGetter} from '../properties.interfaces.js';
import {AsmParser} from './asm-parser.js';
@@ -35,7 +36,7 @@ export class CC65AsmParser extends AsmParser {
directiveRe: RegExp;
labelExtractRe: RegExp;
constructor(compilerProps) {
constructor(compilerProps: PropertyGetter) {
super(compilerProps);
this.labelWithAsmRe = /(L[\dA-F]{4}):\s*(.*)/;
@@ -69,7 +70,7 @@ export class CC65AsmParser extends AsmParser {
return undefined;
}
override processBinaryAsm(asm, filters: ParseFiltersAndOutputOptions) {
override processBinaryAsm(asm: string, filters: ParseFiltersAndOutputOptions) {
const result: ParsedAsmResultLine[] = [];
const asmLines = asm.split('\n');

View File

@@ -22,6 +22,7 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js';
import * as utils from '../utils.js';
import {IAsmParser} from './asm-parser.interfaces.js';
@@ -132,7 +133,7 @@ export class DotNetAsmParser implements IAsmParser {
return cleanedAsm;
}
process(asmResult: string, filters) {
process(asmResult: string, filters: ParseFiltersAndOutputOptions) {
const startTime = process.hrtime.bigint();
const asm: {
@@ -150,7 +151,7 @@ export class DotNetAsmParser implements IAsmParser {
asmLines = asmLines.flatMap(l => (commentRe.test(l) ? [] : [l]));
}
const result = this.scanLabelsAndMethods(asmLines, filters.labels);
const result = this.scanLabelsAndMethods(asmLines, filters.labels!);
for (const i in result.labelDef) {
const label = result.labelDef[i];

View File

@@ -98,7 +98,7 @@ export class AsmEWAVRParser extends AsmParser {
override processAsm(asm: string, filters: ParseFiltersAndOutputOptions): ParsedAsmResult {
// NOTE: EWAVR assembly seems to be closest to visual studio
const getFilenameFromComment = line => {
const getFilenameFromComment = (line: string) => {
const matches = line.match(this.filenameComment);
if (matches) {
return matches[3];
@@ -107,7 +107,7 @@ export class AsmEWAVRParser extends AsmParser {
}
};
const getLineNumberFromComment = line => {
const getLineNumberFromComment = (line: string) => {
const matches = line.match(this.lineNumberComment);
if (matches) {
return parseInt(matches[1]);
@@ -127,27 +127,27 @@ export class AsmEWAVRParser extends AsmParser {
};
let currentLabel: Label | null = null;
let currentFile: string | undefined | null;
let currentLine: number | undefined;
let currentFile: string | null = null;
let currentLine: number | null = null;
let seenEnd = false;
const definedLabels: Record<string, number> = {};
const createSourceFor = (line, currentFile, currentLine) => {
const createSourceFor = (line: string, currentFile: string | null, currentLine: number | null) => {
const hasopc = this.hasOpcode(line);
const createsData = line.match(this.dataStatement);
if ((hasopc || createsData) && (currentFile || currentLine)) {
return {
file: currentFile || null,
line: currentLine || null,
};
} as Source;
}
return null;
};
const checkBeginLabel = line => {
const checkBeginLabel = (line: string) => {
const matches = line.match(this.labelDef);
if (matches && currentLine) {
currentLabel = {
@@ -163,7 +163,7 @@ export class AsmEWAVRParser extends AsmParser {
return currentLabel;
};
const checkRequiresStatement = line => {
const checkRequiresStatement = (line: string) => {
const matches = line.match(this.requireStatement);
if (matches && currentLabel != null) {
if (currentLabel.require == null) {
@@ -199,24 +199,24 @@ export class AsmEWAVRParser extends AsmParser {
throw new Error('EWAVR: non-comment line after the end statement');
}
let tmp = getFilenameFromComment(line);
if (tmp === null) {
tmp = getLineNumberFromComment(line);
if (tmp !== null) {
const fn = getFilenameFromComment(line);
if (fn === null) {
const ln = getLineNumberFromComment(line);
if (ln !== null) {
if (currentFile === undefined) {
logger.error('Somehow, we have a line number comment without a file comment: %s', line);
}
if (currentLabel !== null && currentLabel.initialLine === undefined) {
currentLabel.initialLine = tmp;
currentLabel.initialLine = ln;
}
currentLine = tmp;
currentLine = ln;
}
} else {
// if the file is the "main file", give it the file `null`
if (stdInLooking.test(tmp)) {
if (stdInLooking.test(fn)) {
currentFile = null;
} else {
currentFile = tmp;
currentFile = fn;
}
if (currentLabel != null && currentLabel.file === undefined) {
currentLabel.file = currentFile || null;
@@ -244,7 +244,7 @@ export class AsmEWAVRParser extends AsmParser {
}
line = utils.expandTabs(line);
const textAndSource = {
const textAndSource: Line = {
text: AsmRegex.filterAsmLine(line, filters),
source: createSourceFor(line, currentFile, currentLine),
};
@@ -279,7 +279,7 @@ export class AsmEWAVRParser extends AsmParser {
const result: ParsedAsmResultLine[] = [];
let lastLineWasWhitespace = true;
const pushLine = line => {
const pushLine = (line: Line) => {
if (line.text.trim() === '') {
if (!lastLineWasWhitespace) {
result.push({text: '', source: null});

View File

@@ -72,23 +72,23 @@ export class MadsAsmParser extends AsmParser {
override handleSource(context: ParsingContext, line: string) {}
override handleStabs(context, line) {}
override handleStabs(context: ParsingContext, line: string) {}
getAsmLineWithOpcodeReMatch(
line: string,
source: AsmResultSource | undefined | null,
filters: ParseFiltersAndOutputOptions,
match,
matchGroups: {[key: string]: string},
): ParsedAsmResultLine {
const labelsInLine: AsmResultLabel[] = [];
const address = parseInt(match.groups.address, 16);
const opcodes = (match.groups.opcodes || '').split(' ').filter(x => !!x);
const address = parseInt(matchGroups.address, 16);
const opcodes = (matchGroups.opcodes || '').split(' ').filter(x => !!x);
let text = '';
if (match.groups.label) {
text = match.groups.label.trim() + ': ';
if (matchGroups.label) {
text = matchGroups.label.trim() + ': ';
}
const disassembly = ' ' + AsmRegex.filterAsmLine(match.groups.disasm, filters);
const disassembly = ' ' + AsmRegex.filterAsmLine(matchGroups.disasm, filters);
const destMatch = line.match(this.destRe);
if (destMatch) {
const labelName = destMatch[2];
@@ -152,7 +152,7 @@ export class MadsAsmParser extends AsmParser {
assert(match.groups);
labelDefinitions[match.groups.label] = asm.length;
asm.push(this.getAsmLineWithOpcodeReMatch(line, source, filters, match));
asm.push(this.getAsmLineWithOpcodeReMatch(line, source, filters, match.groups));
continue;
}
@@ -161,7 +161,7 @@ export class MadsAsmParser extends AsmParser {
if (match) {
assert(match.groups);
const parsedLine = this.getAsmLineWithOpcodeReMatch(line, source, filters, match);
const parsedLine = this.getAsmLineWithOpcodeReMatch(line, source, filters, match.groups);
parsedLine.text = linePrefix + parsedLine.text;
asm.push(parsedLine);

View File

@@ -28,9 +28,9 @@ import * as utils from '../utils.js';
import {AsmParser} from './asm-parser.js';
export class SPIRVAsmParser extends AsmParser {
parseOpString(asmLines) {
parseOpString(asmLines: string[]) {
const opString = /^\s*%(\d+)\s+=\s+OpString\s+"([^"]+)"$/;
const files = {};
const files: Record<number, string> = {};
for (const line of asmLines) {
const match = line.match(opString);
if (match) {
@@ -41,7 +41,7 @@ export class SPIRVAsmParser extends AsmParser {
return files;
}
override getUsedLabelsInLine(line): AsmResultLabel[] {
override getUsedLabelsInLine(line: string): AsmResultLabel[] {
const labelsInLine: AsmResultLabel[] = [];
const labelPatterns = [

View File

@@ -22,10 +22,12 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import {PropertyGetter} from '../properties.interfaces.js';
import {AsmParser} from './asm-parser.js';
export class TiC2000AsmParser extends AsmParser {
constructor(compilerProps) {
constructor(compilerProps: PropertyGetter) {
super(compilerProps);
// ignore things that start with a $ or start with .

View File

@@ -58,7 +58,7 @@ export class AsmParserZ88dk extends AsmParser {
if (!lastBlank) asm.push({text: '', source: null, labels: []});
}
const handleSource = line => {
const handleSource = (line: string) => {
const match = line.match(this.sourceTag);
if (match) {
const sourceLine = parseInt(match[1]);

View File

@@ -80,24 +80,24 @@ export class Dex2OatPassDumpParser {
if (inFunctionHeader && this.nameRegex.test(l)) {
match = l.match(this.nameRegex);
functionName = match[1];
functionName = match![1];
functionsToPassDumps[functionName] = [];
} else if (inOptPass && !inBlock && this.nameRegex.test(l)) {
// We check !inBlock because blocks also contain a name
// field that will match nameRegex.
match = l.match(this.nameRegex);
passName = match[1];
functionsToPassDumps[functionName].push({name: passName, lines: []});
passName = match![1];
functionsToPassDumps[functionName!].push({name: passName, lines: []});
} else if (inOptPass) {
const passDump = functionsToPassDumps[functionName].pop();
const passDump = functionsToPassDumps[functionName!].pop();
// pop() can return undefined, but we know that it won't
// because if we're in an opt pass, the previous case should
// have been met already.
if (passDump) {
passDump.lines.push({text: l});
functionsToPassDumps[functionName].push(passDump);
functionsToPassDumps[functionName!].push(passDump);
} else {
logger.error(`passDump for function ${functionName} is undefined!`);
}

View File

@@ -30,6 +30,7 @@ import {
import {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js';
import {ResultLine} from '../../types/resultline/resultline.interfaces.js';
import {assert} from '../assert.js';
import {PropertyGetter} from '../properties.interfaces.js';
// Note(jeremy-rifkin):
// For now this filters out a bunch of metadata we aren't interested in
@@ -81,7 +82,7 @@ export class LlvmPassDumpParser {
//label: RegExp;
//instruction: RegExp;
constructor(compilerProps) {
constructor(compilerProps: PropertyGetter) {
//this.maxIrLines = 5000;
//if (compilerProps) {
// this.maxIrLines = compilerProps('maxLinesOfAsm', this.maxIrLines);

View File

@@ -95,7 +95,7 @@ export function parseProperties(blob: string, name: string): Record<string, Prop
return props;
}
export function initialize(directory: string, hier) {
export function initialize(directory: string, hier: string[]) {
if (hier === null) throw new Error('Must supply a hierarchy array');
hierarchy = hier.map((x: string) => x.toLowerCase());
logger.info(`Reading properties from ${directory} with hierarchy ${hierarchy}`);

View File

@@ -34,7 +34,7 @@ export class TinyUrlShortener extends BaseShortener {
url: 'https://tinyurl.com/api-create.php?url=' + encodeURIComponent(url),
method: 'GET',
};
const callback = (err, resp: request.Response, body) => {
const callback = (err: any, resp: request.Response, body: any) => {
if (!err && resp.statusCode === 200) {
res.send({url: body});
} else {

View File

@@ -29,7 +29,7 @@ import type {Level, Sponsor, Sponsors} from './sponsors.interfaces.js';
export function parse(mapOrString: Record<string, any> | string): Sponsor {
if (typeof mapOrString == 'string') mapOrString = {name: mapOrString};
const displayType = mapOrString.displayType || 'Above';
const style = {};
const style: Record<string, string> = {};
if (mapOrString.bgColour) {
style['background-color'] = mapOrString.bgColour;
}
@@ -128,7 +128,7 @@ class SponsorsImpl implements Sponsors {
private readonly _iconSets: Sponsor[][];
private _nextSet: number;
constructor(levels: Level[], maxTopIcons) {
constructor(levels: Level[], maxTopIcons: number) {
this._levels = levels;
this._icons = [];
for (const level of levels) {

View File

@@ -28,6 +28,7 @@ import * as express from 'express';
import request from 'request';
import {logger} from '../logger.js';
import {CompilerProps} from '../properties.js';
import {ExpandedShortLink, StorageBase} from './base.js';
@@ -40,10 +41,10 @@ export class StorageRemote extends StorageBase {
protected readonly get: (uri: string, options?: request.CoreOptions) => Promise<request.Response>;
protected readonly post: (uri: string, options?: request.CoreOptions) => Promise<request.Response>;
constructor(httpRootDir, compilerProps) {
constructor(httpRootDir: string, compilerProps: CompilerProps) {
super(httpRootDir, compilerProps);
this.baseUrl = compilerProps.ceProps('remoteStorageServer');
this.baseUrl = compilerProps.ceProps('remoteStorageServer') as string;
const req = request.defaults({
baseUrl: this.baseUrl,

View File

@@ -26,9 +26,11 @@ import path from 'path';
import fs from 'fs-extra';
import {ToolInfo} from '../../types/tool.interfaces.js';
import {OptionsHandlerLibrary} from '../options-handler.js';
import * as utils from '../utils.js';
import {ToolEnv} from './base-tool.interface.js';
import {BaseTool} from './base-tool.js';
export class ClangTidyTool extends BaseTool {
@@ -36,7 +38,7 @@ export class ClangTidyTool extends BaseTool {
return 'clang-tidy-tool';
}
constructor(toolInfo, env) {
constructor(toolInfo: ToolInfo, env: ToolEnv) {
super(toolInfo, env);
this.addOptionsToToolArgs = false;

View File

@@ -28,6 +28,7 @@ import * as fs from 'fs-extra';
import {ExecutionOptionsWithEnv} from '../types/compilation/compilation.interfaces.js';
import {BaseCompiler} from './base-compiler.js';
import {logger} from './logger.js';
import * as utils from './utils.js';
@@ -39,7 +40,7 @@ export class WinUtils {
protected execOptions: ExecutionOptionsWithEnv;
protected skippable: string[];
constructor(exec, objdumper: string, execOptions: ExecutionOptionsWithEnv) {
constructor(exec: typeof BaseCompiler.prototype.exec, objdumper: string, execOptions: ExecutionOptionsWithEnv) {
this.exec = exec;
this.objdumper = objdumper;
this.execOptions = execOptions;
@@ -96,7 +97,7 @@ export class WinUtils {
export async function copyNeededDlls(
dirPath: string,
executableFilename: string,
execFunction,
execFunction: typeof BaseCompiler.prototype.exec,
objdumper: string,
execoptions: ExecutionOptionsWithEnv,
): Promise<void> {

1
package-lock.json generated
View File

@@ -4147,6 +4147,7 @@
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-11.0.4.tgz",
"integrity": "sha512-yTbItCNreRooED33qjunPthRcSjERP1r4MqCZc7wv0u2sUkzTFp45tgUfS5+r7FrZPdmCCNflLhVSP/o+SemsQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/jsonfile": "*",
"@types/node": "*"

View File

@@ -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 {Language} from '../types/languages.interfaces.js';
import {Language, LanguageKey} from '../types/languages.interfaces.js';
import {MessageWithLocation} from '../types/resultline/resultline.interfaces.js';
import {SiteSettings} from './settings.js';
import {Theme} from './themes.js';
@@ -116,7 +116,7 @@ export type EventMap = {
optPipelineViewOpened: (compilerId: number) => void;
optPipelineViewOptionsUpdated: (compilerId: number, options: OptPipelineBackendOptions, recompile: boolean) => void;
llvmIrViewOptionsUpdated: (compilerId: number, options: LLVMIrBackendOptions, recompile: boolean) => void;
languageChange: (editorId: number | boolean, newLangId: string, treeId?: boolean | number) => void;
languageChange: (editorId: number | boolean, newLangId: LanguageKey, treeId?: boolean | number) => void;
modifySettings: (modifiedSettings: Partial<SiteSettings>) => void;
motd: (data: Motd) => void;
newSource: (editorId: number, newSource: string) => void;

View File

@@ -28,6 +28,8 @@ import JSZip from 'jszip';
import {Hub} from './hub.js';
import {unwrap} from './assert.js';
import {FiledataPair} from '../types/compilation/compilation.interfaces.js';
import {LanguageKey} from './languages.interfaces.js';
import {Alert} from './widgets/alert.js';
const languages = require('./options').options.languages;
export interface MultifileFile {
@@ -43,14 +45,14 @@ export interface MultifileFile {
export interface MultifileServiceState {
isCMakeProject: boolean;
compilerLanguageId: string;
compilerLanguageId: LanguageKey;
files: MultifileFile[];
newFileId: number;
}
export class MultifileService {
private files: Array<MultifileFile>;
private compilerLanguageId: string;
private compilerLanguageId: LanguageKey;
private isCMakeProject: boolean;
private hub: Hub;
private newFileId: number;
@@ -61,12 +63,12 @@ export class MultifileService {
private readonly cmakeMainSourceFilename: string;
private readonly maxFilesize: number;
constructor(hub: Hub, alertSystem, state: MultifileServiceState) {
constructor(hub: Hub, alertSystem: Alert, state: MultifileServiceState) {
this.hub = hub;
this.alertSystem = alertSystem;
this.isCMakeProject = state.isCMakeProject || false;
this.compilerLanguageId = state.compilerLanguageId || '';
this.compilerLanguageId = state.compilerLanguageId;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
this.files = state.files || [];
this.newFileId = state.newFileId || 1;
@@ -211,7 +213,7 @@ export class MultifileService {
);
}
public setLanguageId(id: string) {
public setLanguageId(id: LanguageKey) {
this.compilerLanguageId = id;
}

View File

@@ -64,7 +64,7 @@ export type Options = {
release?: string;
sentryEnvironment?: string;
compileOptions: Record<LanguageKey, string>;
tools: Record<LanguageKey, Record<string, Tool>>;
tools: Partial<Record<LanguageKey, Record<string, Tool>>>;
slides?: any[];
cookieDomainRe: string;
motdUrl: string;

View File

@@ -80,6 +80,7 @@ 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 {LanguageKey} from '../languages.interfaces.js';
const toolIcons = require.context('../../views/resources/logos', false, /\.(png|svg)$/);
@@ -1297,7 +1298,7 @@ export class Compiler extends MonacoPane<monaco.editor.IStandaloneCodeEditor, Co
version: item.versionId,
})) ?? [],
executeParameters: {
args: '',
args: [],
stdin: '',
runtimeTools: this.getCurrentState().runtimeTools,
},
@@ -3748,7 +3749,7 @@ export class Compiler extends MonacoPane<monaco.editor.IStandaloneCodeEditor, Co
CompilerService.handleCompilationStatus(this.statusLabel, this.statusIcon, status);
}
onLanguageChange(editorId: number | boolean, newLangId: string, treeId?: number | boolean): void {
onLanguageChange(editorId: number | boolean, newLangId: LanguageKey, treeId?: number | boolean): void {
if (
(this.sourceEditorId && this.sourceEditorId === editorId) ||
(this.sourceTreeId && this.sourceTreeId === treeId)
@@ -3757,7 +3758,10 @@ export class Compiler extends MonacoPane<monaco.editor.IStandaloneCodeEditor, Co
this.currentLangId = newLangId;
// Store the current selected stuff to come back to it later in the same session (Not state stored!)
this.infoByLang[oldLangId] = {
compiler: this.compiler && this.compiler.id ? this.compiler.id : options.defaultCompiler[oldLangId],
compiler:
this.compiler && this.compiler.id
? this.compiler.id
: options.defaultCompiler[oldLangId as LanguageKey],
options: this.options,
};
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition

View File

@@ -1862,7 +1862,7 @@ export class Editor extends MonacoPane<monaco.editor.IStandaloneCodeEditor, Edit
});
}
onLanguageChange(newLangId: string, firstTime?: boolean): void {
onLanguageChange(newLangId: LanguageKey, firstTime?: boolean): void {
if (newLangId in languages) {
if (firstTime || newLangId !== this.currentLanguage?.id) {
const oldLangId = this.currentLanguage?.id;

View File

@@ -286,7 +286,7 @@ export class Executor extends Pane<ExecutorState> {
const options: CompilationRequestOptions = {
userArguments: this.options,
executeParameters: {
args: this.executionArguments,
args: this.executionArguments.split(' '),
stdin: this.executionStdin,
runtimeTools: this.compilerShared.getRuntimeTools(),
},

View File

@@ -41,6 +41,7 @@ import {ComponentConfig, PopulatedToolInputViewState} from '../components.interf
import {unwrap, unwrapString} from '../assert.js';
import {CompilationResult} from '../compilation/compilation.interfaces.js';
import {CompilerInfo} from '../compiler.interfaces.js';
import {LanguageKey} from '../languages.interfaces.js';
function makeAnsiToHtml(color?: string) {
return new AnsiToHtml.Filter({
@@ -179,14 +180,14 @@ export class Tool extends MonacoPane<monaco.editor.IStandaloneCodeEditor, ToolSt
}
}
onLanguageChange(editorId, newLangId) {
onLanguageChange(editorId: number | boolean, newLangId: LanguageKey) {
if (this.compilerInfo.editorId && this.compilerInfo.editorId === editorId) {
const tools = ceoptions.tools[newLangId];
this.toggleUsable(tools && tools[this.toolId]);
this.toggleUsable(!!tools && !!tools[this.toolId]);
}
}
toggleUsable(isUsable) {
toggleUsable(isUsable: boolean) {
if (isUsable) {
this.plainContentRoot.css('opacity', '1');
this.badLangToolbar.hide();
@@ -199,7 +200,7 @@ export class Tool extends MonacoPane<monaco.editor.IStandaloneCodeEditor, ToolSt
}
initArgs(state: ToolState & MonacoPaneState) {
const optionsChange = _.debounce(e => {
const optionsChange = _.debounce((e: any) => {
this.onOptionsChange();
this.eventHub.emit('toolSettingsChange', this.compilerInfo.compilerId);
@@ -416,7 +417,7 @@ export class Tool extends MonacoPane<monaco.editor.IStandaloneCodeEditor, ToolSt
const foundTool = _.find(compiler.tools, tool => tool.tool.id === this.toolId);
this.toggleUsable(foundTool);
this.toggleUsable(!!foundTool);
// any for now for typing reasons... TODO(jeremy-rifkin)
let toolResult: any = null;

View File

@@ -40,6 +40,7 @@ import {Container} from 'golden-layout';
import _ from 'underscore';
import {assert, unwrap, unwrapString} from '../assert.js';
import {escapeHTML} from '../../shared/common-utils.js';
import {LanguageKey} from '../languages.interfaces.js';
const languages = options.languages;
@@ -236,7 +237,7 @@ export class Tree {
this.updateState();
}
private onLanguageChange(newLangId: string) {
private onLanguageChange(newLangId: LanguageKey) {
if (newLangId in languages) {
this.multifileService.setLanguageId(newLangId);
this.eventHub.emit('languageChange', false, newLangId, this.id);
@@ -269,7 +270,7 @@ export class Tree {
}
}
private onCompilerOpen(compilerId: number, unused, treeId: number | boolean) {
private onCompilerOpen(compilerId: number, unused: number, treeId: number | boolean) {
if (treeId === this.id) {
this.ourCompilers[compilerId] = true;
this.sendCompilerChangesToEditor(compilerId);

View File

@@ -36,13 +36,9 @@ import {
} from '../../lib/compilers/argument-parsers.js';
import {FakeCompiler} from '../../lib/compilers/fake-for-test.js';
const languages = {
'c++': {id: 'c++'},
};
function makeCompiler(stdout?: string, stderr?: string, code?: number) {
if (code === undefined) code = 0;
const compiler = new FakeCompiler({lang: languages['c++'].id, remote: true}) as any;
const compiler = new FakeCompiler({lang: 'c++'}) as any;
compiler.exec = () => Promise.resolve({code: code, stdout: stdout || '', stderr: stderr || ''});
compiler.execCompilerCached = compiler.exec;
compiler.possibleArguments = new CompilerArguments('g82');

View File

@@ -156,7 +156,7 @@ describe('Hook compiler', () => {
labelDefinitions: {},
};
const filters = {trim: false};
const result = await hook.processAsm({asm: asm}, filters, null);
const result = await hook.processAsm({asm: asm}, filters, []);
delete result.parsingTime;
expect(result).toEqual(expected);
});

View File

@@ -48,7 +48,7 @@ export type ActiveTools = {
};
export type ExecutionParams = {
args?: string[] | string;
args?: string[];
stdin?: string;
runtimeTools?: ConfiguredRuntimeTools;
};

View File

@@ -26,6 +26,7 @@ import {
BypassCache,
CompilationResult,
CompileChildLibraries,
ExecutionParams,
FiledataPair,
} from './compilation/compilation.interfaces.js';
import {AllCompilerOverrideOptions} from './compilation/compiler-overrides.interfaces.js';
@@ -121,7 +122,7 @@ export type CompilerInfo = {
hidden: boolean;
buildenvsetup?: {
id: string;
props: (name: string, def: any) => any;
props: (name: string, def?: any) => any;
};
license?: {
link?: string;
@@ -175,11 +176,11 @@ export interface ICompiler {
filters: ParseFiltersAndOutputOptions,
bypassCache: BypassCache,
tools,
executeParameters,
executeParameters: ExecutionParams,
libraries: CompileChildLibraries[],
files: FiledataPair[],
);
): Promise<any>;
cmake(files: FiledataPair[], key, bypassCache: BypassCache): Promise<CompilationResult>;
initialise(mtime: Date, clientOptions, isPrediscovered: boolean);
initialise(mtime: Date, clientOptions, isPrediscovered: boolean): Promise<ICompiler | null>;
getInfo(): CompilerInfo;
}

View File

@@ -56,7 +56,7 @@ const hasGit = fs.existsSync(path.resolve(__dirname, '.git'));
// Hack alert: due to a variety of issues, sometimes we need to change
// the name here. Mostly it's things like webpack changes that affect
// how minification is done, even though that's supposed not to matter.
const webpackJsHack = '.v53.';
const webpackJsHack = '.v54.';
const plugins: Webpack.WebpackPluginInstance[] = [
new MonacoEditorWebpackPlugin({
languages: [