Skip to content

Commit

Permalink
CR
Browse files Browse the repository at this point in the history
  • Loading branch information
netalondon committed Sep 16, 2024
1 parent 48d1591 commit bd613da
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 11 deletions.
18 changes: 8 additions & 10 deletions simulator/src/jack/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ import {
isPrimitive,
} from "../languages/jack.js";
import { Segment } from "../languages/vm.js";
import { VM_BUILTINS } from "../vm/builtins.js";
import {
VM_BUILTINS,
makeInterface,
overridesOsCorrectly,
} from "../vm/builtins.js";
import { validateSubroutine } from "./controlFlow.js";

const osClasses = new Set([
Expand Down Expand Up @@ -299,16 +303,10 @@ export class Compiler {

if (isOsClass(this.className)) {
const builtin = VM_BUILTINS[`${this.className}.${subroutine.name.value}`];
const argTypes = subroutine.parameters.map((arg) => arg.type.value);

if (
builtin &&
(builtin.args.length != argTypes.length ||
builtin.args.some((arg, index) => arg != argTypes[index]) ||
builtin.returnType != subroutine.returnType.value)
) {

if (builtin && !overridesOsCorrectly(this.className, subroutine)) {
throw createError(
`OS subroutine ${this.className}.${subroutine.name.value} must follow the interface ${builtin.returnType} ${subroutine.name.value}(${builtin.args.join(",")})`,
`OS subroutine ${this.className}.${subroutine.name.value} must follow the interface ${makeInterface(subroutine.name.value, builtin)})`,
);
}
}
Expand Down
24 changes: 23 additions & 1 deletion simulator/src/vm/builtins.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { ReturnType, SubroutineType, Type } from "../languages/jack.js";
import {
ReturnType,
Subroutine,
SubroutineType,
Type,
} from "../languages/jack.js";
import { VmMemory } from "./memory.js";
import { ERRNO } from "./os/errors.js";
import { OS } from "./os/os.js";
Expand All @@ -21,6 +26,23 @@ function getArgs(memory: VmMemory, n: number) {
return args;
}

export function overridesOsCorrectly(cls: string, subroutine: Subroutine) {
const builtin = VM_BUILTINS[`${cls}.${subroutine.name.value}`];

return (
builtin &&
builtin.args.length == subroutine.parameters.length &&
builtin.args.every(
(arg, index) => arg == subroutine.parameters[index].type.value,
) &&
builtin.returnType == subroutine.returnType.value
);
}

export function makeInterface(name: string, builtin: VmBuiltin) {
return `${builtin.returnType} ${name}(${builtin.args.join(",")}`;
}

export const VM_BUILTINS: Record<string, VmBuiltin> = {
"Math.multiply": {
func: (memory, _) => {
Expand Down

0 comments on commit bd613da

Please sign in to comment.