From b2e813803e9497da69bec492a12a4537442a6f86 Mon Sep 17 00:00:00 2001 From: benmurphyy <47269122+benmurphyy@users.noreply.github.com> Date: Sat, 10 Feb 2024 16:09:30 +0800 Subject: [PATCH] Lint and prettify --- ctowasm/src/common/constants.ts | 2 +- ctowasm/src/common/utils.ts | 2 +- ctowasm/src/compiler.ts | 13 ++-- ctowasm/src/index.ts | 9 ++- ctowasm/src/modules/index.ts | 20 ++++-- ctowasm/src/modules/source_stdlib/index.ts | 8 +-- ctowasm/src/modules/source_stdlib/memory.ts | 10 +-- ctowasm/src/parser/index.ts | 6 +- ctowasm/src/processor/c-ast/function.ts | 6 +- ctowasm/src/processor/c-ast/memory.ts | 2 +- ctowasm/src/processor/dataTypeUtil.ts | 36 +++++----- ctowasm/src/processor/index.ts | 10 +-- ctowasm/src/processor/processBlockItem.ts | 4 +- ctowasm/src/processor/processExpression.ts | 68 +++++++++---------- .../processor/processFunctionDefinition.ts | 19 +++--- ctowasm/src/processor/symbolTable.ts | 36 +++++----- ctowasm/src/processor/util.ts | 27 +++++--- ctowasm/src/translator/index.ts | 4 +- ctowasm/src/translator/memoryUtil.ts | 6 +- .../translator/processImportedFunctions.ts | 10 +-- ctowasm/src/translator/translateExpression.ts | 6 +- .../src/translator/translateFunctionCall.ts | 28 ++++---- ctowasm/src/translator/util.ts | 25 ++++--- ctowasm/src/translator/wasm-ast/core.ts | 2 +- .../src/translator/wasm-ast/functionTable.ts | 6 +- ctowasm/src/translator/wasm-ast/functions.ts | 9 ++- ctowasm/src/wat-generator/constants.ts | 2 +- .../src/wat-generator/generateWatStatement.ts | 13 ++-- ctowasm/src/wat-generator/index.ts | 22 +++--- ctowasm/src/wat-generator/util.ts | 6 +- 30 files changed, 232 insertions(+), 185 deletions(-) diff --git a/ctowasm/src/common/constants.ts b/ctowasm/src/common/constants.ts index 5fb4c10..56afa16 100644 --- a/ctowasm/src/common/constants.ts +++ b/ctowasm/src/common/constants.ts @@ -8,4 +8,4 @@ export const POINTER_SIZE = WASM_ADDR_SIZE; // size of a pointer in bytes - shou export const SIZE_T = "unsigned int"; // implmentation-defined export const PTRDIFF_T = "signed int"; // defined type for difference between pointers export const POINTER_TYPE = "unsigned int"; // type equivalent to pointer TODO: check this -export const ENUM_DATA_TYPE = "signed int"; // the datatype that enum directly corresponds to in this compiler implementation \ No newline at end of file +export const ENUM_DATA_TYPE = "signed int"; // the datatype that enum directly corresponds to in this compiler implementation diff --git a/ctowasm/src/common/utils.ts b/ctowasm/src/common/utils.ts index af3523a..48fd0e8 100644 --- a/ctowasm/src/common/utils.ts +++ b/ctowasm/src/common/utils.ts @@ -69,4 +69,4 @@ export function isConstant(node: CNodeBase) { */ export function calculateNumberOfPagesNeededForBytes(numBytes: number) { return Math.floor(numBytes / WASM_PAGE_SIZE) + 1; -} \ No newline at end of file +} diff --git a/ctowasm/src/compiler.ts b/ctowasm/src/compiler.ts index 9402adf..d990d48 100644 --- a/ctowasm/src/compiler.ts +++ b/ctowasm/src/compiler.ts @@ -17,7 +17,7 @@ export interface CompilationResult { export async function compile( cSourceCode: string, - moduleRepository: ModuleRepository + moduleRepository: ModuleRepository, ): Promise { try { const CAst = parse(cSourceCode, moduleRepository); @@ -39,7 +39,7 @@ export async function compile( export function compileToWat( cSourceCode: string, - moduleRepository: ModuleRepository + moduleRepository: ModuleRepository, ) { try { const CAst = parse(cSourceCode, moduleRepository); @@ -55,7 +55,10 @@ export function compileToWat( } } -export function generate_C_AST(cSourceCode: string, moduleRepository: ModuleRepository) { +export function generate_C_AST( + cSourceCode: string, + moduleRepository: ModuleRepository, +) { try { const ast = parse(cSourceCode, moduleRepository); return toJson(ast); @@ -69,7 +72,7 @@ export function generate_C_AST(cSourceCode: string, moduleRepository: ModuleRepo export function generate_processed_C_AST( cSourceCode: string, - moduleRepository: ModuleRepository + moduleRepository: ModuleRepository, ) { try { const CAst = parse(cSourceCode, moduleRepository); @@ -85,7 +88,7 @@ export function generate_processed_C_AST( export function generate_WAT_AST( cSourceCode: string, - moduleRepository: ModuleRepository + moduleRepository: ModuleRepository, ) { const CAst = parse(cSourceCode, moduleRepository); const { astRootNode } = process(CAst, moduleRepository); diff --git a/ctowasm/src/index.ts b/ctowasm/src/index.ts index 1406e9f..8ff00ff 100644 --- a/ctowasm/src/index.ts +++ b/ctowasm/src/index.ts @@ -49,13 +49,16 @@ export async function runWasm( importedModules: ModuleName[], modulesConfig?: ModulesGlobalConfig, ) { - const numberOfInitialPagesNeeded = calculateNumberOfPagesNeededForBytes(dataSegmentSize); + const numberOfInitialPagesNeeded = + calculateNumberOfPagesNeededForBytes(dataSegmentSize); const moduleRepository = new ModuleRepository( new WebAssembly.Memory({ initial: numberOfInitialPagesNeeded }), modulesConfig, ); - moduleRepository.setStackPointerValue(numberOfInitialPagesNeeded * WASM_PAGE_SIZE); - moduleRepository.setHeapPointerValue(Math.ceil(dataSegmentSize / 4) * 4) // align to 4 bytes + moduleRepository.setStackPointerValue( + numberOfInitialPagesNeeded * WASM_PAGE_SIZE, + ); + moduleRepository.setHeapPointerValue(Math.ceil(dataSegmentSize / 4) * 4); // align to 4 bytes await WebAssembly.instantiate( wasm, moduleRepository.createWasmImportsObject(importedModules), diff --git a/ctowasm/src/modules/index.ts b/ctowasm/src/modules/index.ts index 594ea7f..cc265ea 100644 --- a/ctowasm/src/modules/index.ts +++ b/ctowasm/src/modules/index.ts @@ -29,7 +29,7 @@ export default class ModuleRepository { config: ModulesGlobalConfig; modules: Record; sharedWasmGlobalVariables: SharedWasmGlobalVariables; - + constructor(memory?: WebAssembly.Memory, config?: ModulesGlobalConfig) { if (memory) { this.memory = memory; // initially memory starts at 0 @@ -44,15 +44,21 @@ export default class ModuleRepository { } this.sharedWasmGlobalVariables = { - stackPointer: new WebAssembly.Global({value: WASM_ADDR_TYPE, mutable: true}, 0), - heapPointer:new WebAssembly.Global({value: WASM_ADDR_TYPE, mutable: true}, 0) + stackPointer: new WebAssembly.Global( + { value: WASM_ADDR_TYPE, mutable: true }, + 0, + ), + heapPointer: new WebAssembly.Global( + { value: WASM_ADDR_TYPE, mutable: true }, + 0, + ), }; this.modules = { [sourceStandardLibraryModuleImportName]: new SourceStandardLibraryModule( this.memory, this.config, - this.sharedWasmGlobalVariables + this.sharedWasmGlobalVariables, ), }; } @@ -75,7 +81,11 @@ export default class ModuleRepository { */ createWasmImportsObject(importedModules: ModuleName[]): WebAssembly.Imports { const imports: WebAssembly.Imports = { - js: { mem: this.memory, sp: this.sharedWasmGlobalVariables.stackPointer, hp: this.sharedWasmGlobalVariables.heapPointer }, + js: { + mem: this.memory, + sp: this.sharedWasmGlobalVariables.stackPointer, + hp: this.sharedWasmGlobalVariables.heapPointer, + }, }; importedModules.forEach((moduleName) => { diff --git a/ctowasm/src/modules/source_stdlib/index.ts b/ctowasm/src/modules/source_stdlib/index.ts index ee831f5..74bf026 100644 --- a/ctowasm/src/modules/source_stdlib/index.ts +++ b/ctowasm/src/modules/source_stdlib/index.ts @@ -9,7 +9,7 @@ import { } from "~src/modules/source_stdlib/memory"; import { Module, ModuleFunction } from "~src/modules/types"; import { convertFloatToCStyleString } from "~src/modules/util"; -import { DataType, StructDataType } from "~src/parser/c-ast/dataTypes"; +import { StructDataType } from "~src/parser/c-ast/dataTypes"; // the name that this module is imported into wasm by, // as well as the include name to use in C program file. @@ -27,7 +27,7 @@ export class SourceStandardLibraryModule extends Module { constructor( memory: WebAssembly.Memory, config: ModulesGlobalConfig, - sharedWasmGlobalVariables: SharedWasmGlobalVariables + sharedWasmGlobalVariables: SharedWasmGlobalVariables, ) { super(memory, config); this.sharedWasmGlobalVariables = sharedWasmGlobalVariables; @@ -275,7 +275,7 @@ export class SourceStandardLibraryModule extends Module { printHeap( this.memory, this.heapAddress, - this.sharedWasmGlobalVariables.heapPointer.value + this.sharedWasmGlobalVariables.heapPointer.value, ), }, print_stack: { @@ -288,7 +288,7 @@ export class SourceStandardLibraryModule extends Module { jsFunction: () => printStack( this.memory, - this.sharedWasmGlobalVariables.stackPointer.value + this.sharedWasmGlobalVariables.stackPointer.value, ), }, // EXAMPLE of how to have a function taking aggregate type and returning aggreate type - TESTED AND WORKING diff --git a/ctowasm/src/modules/source_stdlib/memory.ts b/ctowasm/src/modules/source_stdlib/memory.ts index 08ab6e2..9adca27 100644 --- a/ctowasm/src/modules/source_stdlib/memory.ts +++ b/ctowasm/src/modules/source_stdlib/memory.ts @@ -59,7 +59,7 @@ export function mallocFunction({ if (freeSpace < bytesRequested) { // need to grow memory const additionalPagesNeeded = calculateNumberOfPagesNeededForBytes( - bytesRequested - freeSpace + bytesRequested - freeSpace, ); const stackSegmentSize = memory.buffer.byteLength - stackPointer.value; const oldMemorySize = memory.buffer.byteLength; @@ -107,12 +107,12 @@ export function freeFunction({ export function printHeap( memory: WebAssembly.Memory, heapAddress: number, - heapPointer: number + heapPointer: number, ) { const memoryView = new Uint8Array( memory.buffer, heapAddress, - heapPointer - heapAddress + heapPointer - heapAddress, ); console.log(memoryView); } @@ -121,7 +121,7 @@ export function printStack(memory: WebAssembly.Memory, stackPointer: number) { const memoryView = new Uint8Array( memory.buffer, stackPointer, - memory.buffer.byteLength - stackPointer + memory.buffer.byteLength - stackPointer, ); console.log(memoryView); -} \ No newline at end of file +} diff --git a/ctowasm/src/parser/index.ts b/ctowasm/src/parser/index.ts index ab9b422..cc11f95 100644 --- a/ctowasm/src/parser/index.ts +++ b/ctowasm/src/parser/index.ts @@ -37,7 +37,11 @@ const parser = peggy.generate(parsingGrammar as string, { warning: warningCallback, }); -export default function parse(sourceCode: string, moduleRepository: ModuleRepository) { +export default function parse( + sourceCode: string, + moduleRepository: ModuleRepository, +) { + // eslint-disable-next-line // @ts-ignore parser.moduleRepository = moduleRepository; // make moduleRepository available to parser object return parser.parse(lexer.parse(preprocessor.parse(sourceCode))); diff --git a/ctowasm/src/processor/c-ast/function.ts b/ctowasm/src/processor/c-ast/function.ts index 5afd1d3..60b2e81 100644 --- a/ctowasm/src/processor/c-ast/function.ts +++ b/ctowasm/src/processor/c-ast/function.ts @@ -27,15 +27,15 @@ export interface FunctionDetails { export interface FunctionCallP { type: "FunctionCall"; calledFunction: CalledFunction; - functionDetails: FunctionDetails;// details of the function being called + functionDetails: FunctionDetails; // details of the function being called args: ExpressionP[]; // the sequence of expressions which load up the function arguments } export type CalledFunction = IndirectlyCalledFunction | DirectlyCalledFunction; export interface IndirectlyCalledFunction { - type: "IndirectlyCalledFunction" - functionAddress: ExpressionP // expression that returns the address of function to call + type: "IndirectlyCalledFunction"; + functionAddress: ExpressionP; // expression that returns the address of function to call } export interface DirectlyCalledFunction { diff --git a/ctowasm/src/processor/c-ast/memory.ts b/ctowasm/src/processor/c-ast/memory.ts index a9d1158..3744de2 100644 --- a/ctowasm/src/processor/c-ast/memory.ts +++ b/ctowasm/src/processor/c-ast/memory.ts @@ -43,7 +43,7 @@ export interface DynamicAddress extends AddressBase { */ export interface FunctionTableIndex extends AddressBase { type: "FunctionTableIndex"; - index: IntegerConstantP; + index: IntegerConstantP; } // represents the address of a primary data object that is part of a return object of a function diff --git a/ctowasm/src/processor/dataTypeUtil.ts b/ctowasm/src/processor/dataTypeUtil.ts index c2a97c0..317ac30 100644 --- a/ctowasm/src/processor/dataTypeUtil.ts +++ b/ctowasm/src/processor/dataTypeUtil.ts @@ -274,7 +274,9 @@ export function determineIndexAndDataTypeOfFieldInStruct( ); } -export function convertFunctionDataTypeToFunctionDetails(dataType: FunctionDataType): FunctionDetails { +export function convertFunctionDataTypeToFunctionDetails( + dataType: FunctionDataType, +): FunctionDetails { const functionDetails: FunctionDetails = { sizeOfParams: 0, sizeOfReturn: 0, @@ -299,23 +301,23 @@ export function convertFunctionDataTypeToFunctionDetails(dataType: FunctionDataT } let offset = 0; - for (const param of dataType.parameters) { - // sanity check, as parser should have converted all array params into pointers. - if (param.type === "array") { - throw new ProcessingError( - "Compiler error: The type of a function parameter should not be an array after parsing", - ); - } - const dataTypeSize = getDataTypeSize(param); - offset -= dataTypeSize; - functionDetails.sizeOfParams += dataTypeSize; - const unpackedParam = unpackDataType(param).map((scalarDataType) => ({ - dataType: scalarDataType.dataType, - offset: offset + scalarDataType.offset, // offset of entire aggregate object + offset of particular sacalar data type within object - })); - // need to load unpacked param in reverse order, as in stack frame creation, the highest address subobject of an aggregate type gets loaded first as the stack frame grows from high to low address - functionDetails.parameters.push(...unpackedParam.reverse()); + for (const param of dataType.parameters) { + // sanity check, as parser should have converted all array params into pointers. + if (param.type === "array") { + throw new ProcessingError( + "Compiler error: The type of a function parameter should not be an array after parsing", + ); } + const dataTypeSize = getDataTypeSize(param); + offset -= dataTypeSize; + functionDetails.sizeOfParams += dataTypeSize; + const unpackedParam = unpackDataType(param).map((scalarDataType) => ({ + dataType: scalarDataType.dataType, + offset: offset + scalarDataType.offset, // offset of entire aggregate object + offset of particular sacalar data type within object + })); + // need to load unpacked param in reverse order, as in stack frame creation, the highest address subobject of an aggregate type gets loaded first as the stack frame grows from high to low address + functionDetails.parameters.push(...unpackedParam.reverse()); + } return functionDetails; } diff --git a/ctowasm/src/processor/index.ts b/ctowasm/src/processor/index.ts index 0b3877a..8830b71 100644 --- a/ctowasm/src/processor/index.ts +++ b/ctowasm/src/processor/index.ts @@ -17,13 +17,13 @@ import ModuleRepository, { ModuleName } from "~src/modules"; */ export default function process( ast: CAstRoot, - moduleRepository: ModuleRepository + moduleRepository: ModuleRepository, ): { astRootNode: CAstRootP; includedModules: ModuleName[] } { const includedModules: ModuleName[] = []; const symbolTable = new SymbolTable(); const processedExternalFunctions = symbolTable.setExternalFunctions( ast.includedModules, - moduleRepository + moduleRepository, ); const processedAst: CAstRootP = { type: "Root", @@ -31,7 +31,7 @@ export default function process( dataSegmentByteStr: "", dataSegmentSizeInBytes: 0, externalFunctions: [], - functionTable: [] + functionTable: [], }; // save the processed details of external functions @@ -49,7 +49,7 @@ export default function process( processedExternalFunctions[moduleFunctionName].functionDetails .returnObjects, }); - } + }, ); } @@ -57,7 +57,7 @@ export default function process( // special handling for function definitions if (child.type === "FunctionDefinition") { processedAst.functions.push( - processFunctionDefinition(child, symbolTable) + processFunctionDefinition(child, symbolTable), ); } else { processGlobalScopeDeclaration(child, symbolTable); diff --git a/ctowasm/src/processor/processBlockItem.ts b/ctowasm/src/processor/processBlockItem.ts index dcc1c0a..cdcbaf7 100644 --- a/ctowasm/src/processor/processBlockItem.ts +++ b/ctowasm/src/processor/processBlockItem.ts @@ -215,7 +215,9 @@ export default function processBlockItem( return getAssignmentNodes(node, symbolTable).memoryStoreStatements; } else if (node.type === "FunctionCall") { // in this context, the return (if any) of the functionCall is ignored, as it is used as a statement - return [convertFunctionCallToFunctionCallP(node, symbolTable).functionCallP]; + return [ + convertFunctionCallToFunctionCallP(node, symbolTable).functionCallP, + ]; } else if ( node.type === "PrefixExpression" || node.type === "PostfixExpression" diff --git a/ctowasm/src/processor/processExpression.ts b/ctowasm/src/processor/processExpression.ts index 52fd827..ee0e422 100644 --- a/ctowasm/src/processor/processExpression.ts +++ b/ctowasm/src/processor/processExpression.ts @@ -52,7 +52,7 @@ import { StatementP } from "~src/processor/c-ast/core"; export default function processExpression( expr: Expression, symbolTable: SymbolTable, - enclosingFunc?: FunctionDefinitionP + enclosingFunc?: FunctionDefinitionP, ): ExpressionWrapperP { try { if (expr.type === "Assignment") { @@ -90,7 +90,7 @@ export default function processExpression( !isScalarDataType(processedRightExprDataType) ) { throw new ProcessingError( - `Non-scalar operand to ${expr.operator} binary expression: left operand: ${processedLeftExprDataType.type}, right operand: ${processedRightExprDataType.type}` + `Non-scalar operand to ${expr.operator} binary expression: left operand: ${processedLeftExprDataType.type}, right operand: ${processedRightExprDataType.type}`, ); } @@ -100,7 +100,7 @@ export default function processExpression( ) { throw new ProcessingError( "Aggregate expressions cannot be used in binary expressions", - expr.position + expr.position, ); } @@ -108,7 +108,7 @@ export default function processExpression( checkBinaryExpressionDataTypesValidity( processedLeftExprDataType, processedRightExprDataType, - expr.operator + expr.operator, ); } catch (e) { if (e instanceof ProcessingError) { @@ -122,14 +122,14 @@ export default function processExpression( determineResultDataTypeOfBinaryExpression( processedLeftExprDataType as ScalarDataType, processedRightExprDataType as ScalarDataType, - expr.operator + expr.operator, ); const operandTargetDataType = determineOperandTargetDataTypeOfBinaryExpression( processedLeftExprDataType as ScalarDataType, // already checked that is scalar in checkBinaryExpressionDataTypesValidity processedRightExprDataType as ScalarDataType, - expr.operator + expr.operator, ); let leftExpr = processedLeftExpr.exprs[0]; @@ -147,7 +147,9 @@ export default function processExpression( rightExpr: { type: "IntegerConstant", value: BigInt( - getDataTypeSize(processedLeftExprDataType.pointeeType as DataType) + getDataTypeSize( + processedLeftExprDataType.pointeeType as DataType, + ), ), // void pointer already checked for dataType: rightExpr.dataType as IntegerDataType, // datatype is confirmed by determineDataTypeOfBinaryExpression }, @@ -166,8 +168,8 @@ export default function processExpression( type: "IntegerConstant", value: BigInt( getDataTypeSize( - processedRightExprDataType.pointeeType as DataType - ) + processedRightExprDataType.pointeeType as DataType, + ), ), dataType: leftExpr.dataType as IntegerDataType, // datatype is confirmed by determineDataTypeOfBinaryExpression }, @@ -203,8 +205,8 @@ export default function processExpression( type: "IntegerConstant", value: BigInt( getDataTypeSize( - processedRightExprDataType.pointeeType as DataType - ) + processedRightExprDataType.pointeeType as DataType, + ), ), dataType: PTRDIFF_T, }, @@ -254,7 +256,7 @@ export default function processExpression( if (funcReturnType === null) { // trying to use a function call as an expression in context that expects a return object - throw new ProcessingError("void value not ignored as it should") + throw new ProcessingError("void value not ignored as it should"); } // start curr offset at negative of the size of the return obj @@ -304,7 +306,7 @@ export default function processExpression( return createFunctionTableIndexExpressionWrapper( expr.name, symbolEntry.dataType, - symbolTable + symbolTable, ); } @@ -349,7 +351,7 @@ export default function processExpression( ? "DataSegmentAddress" : "LocalAddress", offset: createMemoryOffsetIntegerConstant( - symbolEntry.offset + primaryDataObject.offset + symbolEntry.offset + primaryDataObject.offset, ), dataType: "pointer", }, @@ -370,7 +372,7 @@ export default function processExpression( return createFunctionTableIndexExpressionWrapper( expr.expr.name, symbolEntry.dataType, - symbolTable + symbolTable, ); } @@ -417,9 +419,7 @@ export default function processExpression( } // if the derefed expression a function pointer, it remains one - if ( - isFunctionPointer(derefedExpressionDataType) - ) { + if (isFunctionPointer(derefedExpressionDataType)) { return derefedExpression; } @@ -458,7 +458,7 @@ export default function processExpression( }; } else { const unpackedStruct = unpackDataType( - derefedExpressionDataType.pointeeType + derefedExpressionDataType.pointeeType, ); return { originalDataType: derefedExpressionDataType.pointeeType, @@ -470,7 +470,7 @@ export default function processExpression( type: "BinaryExpression", leftExpr: derefedExpression.exprs[0], // value of dereferenced expression (starting address of the pointed to struct) rightExpr: createMemoryOffsetIntegerConstant( - primaryDataObject.offset + primaryDataObject.offset, ), // offset of particular primary data object in struct operator: "+", operandTargetDataType: "pointer", @@ -488,7 +488,7 @@ export default function processExpression( // sizeof used on expression dataTypeToGetSizeOf = processExpression( expr.expr, - symbolTable + symbolTable, ).originalDataType; } else { // sizeof used on datatype @@ -515,7 +515,7 @@ export default function processExpression( }); if (dataTypeOfExpr.type !== "struct") { throw new ProcessingError( - `request for member '${expr.fieldTag}' in something that is not a structure or union` + `request for member '${expr.fieldTag}' in something that is not a structure or union`, ); } const { fieldIndex, fieldDataType } = @@ -535,7 +535,7 @@ export default function processExpression( const memLoad = processedExpr.exprs[0].expr; if (memLoad.type !== "MemoryLoad") { throw new ProcessingError( - `request for member '${expr.fieldTag}' in something that is not a structure or union` + `request for member '${expr.fieldTag}' in something that is not a structure or union`, ); } memoryLoadExpr = memLoad; @@ -543,7 +543,7 @@ export default function processExpression( const memLoad = processedExpr.exprs[fieldIndex]; if (memLoad.type !== "MemoryLoad") { throw new ProcessingError( - `request for member '${expr.fieldTag}' in something that is not a structure or union` + `request for member '${expr.fieldTag}' in something that is not a structure or union`, ); } memoryLoadExpr = memLoad; @@ -602,7 +602,7 @@ export default function processExpression( totalBytesLoaded += getSizeOfScalarDataType(loadExpr.dataType); } else { throw new ProcessingError( - `request for member '${expr.fieldTag}' in something that is not a structure or union` + `request for member '${expr.fieldTag}' in something that is not a structure or union`, ); } } @@ -611,14 +611,14 @@ export default function processExpression( if (processedExpr.exprs[currLoadIndex].type !== "MemoryLoad") { // only "MemoryLoads" can possibly indicate an lvalue throw new ProcessingError( - `request for member '${expr.fieldTag}' in something that is not a structure or union` + `request for member '${expr.fieldTag}' in something that is not a structure or union`, ); } totalBytesLoaded += getSizeOfScalarDataType( - (processedExpr.exprs[currLoadIndex] as MemoryLoad).dataType + (processedExpr.exprs[currLoadIndex] as MemoryLoad).dataType, ); memoryLoadExprs.push( - processedExpr.exprs[currLoadIndex++] as MemoryLoad + processedExpr.exprs[currLoadIndex++] as MemoryLoad, ); } return { @@ -634,7 +634,7 @@ export default function processExpression( // process the first expressions as statements const processedLastExpr = processExpression( expr.expressions[expr.expressions.length - 1], - symbolTable + symbolTable, ); const precedingExpressionsAsStatements: StatementP[] = []; for (let i = 0; i < expr.expressions.length - 1; ++i) { @@ -642,8 +642,8 @@ export default function processExpression( ...processBlockItem( expr.expressions[i], symbolTable, - enclosingFunc as FunctionDefinitionP - ) + enclosingFunc as FunctionDefinitionP, + ), ); } return { @@ -662,7 +662,7 @@ export default function processExpression( const processedCondition = processCondition(expr.condition, symbolTable); const processedTrueExpression = processExpression( expr.trueExpression, - symbolTable + symbolTable, ); const dataTypeOfTrueExpression = getDataTypeOfExpression({ expression: processedTrueExpression, @@ -670,7 +670,7 @@ export default function processExpression( }); const processedFalseExpression = processExpression( expr.falseExpression, - symbolTable + symbolTable, ); const dataTypeOfFalseExpression = getDataTypeOfExpression({ expression: processedFalseExpression, @@ -682,7 +682,7 @@ export default function processExpression( if (isScalarDataType(dataTypeOfTrueExpression)) { scalarConditionalDataType = determineConditionalExpressionDataType( dataTypeOfTrueExpression as ScalarDataType, - dataTypeOfFalseExpression as ScalarDataType + dataTypeOfFalseExpression as ScalarDataType, ); } diff --git a/ctowasm/src/processor/processFunctionDefinition.ts b/ctowasm/src/processor/processFunctionDefinition.ts index 597c228..3fbb3b2 100644 --- a/ctowasm/src/processor/processFunctionDefinition.ts +++ b/ctowasm/src/processor/processFunctionDefinition.ts @@ -25,7 +25,7 @@ import { DataType } from "~src/parser/c-ast/dataTypes"; export default function processFunctionDefinition( node: FunctionDefinition, - symbolTable: SymbolTable + symbolTable: SymbolTable, ): FunctionDefinitionP { symbolTable.addFunctionEntry(node.name, node.dataType); symbolTable.setFunctionIsDefinedFlag(node.name); @@ -43,7 +43,7 @@ export default function processFunctionDefinition( funcSymbolTable.addVariableEntry( node.parameterNames[i], node.dataType.parameters[i], - "auto" // all function parameters must have "auto" storage class + "auto", // all function parameters must have "auto" storage class ); } @@ -59,7 +59,7 @@ export default function processFunctionDefinition( const body = processBlockItem( node.body, funcSymbolTable, - functionDefinitionNode + functionDefinitionNode, ); functionDefinitionNode.body = body; // body is a Block, an array of StatementP will be returned return functionDefinitionNode; @@ -71,7 +71,7 @@ export default function processFunctionDefinition( */ export function processFunctionReturnStatement( expr: Expression, - symbolTable: SymbolTable + symbolTable: SymbolTable, ): StatementP[] { const statements: StatementP[] = []; const processedExpr = processExpression(expr, symbolTable); @@ -118,16 +118,15 @@ export function processFunctionReturnStatement( */ export function convertFunctionCallToFunctionCallP( node: FunctionCall, - symbolTable: SymbolTable + symbolTable: SymbolTable, ): { functionCallP: FunctionCallP; returnType: DataType | null } { - // direct call of a function if ( node.expr.type === "IdentifierExpression" && symbolTable.getSymbolEntry(node.expr.name).type === "function" ) { const symbolEntry = symbolTable.getSymbolEntry( - node.expr.name + node.expr.name, ) as FunctionSymbolEntry; return { functionCallP: { @@ -142,7 +141,7 @@ export function convertFunctionCallToFunctionCallP( // whereas indiviudal primary data types within larger aggergates go from low to high (reverse direction) (prv, expr) => prv.concat(processExpression(expr, symbolTable).exprs.reverse()), - [] as ExpressionP[] + [] as ExpressionP[], ), }, returnType: symbolEntry.dataType.returnType, @@ -168,13 +167,13 @@ export function convertFunctionCallToFunctionCallP( functionAddress: processedCalledExpr.exprs[0], }, functionDetails: - convertFunctionDataTypeToFunctionDetails(functionDataType), + convertFunctionDataTypeToFunctionDetails(functionDataType), args: node.args.reduce( // each inidividual expression is concatenated in reverse order, as stack grows from high to low, // whereas indiviudal primary data types within larger aggergates go from low to high (reverse direction) (prv, expr) => prv.concat(processExpression(expr, symbolTable).exprs.reverse()), - [] as ExpressionP[] + [] as ExpressionP[], ), }, }; diff --git a/ctowasm/src/processor/symbolTable.ts b/ctowasm/src/processor/symbolTable.ts index 1f8d2e2..2a48792 100644 --- a/ctowasm/src/processor/symbolTable.ts +++ b/ctowasm/src/processor/symbolTable.ts @@ -41,12 +41,12 @@ export interface VariableSymbolEntry { offset: number; // offset in number of bytes of this from the first byte of the first encountered symbol in the same function OR global scope } -export type FunctionTable = FunctionTableEntry[] +export type FunctionTable = FunctionTableEntry[]; export interface FunctionTableEntry { functionName: string; functionDetails: FunctionDetails; - isDefined: boolean // whether the given function has been defined + isDefined: boolean; // whether the given function has been defined } export class SymbolTable { @@ -54,7 +54,7 @@ export class SymbolTable { currOffset: { value: number }; // current offset saved as "value" in an object. Used to make it sharable as a reference across tables dataSegmentByteStr: { value: string }; // the string of bytes that forms the data segment dataSegmentOffset: { value: number }; // the current offset at data segment (address of next allocated data segment object) - functionTable: FunctionTableEntry[]; // list of all functions declared in the program in one table + functionTable: FunctionTableEntry[]; // list of all functions declared in the program in one table functionTableIndexes: Record; // map function name to index in functionTable for fast lookup symbols: Record; externalFunctions: Record; @@ -93,7 +93,7 @@ export class SymbolTable { */ setExternalFunctions( includedModules: ModuleName[], - moduleRepository: ModuleRepository + moduleRepository: ModuleRepository, ) { this.externalFunctions = {}; for (const moduleName of includedModules) { @@ -103,10 +103,10 @@ export class SymbolTable { funcName, moduleRepository.modules[moduleName].moduleFunctions[funcName] .functionType, - true + true, ); this.setFunctionIsDefinedFlag(funcName); - } + }, ); } return this.externalFunctions; @@ -128,20 +128,20 @@ export class SymbolTable { declaration.dataType, typeof declaration.initializer === "undefined" ? null - : declaration.initializer + : declaration.initializer, ); } return this.addVariableEntry( declaration.name, declaration.dataType, - declaration.storageClass + declaration.storageClass, ); } } addEnumeratorEntry( enumeratorName: string, - enumeratorValue: bigint + enumeratorValue: bigint, ): EnumeratorSymbolEntry { const entry: EnumeratorSymbolEntry = { type: "enumerator", @@ -162,7 +162,7 @@ export class SymbolTable { bytes.forEach((byte) => { this.dataSegmentByteStr.value += convertIntegerToByteString( BigInt(byte), - 1 + 1, ); }); const offset = this.dataSegmentOffset.value; @@ -173,7 +173,7 @@ export class SymbolTable { addVariableEntry( name: string, dataType: DataType, - storageClass: "auto" | "static" + storageClass: "auto" | "static", ): VariableSymbolEntry { if (name in this.symbols) { // given variable already exists in given scope @@ -192,8 +192,8 @@ export class SymbolTable { if (toJson(symbolEntry.dataType) !== toJson(dataType)) { throw new ProcessingError( `Conflicting types for ${name}: redeclared as ${symbolEntry} instead of ${toJson( - dataType - )}` + dataType, + )}`, ); //TODO: stringify there datatype in english instead of just printing json } return this.symbols[name] as VariableSymbolEntry; @@ -226,7 +226,7 @@ export class SymbolTable { }; } else { throw new ProcessingError( - "addVariableEntry(): Unhandled storage class" + "addVariableEntry(): Unhandled storage class", ); } } @@ -244,7 +244,7 @@ export class SymbolTable { // simple check that symbol is a function and the params and return types match if (this.symbols[name].type !== "function") { throw new ProcessingError( - `${name} redeclared as different kind of symbol: function instead of variable` + `${name} redeclared as different kind of symbol: function instead of variable`, ); } @@ -289,7 +289,11 @@ export class SymbolTable { this.symbols[name] = entry; } - this.functionTable.push({functionName: name, functionDetails: entry.functionDetails, isDefined: false}); + this.functionTable.push({ + functionName: name, + functionDetails: entry.functionDetails, + isDefined: false, + }); this.functionTableIndexes[name] = this.functionTable.length - 1; return entry; } diff --git a/ctowasm/src/processor/util.ts b/ctowasm/src/processor/util.ts index 1736915..4fcc989 100644 --- a/ctowasm/src/processor/util.ts +++ b/ctowasm/src/processor/util.ts @@ -8,13 +8,17 @@ import { Expression } from "~src/parser/c-ast/core"; import processExpression from "~src/processor/processExpression"; import { IntegerConstantP } from "~src/processor/c-ast/expression/constants"; import { isScalarDataType } from "~src/processor/dataTypeUtil"; -import { DataType, FunctionDataType, PointerDataType } from "~src/parser/c-ast/dataTypes"; +import { + DataType, + FunctionDataType, + PointerDataType, +} from "~src/parser/c-ast/dataTypes"; import { ExpressionWrapperP } from "~src/processor/c-ast/expression/expressions"; import { PTRDIFF_T } from "~src/common/constants"; export function processCondition( condition: Expression, - symbolTable: SymbolTable + symbolTable: SymbolTable, ) { const processedCondition = processExpression(condition, symbolTable); const dataTypeOfConditionExpression = getDataTypeOfExpression({ @@ -23,14 +27,14 @@ export function processCondition( }); if (!isScalarDataType(dataTypeOfConditionExpression)) { throw new ProcessingError( - `Cannot use ${dataTypeOfConditionExpression.type} where scalar is required` + `Cannot use ${dataTypeOfConditionExpression.type} where scalar is required`, ); } return processedCondition.exprs[0]; } export function createMemoryOffsetIntegerConstant( - offset: number + offset: number, ): IntegerConstantP { return { type: "IntegerConstant", @@ -62,7 +66,7 @@ export function getDataTypeOfExpression({ export function createFunctionTableIndexExpressionWrapper( functionName: string, functionDataType: FunctionDataType, - symbolTable: SymbolTable + symbolTable: SymbolTable, ): ExpressionWrapperP { const indexInFunctionTable = symbolTable.getFunctionIndex(functionName); return { @@ -80,22 +84,23 @@ export function createFunctionTableIndexExpressionWrapper( }; } - export function isFunctionPointer(dataType: DataType) { - return dataType.type === "pointer" && - dataType.pointeeType !== null && - dataType.pointeeType.type === "function" + return ( + dataType.type === "pointer" && + dataType.pointeeType !== null && + dataType.pointeeType.type === "function" + ); } /** * Extracts the FunctionDataType from a dataType which is a pointer to a f cuntion */ export function extractFunctionDataTypeFromFunctionPointer( - dataType: DataType + dataType: DataType, ): FunctionDataType { if (!isFunctionPointer(dataType)) { throw new ProcessingError( - "Called object is not a function or function pointer" + "Called object is not a function or function pointer", ); } diff --git a/ctowasm/src/translator/index.ts b/ctowasm/src/translator/index.ts index f1762b5..3084094 100644 --- a/ctowasm/src/translator/index.ts +++ b/ctowasm/src/translator/index.ts @@ -13,7 +13,7 @@ import ModuleRepository from "~src/modules"; export default function translate( CAstRoot: CAstRootP, - moduleRepository: ModuleRepository + moduleRepository: ModuleRepository, ) { const wasmRoot: WasmModule = { type: "Module", @@ -28,7 +28,7 @@ export default function translate( const processedImportedFunctions = processIncludedModules( moduleRepository, - CAstRoot.externalFunctions + CAstRoot.externalFunctions, ); wasmRoot.importedFunctions = processedImportedFunctions.functionImports; diff --git a/ctowasm/src/translator/memoryUtil.ts b/ctowasm/src/translator/memoryUtil.ts index cff812f..0768ecd 100644 --- a/ctowasm/src/translator/memoryUtil.ts +++ b/ctowasm/src/translator/memoryUtil.ts @@ -25,9 +25,9 @@ export const BASE_POINTER = "bp"; export const HEAP_POINTER = "hp"; // points to the address of first byte after heap export const REG_1 = "r1"; // general purpose register export const REG_2 = "r2"; -export const REG_I64 = "ri64" // gpr for i64 type -export const REG_F32 = "rf32" // gpr for f32 type -export const REG_F64 = "rf64" // gpr for f64 type +export const REG_I64 = "ri64"; // gpr for i64 type +export const REG_F32 = "rf32"; // gpr for f32 type +export const REG_F64 = "rf64"; // gpr for f64 type // Wasm AST node for getting the value of base pointer at run time export const basePointerGetNode: WasmGlobalGet = { diff --git a/ctowasm/src/translator/processImportedFunctions.ts b/ctowasm/src/translator/processImportedFunctions.ts index c744a31..3ff095b 100644 --- a/ctowasm/src/translator/processImportedFunctions.ts +++ b/ctowasm/src/translator/processImportedFunctions.ts @@ -46,7 +46,7 @@ export default function processImportedFunctions( wasmParams.push(convertScalarDataTypeToWasmType(scalarType.dataType)); } } - + console.assert( typeof importedFunction !== "undefined", "Translator: Imported function not found in module repository", @@ -64,7 +64,6 @@ export default function processImportedFunctions( ) : [], }); - // create the function wrapper // function wrapper needs to first load up function args into virtual wasm stack from the real stack in linear memory @@ -86,10 +85,11 @@ export default function processImportedFunctions( let externalCFunctionParamIndex = 0; for (const dataType of importedFunction.functionType.parameters) { const unpackedDataType = unpackDataType(dataType); // unpack the data type into series of primary object first - externalCFunctionParamIndex += unpackedDataType.length // the index of the next aggregate/primary param + externalCFunctionParamIndex += unpackedDataType.length; // the index of the next aggregate/primary param for (let i = 0; i < unpackedDataType.length; ++i) { - // the primary data type param corresponding to the param - const correspondingExternalFunctionParam = externalCFunction.parameters[externalCFunctionParamIndex - 1 - i]; + // the primary data type param corresponding to the param + const correspondingExternalFunctionParam = + externalCFunction.parameters[externalCFunctionParamIndex - 1 - i]; // sanity check, should not occur if ( unpackedDataType[i].dataType !== diff --git a/ctowasm/src/translator/translateExpression.ts b/ctowasm/src/translator/translateExpression.ts index dae55cd..a5bcab2 100644 --- a/ctowasm/src/translator/translateExpression.ts +++ b/ctowasm/src/translator/translateExpression.ts @@ -134,7 +134,11 @@ export default function translateExpression( wasmDataType: convertScalarDataTypeToWasmType(expr.dataType), }; } else if (expr.type === "FunctionTableIndex") { - return translateExpression(expr.index, POINTER_TYPE, enclosingLoopDetails); // translate the underlying integer constant + return translateExpression( + expr.index, + POINTER_TYPE, + enclosingLoopDetails, + ); // translate the underlying integer constant } else { throw new TranslationError(`Unhandled expression: ${toJson(expr)}`); } diff --git a/ctowasm/src/translator/translateFunctionCall.ts b/ctowasm/src/translator/translateFunctionCall.ts index 2efff58..24be3a4 100644 --- a/ctowasm/src/translator/translateFunctionCall.ts +++ b/ctowasm/src/translator/translateFunctionCall.ts @@ -8,9 +8,12 @@ import { } from "~src/translator/memoryUtil"; import translateExpression from "~src/translator/translateExpression"; import { WasmExpression } from "~src/translator/wasm-ast/core"; -import { WasmFunctionCall, WasmIndirectFunctionCall } from "~src/translator/wasm-ast/functions"; +import { + WasmFunctionCall, + WasmIndirectFunctionCall, +} from "~src/translator/wasm-ast/functions"; import { FunctionCallP } from "~src/processor/c-ast/function"; -import { TranslationError, UnsupportedFeatureError } from "~src/errors"; +import { TranslationError } from "~src/errors"; import { POINTER_TYPE } from "~src/common/constants"; export default function translateFunctionCall( @@ -18,11 +21,7 @@ export default function translateFunctionCall( ): WasmFunctionCall | WasmIndirectFunctionCall { // translate the arguments const functionArgs: WasmExpression[] = []; - for ( - let i = 0; - i < node.functionDetails.parameters.length; - ++i - ) { + for (let i = 0; i < node.functionDetails.parameters.length; ++i) { functionArgs.push( translateExpression( node.args[i], @@ -38,24 +37,27 @@ export default function translateFunctionCall( const stackFrameTearDown = getFunctionCallStackFrameTeardownStatements( node.functionDetails, - ) + ); if (node.calledFunction.type === "DirectlyCalledFunction") { return { type: "FunctionCall", name: node.calledFunction.functionName, stackFrameSetup, - stackFrameTearDown + stackFrameTearDown, }; } else if (node.calledFunction.type === "IndirectlyCalledFunction") { return { type: "IndirectFunctionCall", - index: translateExpression(node.calledFunction.functionAddress, POINTER_TYPE), + index: translateExpression( + node.calledFunction.functionAddress, + POINTER_TYPE, + ), stackFrameSetup, - stackFrameTearDown - } + stackFrameTearDown, + }; } else { - console.assert(false, "translateFunctionCall(): unreachable block") + console.assert(false, "translateFunctionCall(): unreachable block"); throw new TranslationError(""); } } diff --git a/ctowasm/src/translator/util.ts b/ctowasm/src/translator/util.ts index b81edd3..2368685 100644 --- a/ctowasm/src/translator/util.ts +++ b/ctowasm/src/translator/util.ts @@ -27,9 +27,7 @@ import { WasmBooleanExpression } from "~src/translator/wasm-ast/expressions"; import { ExpressionP } from "~src/processor/c-ast/core"; import translateExpression from "~src/translator/translateExpression"; import { FunctionTable } from "~src/processor/symbolTable"; -import { - WasmFunctionTable, -} from "~src/translator/wasm-ast/functionTable"; +import { WasmFunctionTable } from "~src/translator/wasm-ast/functionTable"; import { calculateNumberOfPagesNeededForBytes } from "~src/common/utils"; /** @@ -37,7 +35,7 @@ import { calculateNumberOfPagesNeededForBytes } from "~src/common/utils"; */ export function arithmeticUnaryOperatorToInstruction( op: ArithemeticUnaryOperator, - dataType: DataType + dataType: DataType, ) { if (dataType.type === "primary") { return `${priamryCDataTypeToWasmType[dataType.primaryDataType]}.${ @@ -49,8 +47,8 @@ export function arithmeticUnaryOperatorToInstruction( // arithmetic is not defined for non ints or non pointers throw new TranslationError( `arithmeticUnaryOperatorToInstruction(): Unsupported variable type: ${toJson( - dataType - )}` + dataType, + )}`, ); } } @@ -69,9 +67,7 @@ export const wasmTypeToSize: Record = { * @param stackPreallocate the amount of space in bytes to preallocate before intitial stack pointer position * @param dataSegmentSize the size of the data segment in memory */ -export function setPseudoRegisters( - wasmRoot: WasmModule, -) { +export function setPseudoRegisters(wasmRoot: WasmModule) { // imported from JS runtime wasmRoot.importedGlobalWasmVariables.push({ type: "ImportedGlobalVariable", @@ -86,7 +82,10 @@ export function setPseudoRegisters( initializerValue: { type: "IntegerConst", wasmDataType: "i32", - value: BigInt(calculateNumberOfPagesNeededForBytes(wasmRoot.dataSegmentSize) * WASM_PAGE_SIZE), // BP starts at the memory boundary + value: BigInt( + calculateNumberOfPagesNeededForBytes(wasmRoot.dataSegmentSize) * + WASM_PAGE_SIZE, + ), // BP starts at the memory boundary }, }); @@ -179,7 +178,7 @@ export function getMaxIntConstant(intType: "i32" | "i64"): WasmIntegerConst { */ export function createWasmBooleanExpression( expression: ExpressionP, - isNegated?: boolean + isNegated?: boolean, ): WasmBooleanExpression { return { type: "BooleanExpression", @@ -191,7 +190,7 @@ export function createWasmBooleanExpression( export function createIntegerConst( value: number, - wasmDataType: WasmIntType + wasmDataType: WasmIntType, ): WasmIntegerConst { return { type: "IntegerConst", @@ -201,7 +200,7 @@ export function createIntegerConst( } export function createWasmFunctionTable( - functionTable: FunctionTable + functionTable: FunctionTable, ): WasmFunctionTable { const wasmFunctionTable: WasmFunctionTable = { elements: [], diff --git a/ctowasm/src/translator/wasm-ast/core.ts b/ctowasm/src/translator/wasm-ast/core.ts index 671557b..445da40 100644 --- a/ctowasm/src/translator/wasm-ast/core.ts +++ b/ctowasm/src/translator/wasm-ast/core.ts @@ -52,7 +52,7 @@ export interface WasmModule extends WasmAstNode { type: "Module"; dataSegmentByteStr: string; // string of bytes to set the data segment with globalWasmVariables: WasmGlobalVariable[]; - importedGlobalWasmVariables: WasmImportedGlobalVariable[] + importedGlobalWasmVariables: WasmImportedGlobalVariable[]; functions: Record; dataSegmentSize: number; // number of bytes of data segment importedFunctions: WasmImportedFunction[]; diff --git a/ctowasm/src/translator/wasm-ast/functionTable.ts b/ctowasm/src/translator/wasm-ast/functionTable.ts index bb2d0ab..8e16c1c 100644 --- a/ctowasm/src/translator/wasm-ast/functionTable.ts +++ b/ctowasm/src/translator/wasm-ast/functionTable.ts @@ -1,10 +1,10 @@ // all functions have the the same type (no params, no return) due to the memory model export interface WasmFunctionTable { - elements: WasmFunctionTableEntry[] // functions in the table + elements: WasmFunctionTableEntry[]; // functions in the table size: number; // size of the table - undefined functions may contribute to this size } export interface WasmFunctionTableEntry { - functionName: string, // label of the functions - index: number + functionName: string; // label of the functions + index: number; } diff --git a/ctowasm/src/translator/wasm-ast/functions.ts b/ctowasm/src/translator/wasm-ast/functions.ts index d67f58b..d9beb54 100644 --- a/ctowasm/src/translator/wasm-ast/functions.ts +++ b/ctowasm/src/translator/wasm-ast/functions.ts @@ -3,9 +3,12 @@ */ import { WasmMemoryLoad } from "~src/translator/wasm-ast/memory"; -import { WasmStatement, WasmAstNode, WasmExpression } from "~src/translator/wasm-ast/core"; +import { + WasmStatement, + WasmAstNode, + WasmExpression, +} from "~src/translator/wasm-ast/core"; import { WasmDataType } from "~src/translator/wasm-ast/dataTypes"; -import { WasmIntegerConst } from "~src/translator/wasm-ast/consts"; export type WasmFunctionBodyLine = WasmStatement; @@ -63,4 +66,4 @@ export interface WasmImportedFunction { importPath: string[]; // import path for function e.g: ["console", "log"] wasmParamTypes: WasmDataType[]; // the params of the functions in wasm returnWasmTypes: WasmDataType[]; -} \ No newline at end of file +} diff --git a/ctowasm/src/wat-generator/constants.ts b/ctowasm/src/wat-generator/constants.ts index d091dd0..a6a7a8b 100644 --- a/ctowasm/src/wat-generator/constants.ts +++ b/ctowasm/src/wat-generator/constants.ts @@ -1 +1 @@ -export const FUNCTION_TYPE_LABEL = "$func_type" \ No newline at end of file +export const FUNCTION_TYPE_LABEL = "$func_type"; diff --git a/ctowasm/src/wat-generator/generateWatStatement.ts b/ctowasm/src/wat-generator/generateWatStatement.ts index e37c339..69be3bb 100644 --- a/ctowasm/src/wat-generator/generateWatStatement.ts +++ b/ctowasm/src/wat-generator/generateWatStatement.ts @@ -1,5 +1,4 @@ import { WatGeneratorError, toJson } from "~src/errors"; -import { REG_2 } from "~src/translator/memoryUtil"; import { WasmSelectionStatement } from "~src/translator/wasm-ast/control"; import { WasmStatement } from "~src/translator/wasm-ast/core"; import { FUNCTION_TYPE_LABEL } from "~src/wat-generator/constants"; @@ -25,9 +24,11 @@ export default function generateWatStatement(node: WasmStatement): string { node.stackFrameSetup, )}) ${generateStatementsList(node.stackFrameTearDown)}`; } else if (node.type === "IndirectFunctionCall") { - return `(call_indirect (type ${FUNCTION_TYPE_LABEL}) ${generateWatExpression(node.index)} ${generateStatementsList( + return `(call_indirect (type ${FUNCTION_TYPE_LABEL}) ${generateWatExpression( + node.index, + )} ${generateStatementsList( node.stackFrameSetup, - )}) ${generateStatementsList(node.stackFrameTearDown)}` + )}) ${generateStatementsList(node.stackFrameTearDown)}`; } else if (node.type === "RegularFunctionCall") { return `(call $${node.name}${generateArgString(node.args)})`; } else if (node.type === "SelectionStatement") { @@ -77,7 +78,11 @@ export default function generateWatStatement(node: WasmStatement): string { return `(${getWasmMemoryStoreInstruction( node.wasmDataType, node.numOfBytes, - )} (global.set $${getTempRegister(node.wasmDataType)}) ${generateWatExpression(node.addr)} (global.get $${getTempRegister(node.wasmDataType)}))`; + )} (global.set $${getTempRegister( + node.wasmDataType, + )}) ${generateWatExpression(node.addr)} (global.get $${getTempRegister( + node.wasmDataType, + )}))`; } else if (node.type === "BranchTable") { return generateBranchTableInstruction(node); } else { diff --git a/ctowasm/src/wat-generator/index.ts b/ctowasm/src/wat-generator/index.ts index 9bca400..2ced469 100644 --- a/ctowasm/src/wat-generator/index.ts +++ b/ctowasm/src/wat-generator/index.ts @@ -13,8 +13,10 @@ export function generateWat(module: WasmModule, baseIndentation: number = 0) { // add the memory import watStr += generateLine( - `(import "js" "mem" (memory ${calculateNumberOfPagesNeededForBytes(module.dataSegmentSize)}))`, - baseIndentation + 1 + `(import "js" "mem" (memory ${calculateNumberOfPagesNeededForBytes( + module.dataSegmentSize, + )}))`, + baseIndentation + 1, ); // add the imported functions @@ -37,7 +39,7 @@ export function generateWat(module: WasmModule, baseIndentation: number = 0) { .join(" ") : "" }))`, - baseIndentation + 1 + baseIndentation + 1, ); } @@ -48,7 +50,7 @@ export function generateWat(module: WasmModule, baseIndentation: number = 0) { }") (${importedGlobal.isConst ? "" : "mut"} ${ importedGlobal.wasmDataType }))`, - baseIndentation + 1 + baseIndentation + 1, ); } @@ -62,33 +64,33 @@ export function generateWat(module: WasmModule, baseIndentation: number = 0) { ? generateWatExpression(global.initializerValue) : "" })`, - baseIndentation + 1 + baseIndentation + 1, ); } // add all the global variables (in linear memory) intiializations watStr += generateLine( `(data (i32.const 0) "${module.dataSegmentByteStr}")`, - baseIndentation + 1 + baseIndentation + 1, ); // add the table of functions watStr += generateLine( `(table ${module.functionTable.size} funcref)`, - baseIndentation + 1 + baseIndentation + 1, ); // add the type of all user defined functions (to wasm the functions simply take no params, no return (memory model handles these)) watStr += generateLine( `(type ${FUNCTION_TYPE_LABEL} (func))`, - baseIndentation + 1 + baseIndentation + 1, ); // add all functions into the table for (const f of module.functionTable.elements) { watStr += generateLine( `(elem (i32.const ${f.index}) $${f.functionName})`, - baseIndentation + 1 + baseIndentation + 1, ); } @@ -99,7 +101,7 @@ export function generateWat(module: WasmModule, baseIndentation: number = 0) { for (const statement of func.body) { watStr += generateLine( generateWatStatement(statement), - baseIndentation + 2 + baseIndentation + 2, ); } watStr += generateLine(")", baseIndentation + 1); diff --git a/ctowasm/src/wat-generator/util.ts b/ctowasm/src/wat-generator/util.ts index 6245201..eb9cb5a 100644 --- a/ctowasm/src/wat-generator/util.ts +++ b/ctowasm/src/wat-generator/util.ts @@ -33,7 +33,7 @@ export function generateBlock(block: string, indentation: number) { */ export function getWasmMemoryLoadInstruction( varType: WasmDataType, - numOfBytes: number + numOfBytes: number, ) { if ( ((varType === "i32" || varType === "f32") && numOfBytes === 4) || @@ -46,7 +46,7 @@ export function getWasmMemoryLoadInstruction( export function getWasmMemoryStoreInstruction( varType: WasmDataType, - numOfBytes: number + numOfBytes: number, ) { if ( ((varType === "i32" || varType === "f32") && numOfBytes === 4) || @@ -86,7 +86,7 @@ export function generateBranchTableInstruction(branchTable: WasmBranchTable) { indexes += `${i} `; } return `(br_table ${indexes}${generateWatExpression( - branchTable.indexExpression + branchTable.indexExpression, )})`; }