Skip to content

Commit

Permalink
Fix small function pointer bug; add more complex test case
Browse files Browse the repository at this point in the history
  • Loading branch information
benmurphyy committed Feb 5, 2024
1 parent af854d2 commit 7dfb47c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
3 changes: 2 additions & 1 deletion ctowasm/src/processor/processFunctionDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export function convertFunctionCallToFunctionCallP(
node: FunctionCall,
symbolTable: SymbolTable
): { functionCallP: FunctionCallP; returnType: DataType | null } {

// direct call of a function
if (
node.expr.type === "IdentifierExpression" &&
Expand Down Expand Up @@ -159,7 +160,7 @@ export function convertFunctionCallToFunctionCallP(
extractFunctionDataTypeFromFunctionPointer(dataTypeOfCalledExpr);

return {
returnType: dataTypeOfCalledExpr,
returnType: functionDataType.returnType,
functionCallP: {
type: "FunctionCall",
calledFunction: {
Expand Down
39 changes: 39 additions & 0 deletions ctowasm/test/samples/subset5/valid/function_pointers_2.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Test advanced practical usage of function pointers
#include <source_stdlib>

int ARR_LENGTH = 8;
int arr[] = {2, 1, 4, 11, 23, 5, -10, -200};

// sort will sort arr using cmp
// cmp is a function that returns 3 way comparison between two ints
void sort(int (*cmp)(int, int)) {
for (int i = 1; i < ARR_LENGTH; ++i) {
int j = i;
while (j > 0 && cmp(arr[j - 1], arr[j]) > 0) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
}

int asc(int a, int b) {
return a - b;
}

int desc(int a, int b) {
return b - a;
}

int main() {
int (*cmp_arr[2])(int, int) = {asc, desc};
for (int i = 0; i < 2; i++) {
sort(cmp_arr[i]);
print_string("Sorted output");
for (int j = 0; j < ARR_LENGTH; ++j) {
print_int(arr[j]);
}
print_string("End of sorted output");
}
}

0 comments on commit 7dfb47c

Please sign in to comment.