Skip to content

Commit

Permalink
Add timeout on repeat loop
Browse files Browse the repository at this point in the history
  • Loading branch information
iHiD committed Jan 14, 2025
1 parent 886b06b commit ec07c01
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 3 deletions.
1 change: 1 addition & 0 deletions app/javascript/interpreter/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export type RuntimeErrorType =
| 'InvalidExpression'
| 'RepeatCountMustBeNumber'
| 'RepeatCountMustBeGreaterThanZero'
| 'RepeatCountMustBeLessThanOneThousand'
| 'NonCallableTarget'
| 'InfiniteLoop'
| 'TooFewArguments'
Expand Down
17 changes: 15 additions & 2 deletions app/javascript/interpreter/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,15 +260,28 @@ export class Executor
this.evaluate(statement.count)
)

if (!isNumber(count))
if (!isNumber(count)) {
this.error('RepeatCountMustBeNumber', statement.count.location, {
count,
})
}

if (count < 1)
if (count < 1) {
this.error('RepeatCountMustBeGreaterThanZero', statement.count.location, {
count,
})
}

if (count > 1000) {
console.log('HERE')
this.error(
'RepeatCountMustBeLessThanOneThousand',
statement.count.location,
{
count,
}
)
}

while (count > 0) {
this.executeBlock(statement.body, this.environment)
Expand Down
3 changes: 2 additions & 1 deletion app/javascript/interpreter/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@
"OperandMustBeNumber": "Operand must be a number.",
"OperandsMustBeNumber": "Operands must be numbers.",
"OperandsMustBeTwoNumbersOrTwoStrings": "Operands must be two numbers or two strings.",
"RepeatCountMustBeGreaterThanZero": "The repeat argument must be greater than zero.",
"RepeatCountMustBeGreaterThanZero": "You must repeat things at least once.",
"RepeatCountMustBeLessThanOneThousand": "The most times you can repeat things is 1000.",
"RepeatCountMustBeNumber": "repeat can only take a number as its argument.",
"VariableAlreadyDeclared": "A variable with this name has already been created. Did you mean to use the <code>change</code> keyword?"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,20 @@ describe('statements', () => {
expect(frames[4].status).toBe('SUCCESS')
expect(frames[4].variables).toMatchObject({ x: 3 })
})
test('must be 1000 times or fewer', () => {
const { error, frames } = interpret(`
repeat 1001 times do
end
`)
expect(frames).toBeArrayOfSize(2)

expect(frames[1].line).toBe(2)
expect(frames[1].status).toBe('ERROR')
expect(frames[1].code).toBe('1001')
expect(frames[1].error).not.toBeNull()
expect(frames[1].error!.category).toBe('RuntimeError')
expect(frames[1].error!.type).toBe('RepeatCountMustBeLessThanOneThousand')
})
})

describe('while', () => {
Expand Down

0 comments on commit ec07c01

Please sign in to comment.