diff --git a/packages/struktolab/src/common/code-generator.js b/packages/struktolab/src/common/code-generator.js index 8870104..1d6f3c1 100644 --- a/packages/struktolab/src/common/code-generator.js +++ b/packages/struktolab/src/common/code-generator.js @@ -16,8 +16,9 @@ const TRANSLATIONS = { HeadLoopNode: { pre: "while ", post: ":\n" }, FootLoopNode: { prepre: "while True:\n", - pre: " if not ", - post: ":\n break\n", + pre: "if not ", + post: ":\n", + postpost: "break\n", }, FunctionNode: { pre: "def ", between: "(", post: "):\n" }, CaseNode: { pre: "if ", post: ":\n" }, @@ -228,8 +229,9 @@ function transform(node, level, t, lang) { if (t.pseudoSwitch) { // Python: the pre/post contain the break logic lines.push( - indent(level) + t.FootLoopNode.pre + text + t.FootLoopNode.post, + indent(level + 1) + t.FootLoopNode.pre + text + t.FootLoopNode.post, ); + lines.push(indent(level + 2) + t.FootLoopNode.postpost); } else { if (t.rightBracket) lines.push(indent(level) + t.rightBracket + " "); lines.push(t.FootLoopNode.pre + text + t.FootLoopNode.post); diff --git a/packages/struktolab/src/common/code-generator.test.js b/packages/struktolab/src/common/code-generator.test.js new file mode 100644 index 0000000..301ed29 --- /dev/null +++ b/packages/struktolab/src/common/code-generator.test.js @@ -0,0 +1,14 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { generateCode } from "./code-generator.js"; +import { KEYWORDS_EN, parsePseudocode } from "./pseudocode-parser.js"; + +const python = (code) => generateCode(parsePseudocode(code, KEYWORDS_EN), "python"); + +test("indents the break of a nested foot loop in Python", () => { + const code = "function f(n):\n repeat:\n n = n - 1\n while n > 0"; + assert.equal( + python(code), + "def f(n):\n while True:\n n = n - 1\n if not n > 0:\n break\n", + ); +});