Skip to content

Commit

Permalink
Check for looping wires when building chip (#401)
Browse files Browse the repository at this point in the history
  • Loading branch information
netalondon authored Jul 11, 2024
1 parent 0847275 commit 7703bc8
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
19 changes: 19 additions & 0 deletions simulator/src/chip/builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,25 @@ describe("Chip Builder", () => {
throw new Error(display(e.message ?? e.shortMessage ?? e));
}
});

it("returns error for wire loop", async () => {
try {
const chip = unwrap(
HDL.parse(`CHIP Not {
IN in;
OUT out;
PARTS:
Nand(a=in, b=myNand, out=myNand);
}`),
);
const foo = await build(chip);
expect(foo).toBeErr();

// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
throw new Error(display(e.message ?? e.shortMessage ?? e));
}
});
});

const USE_COPY_HDL = `CHIP UseCopy {
Expand Down
36 changes: 36 additions & 0 deletions simulator/src/chip/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,43 @@ class ChipBuilder {
return Ok();
}

private checkLoops(
part: Part,
partChip: Chip,
): Result<void, CompilationError> {
const ins = new Set<string>();
const outs = new Set<string>();

let loop: string | undefined = undefined;
for (const { lhs, rhs } of part.wires) {
if (partChip.isInPin(lhs.pin)) {
if (outs.has(rhs.pin)) {
loop = rhs.pin;
break;
} else {
ins.add(rhs.pin);
}
} else if (partChip.isOutPin(lhs.pin)) {
if (ins.has(rhs.pin)) {
loop = rhs.pin;
break;
} else {
outs.add(rhs.pin);
}
}
}
if (loop) {
return Err(createError(`Looping wire ${loop}`, part.span));
}
return Ok();
}

private wirePart(part: Part, partChip: Chip): Result<void, CompilationError> {
const result = this.checkLoops(part, partChip);
if (isErr(result)) {
return result;
}

const connections: Connection[] = [];
this.inPins.clear();
for (const { lhs, rhs } of part.wires) {
Expand Down

0 comments on commit 7703bc8

Please sign in to comment.