Skip to content

Commit

Permalink
For range
Browse files Browse the repository at this point in the history
  • Loading branch information
rtoal committed May 2, 2024
1 parent 0c5b581 commit e7e50a3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 25 deletions.
10 changes: 8 additions & 2 deletions src/analyzer.js
Original file line number Diff line number Diff line change
Expand Up @@ -489,12 +489,18 @@ export default function analyze(match) {
const [low, high] = [exp1.rep(), exp2.rep()]
mustHaveIntegerType(low, { at: exp1 })
mustHaveIntegerType(high, { at: exp2 })
const iterator = core.variable(id.sourceString, INT, true)
const iterator = core.variable(id.sourceString, INT)
context = context.newChildContext({ inLoop: true })
context.add(id.sourceString, iterator)
const body = block.rep()
context = context.parent
return core.forRangeStatement(iterator, low, op, high, body)
return core.forRangeStatement(
iterator,
low,
op.sourceString,
high,
body
)
},

Block(_open, statements, _close) {
Expand Down
5 changes: 2 additions & 3 deletions src/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,9 @@ export default function generate(program) {
},
ForRangeStatement(s) {
const i = targetName(s.iterator)
const op = s.op === '..'
output.push(
`for (let ${i} = ${gen(s.low)}; ${i} ${op} ${gen(
s.high
`for (let ${i} = ${gen(s.start)}; ${i} <= ${gen(
s.end
)}; ${i}++) {`
)
s.body.forEach(gen)
Expand Down
39 changes: 19 additions & 20 deletions test/generator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,26 +159,25 @@ const fixtures = [
`,
},

// Not synactically correct yet - loop over array not implemented
// {
// name: "for loops",
// source:`
// for i in 1 .. 50 {
// print i;
// }
// for j in [10, 20, 30] {
// print j;
// }
// `,
// expected: dedent`
// for (let i_1 = 1; i_1 < 50; i_1++) {
// console.log(i_1);
// }
// for (let j_2 of [10,20,30]) {
// console.log(j_2);
// }
// `,
// },
{
name: 'for loops',
source: `
for i in 1 .. 50 {
print i;
}
for j in [10, 20, 30] {
print j;
}
`,
expected: dedent`
for (let i_1 = 1; i_1 < 50; i_1++) {
console.log(i_1);
}
for (let j_2 of [10,20,30]) {
console.log(j_2);
}
`,
},
]

describe('The code generator', () => {
Expand Down

0 comments on commit e7e50a3

Please sign in to comment.