Skip to content

Commit

Permalink
Lint and prettify
Browse files Browse the repository at this point in the history
  • Loading branch information
benmurphyy committed Feb 10, 2024
1 parent 8b02bb1 commit b2e8138
Show file tree
Hide file tree
Showing 30 changed files with 232 additions and 185 deletions.
2 changes: 1 addition & 1 deletion ctowasm/src/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
export const ENUM_DATA_TYPE = "signed int"; // the datatype that enum directly corresponds to in this compiler implementation
2 changes: 1 addition & 1 deletion ctowasm/src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,4 @@ export function isConstant(node: CNodeBase) {
*/
export function calculateNumberOfPagesNeededForBytes(numBytes: number) {
return Math.floor(numBytes / WASM_PAGE_SIZE) + 1;
}
}
13 changes: 8 additions & 5 deletions ctowasm/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export interface CompilationResult {

export async function compile(
cSourceCode: string,
moduleRepository: ModuleRepository
moduleRepository: ModuleRepository,
): Promise<CompilationResult> {
try {
const CAst = parse(cSourceCode, moduleRepository);
Expand All @@ -39,7 +39,7 @@ export async function compile(

export function compileToWat(
cSourceCode: string,
moduleRepository: ModuleRepository
moduleRepository: ModuleRepository,
) {
try {
const CAst = parse(cSourceCode, moduleRepository);
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand Down
9 changes: 6 additions & 3 deletions ctowasm/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
20 changes: 15 additions & 5 deletions ctowasm/src/modules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default class ModuleRepository {
config: ModulesGlobalConfig;
modules: Record<ModuleName, Module>;
sharedWasmGlobalVariables: SharedWasmGlobalVariables;

constructor(memory?: WebAssembly.Memory, config?: ModulesGlobalConfig) {
if (memory) {
this.memory = memory; // initially memory starts at 0
Expand All @@ -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,
),
};
}
Expand All @@ -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) => {
Expand Down
8 changes: 4 additions & 4 deletions ctowasm/src/modules/source_stdlib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand Down Expand Up @@ -275,7 +275,7 @@ export class SourceStandardLibraryModule extends Module {
printHeap(
this.memory,
this.heapAddress,
this.sharedWasmGlobalVariables.heapPointer.value
this.sharedWasmGlobalVariables.heapPointer.value,
),
},
print_stack: {
Expand All @@ -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
Expand Down
10 changes: 5 additions & 5 deletions ctowasm/src/modules/source_stdlib/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Expand All @@ -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);
}
}
6 changes: 5 additions & 1 deletion ctowasm/src/parser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
Expand Down
6 changes: 3 additions & 3 deletions ctowasm/src/processor/c-ast/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion ctowasm/src/processor/c-ast/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 19 additions & 17 deletions ctowasm/src/processor/dataTypeUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;
}
10 changes: 5 additions & 5 deletions ctowasm/src/processor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,21 @@ 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",
functions: [],
dataSegmentByteStr: "",
dataSegmentSizeInBytes: 0,
externalFunctions: [],
functionTable: []
functionTable: [],
};

// save the processed details of external functions
Expand All @@ -49,15 +49,15 @@ export default function process(
processedExternalFunctions[moduleFunctionName].functionDetails
.returnObjects,
});
}
},
);
}

ast.children.forEach((child) => {
// special handling for function definitions
if (child.type === "FunctionDefinition") {
processedAst.functions.push(
processFunctionDefinition(child, symbolTable)
processFunctionDefinition(child, symbolTable),
);
} else {
processGlobalScopeDeclaration(child, symbolTable);
Expand Down
4 changes: 3 additions & 1 deletion ctowasm/src/processor/processBlockItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading

0 comments on commit b2e8138

Please sign in to comment.