calcium-lang
Version:
Calcium language interpreter
56 lines • 2 kB
JavaScript
import LoopCounter from "../runtime/loopCounter";
import retrieveValue from "../util/retrieveValue";
import { Block, Kind, Result } from "../runtime/block";
import { createInt } from "../factory";
/**
* `for i in range(start, stop, step):` loop
*/
export default class ForRange {
/**
*
* @param varName a counter variable
* @param start start from the value (default 0)
* @param stop stop to the value
* @param step step by the value (default 1)
*/
constructor(varName, start, stop, step) {
this.varName = varName;
this.start = start;
this.stop = stop;
this.step = step;
}
execute(env) {
let loopCounter;
const stopValue = retrieveValue(this.stop, env);
if (this.start === null && this.step === null) {
// e.g. for i in range(10):
loopCounter = new LoopCounter(0, stopValue, 1);
}
else if (this.start !== null && this.step === null) {
// e.g. for i in range(1, 11):
const startValue = retrieveValue(this.start, env);
loopCounter = new LoopCounter(startValue, stopValue, 1);
}
else if (this.start !== null && this.step !== null) {
// e.g. for i in range(0, 22, 2):
const startValue = retrieveValue(this.start, env);
const stepValue = retrieveValue(this.step, env);
loopCounter = new LoopCounter(startValue, stopValue, stepValue);
}
const block = new Block(Kind.ForRange, env.address, (env) => {
const nextValue = loopCounter.next();
if (nextValue !== null) {
env.context.register(this.varName, createInt(nextValue));
return true;
}
else {
return false;
}
}, (env) => {
block.willEnter(env);
return Result.Jumpped;
});
block.willEnter(env);
}
}
//# sourceMappingURL=forRange.js.map