Skip to content

Commit

Permalink
add conversions for function return values
Browse files Browse the repository at this point in the history
  • Loading branch information
caipng committed Apr 29, 2024
1 parent f9cd520 commit 99185e6
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/ast/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
TypeInfo,
Void,
int,
FunctionReturnType
} from "../typing/types";

export interface PositionInfo {
Expand Down Expand Up @@ -406,6 +407,7 @@ export const isJumpStatementReturn = (i: BaseNode): i is JumpStatementReturn =>
export interface TypedJumpStatementReturn extends BaseNode {
type: "JumpStatementReturn";
value: TypedExpression | null;
expectedReturnType: FunctionReturnType;
}

export interface JumpStatementContinue extends BaseNode {
Expand Down
12 changes: 9 additions & 3 deletions src/interpreter/evaluators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,16 @@ export const ASTNodeEvaluator: {
},
JumpStatementReturn: (
rt: Runtime,
{ value: expr }: TypedJumpStatementReturn,
{ value: expr, expectedReturnType }: TypedJumpStatementReturn,
) => {
rt.agenda.push(returnInstruction());
if (expr) rt.agenda.push(expr);
if (expr) {
if (!expr.typeInfo.isCompatible(expectedReturnType))
// not possible to be void as expr is not null
// not possible to be a struct that is not compatible as type check would fail
rt.agenda.push(castInstruction(expectedReturnType as ScalarType));
rt.agenda.push(expr);
}
},
JumpStatementBreak: (rt: Runtime) => {
jumpTill(rt, isBreakMarkInstruction);
Expand Down Expand Up @@ -1358,4 +1364,4 @@ const jumpTill = (rt: Runtime, pred: (i: AgendaItem) => boolean): void => {
if (isExitBlockInstruction(t)) instructionEvaluator[t.type](rt, t);
}
rt.agenda.pop();
}
}
4 changes: 2 additions & 2 deletions src/typing/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ const typeJumpStatementReturn = (
if (isVoid(expectedReturnType)) {
if (t.value)
throw "non-empty return statement in function declared with void return type";
return { ...t, value: null };
return { ...t, value: null, expectedReturnType };
}

if (!t.value)
Expand All @@ -508,7 +508,7 @@ const typeJumpStatementReturn = (
)
throw "wrong return type";

return { ...t, value: expr };
return { ...t, value: expr, expectedReturnType };
});

const typeIterationStatement = (
Expand Down

0 comments on commit 99185e6

Please sign in to comment.