Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3635133x 3635133x 3635133x 3635133x 3635133x 45951554x 45951554x 18461541x 18461541x 18461541x 27490013x 27490013x 45951554x 2x 2x 2x 2x 13x 13x 13x 2x 2x 2x 27490011x 27490011x 45951554x 1444247x 1444247x 1444247x 5x 5x 5x 5x 5x 3x 3x 5x 5x 5x 5x 1444247x 1604320x 1604320x 1604320x 1444247x 1444247x 1444247x 26045764x 26045764x 45951554x 827800x 827800x 827800x 827800x 827800x 825236x 825236x 825236x 827800x 827800x 827800x 827800x 25217964x 25217964x 25217964x 45951554x 303459551x 7682532x 7682532x 7682532x 7682532x 7682532x 303459551x 25217964x 17535432x 17535432x 45951554x 2336527x 2336527x 2336527x 2336527x 45951554x 2336527x 2336527x 2336527x 2336527x 45951554x 348207x 348207x 348207x 348207x 45951554x 11x 11x 11x 11x 45951554x 698987x 698987x 698987x 698987x 45951554x 698987x 698987x 698987x 698987x 11116186x 11116186x 11116186x 11116186x 11116186x 11116186x 91603083x 91603083x 91603083x 11116186x 11116186x 11116186x 3635133x 3635133x 3635133x 3635133x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3635133x 3635133x 3635133x 1x 1x 219411214x 219411214x 1x 1x 27490013x 27490013x 27490013x 27490013x 1x 1x 3383742x 3383742x 3383742x 3383742x 1x 1x 3635133x 3635133x 3635132x 3635133x 1x 1x 1x 7717841x 7717841x 1x 1x 1x 7717841x 7717841x 7717841x 698987x 698987x 698987x 698987x 698987x 698987x 7018853x 7018853x 7717841x 1x 1x 1x 7717841x 7717841x 7717841x 576725x 576725x 576725x 576725x 7717840x 7717840x 7717841x 1x 1x 1x 8294566x 8294566x 8294566x 345897x 345897x 345897x 345897x 8294565x 8294565x 8294566x 1x 1x 1x 8640463x 8640463x 8640463x 8640463x 2423558x 8640463x 1500936x 1500936x 1500936x 1500936x 8640462x 8640462x 8640463x 1x 1x 1x 10141399x 10141399x 10141399x 10141399x 3971752x 10141399x 1548194x 1548194x 1548194x 1548194x 1548194x 1548194x 384541x 384541x 1548194x 868480x 868480x 1548194x 3x 3x 1548194x 295170x 295170x 1548194x 1548194x 10141398x 10141398x 10141399x 1x 1x 1x 11689593x 11689593x 11689593x 11689593x 5675549x 11689593x 1703797x 1703797x 1703797x 779961x 779961x 15510x 779961x 764451x 764451x 1703797x 923836x 923836x 1703797x 11689592x 11689592x 11689593x 1x 1x 1x 13393390x 13393390x 13393390x 13393390x 7658693x 13393390x 1983144x 1983144x 1983144x 348199x 1983144x 1286729x 1634945x 348216x 348216x 1983144x 13393389x 13393389x 13393390x 1x 1x 1x 15400373x 23839x 23839x 23839x 15400373x 15376534x 15400373x 1x 1x 1x 15376534x 15376534x 15376534x 15376534x 1444247x 1444247x 1444247x 13932287x 13932287x 15376534x 827800x 827800x 827800x 13104487x 13104487x 15376534x 2x 2x 2x 2x 1x 1x 1x 1x 1x 13104485x 13104485x 15376534x 1988310x 1988310x 1988310x 1988310x 1988310x 11116175x 11116175x 11116175x 11116175x 11116175x 11116175x 11116175x 11116175x 11116175x 11116175x 11116140x 11116140x 11116175x 11116140x 11116140x 11116175x 348217x 348217x 10767923x 10767923x 10767923x 10767923x 15376534x 1x 1x 348217x 348217x 348217x 348217x 348217x 348217x 348207x 348207x 348207x 348217x 348217x 348217x 348217x 348217x 348217x 1x 1x 348217x 348217x 174100x 174100x 174100x 348217x 174098x 174098x 174098x 348217x 4x 4x 4x 348217x 3x 3x 3x 348217x 3x 3x 3x 348217x 4x 4x 4x 348217x 3x 3x 3x 348217x 2x 2x 2x 348217x 348217x 348217x 1x 1x 10767923x 10767923x 10767923x 10767923x 6472459x 10767923x 4295463x 4295464x 1x 1x 1x 10767922x 10767922x 10767923x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 10767922x 10767922x 10767923x 1x 1x 1x 1x 1x 1x 348198x 348198x 348198x 348198x 916685x 916685x 916685x 916685x 348198x 348198x 1x 174100x 174100x 174100x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3635133x 3635133x 3635133x 3635133x 1x 1x 1x 1x 1x 92x 92x 92x 92x 92x 92x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Expression Evaluator for Flowchart Walker
*
* A simple, safe expression language for computing values in flowcharts.
* Does NOT use JavaScript eval - uses a custom parser for security.
*
* Supported:
* - Field access: left.denom, problem.minuend
* - State variables: $lcd, $borrowed (prefix with $)
* - Arithmetic: +, -, *, /, %
* - Comparison: ==, !=, <, >, <=, >=
* - Boolean: &&, ||, !
* - Ternary: condition ? trueValue : falseValue
* - Functions: lcm, gcd, min, max, abs, floor, ceil, mod
* - Literals: numbers, strings, booleans (true/false), null
*/
import type { ProblemValue, MixedNumberValue } from './schema'
// =============================================================================
// Types
// =============================================================================
type TokenType =
| 'NUMBER'
| 'STRING'
| 'IDENTIFIER'
| 'STATE_VAR'
| 'OPERATOR'
| 'LPAREN'
| 'RPAREN'
| 'COMMA'
| 'DOT'
| 'QUESTION'
| 'COLON'
| 'EOF'
interface Token {
type: TokenType
value: string | number
position: number
}
/** Context for expression evaluation */
export interface EvalContext {
/** Problem input values (e.g., left, right, op) */
problem: Record<string, ProblemValue>
/** Computed variables (e.g., lcd, needsBorrow) */
computed: Record<string, ProblemValue>
/** User-entered state during walkthrough */
userState: Record<string, ProblemValue>
/** Special "input" value for checkpoint validation */
input?: ProblemValue
}
// =============================================================================
// Tokenizer
// =============================================================================
const OPERATORS = ['&&', '||', '==', '!=', '<=', '>=', '<', '>', '+', '-', '*', '/', '%', '!']
function tokenize(expr: string): Token[] {
const tokens: Token[] = []
let pos = 0
while (pos < expr.length) {
// Skip whitespace
if (/\s/.test(expr[pos])) {
pos++
continue
}
// State variable ($varName)
if (expr[pos] === '$') {
const start = pos
pos++ // skip $
let name = ''
while (pos < expr.length && /[a-zA-Z0-9_]/.test(expr[pos])) {
name += expr[pos]
pos++
}
tokens.push({ type: 'STATE_VAR', value: name, position: start })
continue
}
// Number
if (/[0-9]/.test(expr[pos]) || (expr[pos] === '-' && /[0-9]/.test(expr[pos + 1]))) {
const start = pos
let numStr = ''
if (expr[pos] === '-') {
// Check if this is a negative number or subtraction
// It's a negative number if: start of expression, after operator, after ( or ,
const lastToken = tokens[tokens.length - 1]
if (
lastToken &&
lastToken.type !== 'OPERATOR' &&
lastToken.type !== 'LPAREN' &&
lastToken.type !== 'COMMA'
) {
// It's subtraction, not negative number
tokens.push({ type: 'OPERATOR', value: '-', position: pos })
pos++
continue
}
numStr += expr[pos]
pos++
}
while (pos < expr.length && /[0-9.]/.test(expr[pos])) {
numStr += expr[pos]
pos++
}
tokens.push({ type: 'NUMBER', value: parseFloat(numStr), position: start })
continue
}
// String literal
if (expr[pos] === '"' || expr[pos] === "'") {
const quote = expr[pos]
const start = pos
pos++ // skip opening quote
let str = ''
while (pos < expr.length && expr[pos] !== quote) {
str += expr[pos]
pos++
}
pos++ // skip closing quote
tokens.push({ type: 'STRING', value: str, position: start })
continue
}
// Multi-character operators (must check before single-char)
let foundOp = false
for (const op of OPERATORS) {
if (expr.slice(pos, pos + op.length) === op) {
tokens.push({ type: 'OPERATOR', value: op, position: pos })
pos += op.length
foundOp = true
break
}
}
if (foundOp) continue
// Single character tokens
if (expr[pos] === '(') {
tokens.push({ type: 'LPAREN', value: '(', position: pos })
pos++
continue
}
if (expr[pos] === ')') {
tokens.push({ type: 'RPAREN', value: ')', position: pos })
pos++
continue
}
if (expr[pos] === ',') {
tokens.push({ type: 'COMMA', value: ',', position: pos })
pos++
continue
}
if (expr[pos] === '.') {
tokens.push({ type: 'DOT', value: '.', position: pos })
pos++
continue
}
if (expr[pos] === '?') {
tokens.push({ type: 'QUESTION', value: '?', position: pos })
pos++
continue
}
if (expr[pos] === ':') {
tokens.push({ type: 'COLON', value: ':', position: pos })
pos++
continue
}
// Identifier (variable name, function name, true/false/null)
if (/[a-zA-Z_]/.test(expr[pos])) {
const start = pos
let name = ''
while (pos < expr.length && /[a-zA-Z0-9_]/.test(expr[pos])) {
name += expr[pos]
pos++
}
tokens.push({ type: 'IDENTIFIER', value: name, position: start })
continue
}
throw new Error(`Unexpected character '${expr[pos]}' at position ${pos}`)
}
tokens.push({ type: 'EOF', value: '', position: pos })
return tokens
}
// =============================================================================
// Parser
// =============================================================================
class Parser {
private tokens: Token[]
private pos = 0
private context: EvalContext
constructor(tokens: Token[], context: EvalContext) {
this.tokens = tokens
this.context = context
}
private current(): Token {
return this.tokens[this.pos]
}
private advance(): Token {
const token = this.current()
this.pos++
return token
}
private expect(type: TokenType): Token {
const token = this.current()
if (token.type !== type) {
throw new Error(`Expected ${type} but got ${token.type} at position ${token.position}`)
}
return this.advance()
}
parse(): ProblemValue {
const result = this.parseExpression()
if (this.current().type !== 'EOF') {
throw new Error(
`Unexpected token ${this.current().type} at position ${this.current().position}`
)
}
return result
}
// Expression = Ternary
private parseExpression(): ProblemValue {
return this.parseTernary()
}
// Ternary = Or ('?' Expression ':' Expression)?
private parseTernary(): ProblemValue {
const condition = this.parseOr()
if (this.current().type === 'QUESTION') {
this.advance() // skip ?
const trueValue = this.parseExpression()
this.expect('COLON')
const falseValue = this.parseExpression()
return condition ? trueValue : falseValue
}
return condition
}
// Or = And ('||' And)*
private parseOr(): ProblemValue {
let left = this.parseAnd()
while (this.current().type === 'OPERATOR' && this.current().value === '||') {
this.advance()
const right = this.parseAnd()
left = Boolean(left) || Boolean(right)
}
return left
}
// And = Equality ('&&' Equality)*
private parseAnd(): ProblemValue {
let left = this.parseEquality()
while (this.current().type === 'OPERATOR' && this.current().value === '&&') {
this.advance()
const right = this.parseEquality()
left = Boolean(left) && Boolean(right)
}
return left
}
// Equality = Comparison (('==' | '!=') Comparison)*
private parseEquality(): ProblemValue {
let left = this.parseComparison()
while (
this.current().type === 'OPERATOR' &&
(this.current().value === '==' || this.current().value === '!=')
) {
const op = this.advance().value
const right = this.parseComparison()
left = op === '==' ? left === right : left !== right
}
return left
}
// Comparison = Addition (('<' | '>' | '<=' | '>=') Addition)*
private parseComparison(): ProblemValue {
let left = this.parseAddition()
while (
this.current().type === 'OPERATOR' &&
['<', '>', '<=', '>='].includes(this.current().value as string)
) {
const op = this.advance().value as string
const right = this.parseAddition()
const l = Number(left)
const r = Number(right)
switch (op) {
case '<':
left = l < r
break
case '>':
left = l > r
break
case '<=':
left = l <= r
break
case '>=':
left = l >= r
break
}
}
return left
}
// Addition = Multiplication (('+' | '-') Multiplication)*
private parseAddition(): ProblemValue {
let left = this.parseMultiplication()
while (
this.current().type === 'OPERATOR' &&
(this.current().value === '+' || this.current().value === '-')
) {
const op = this.advance().value
const right = this.parseMultiplication()
if (op === '+') {
// Support string concatenation: if either operand is a string, concatenate
if (typeof left === 'string' || typeof right === 'string') {
left = String(left) + String(right)
} else {
left = Number(left) + Number(right)
}
} else {
left = Number(left) - Number(right)
}
}
return left
}
// Multiplication = Unary (('*' | '/' | '%') Unary)*
private parseMultiplication(): ProblemValue {
let left = this.parseUnary()
while (
this.current().type === 'OPERATOR' &&
(this.current().value === '*' || this.current().value === '/' || this.current().value === '%')
) {
const op = this.advance().value
const right = this.parseUnary()
if (op === '*') {
left = Number(left) * Number(right)
} else if (op === '/') {
left = Number(left) / Number(right)
} else {
left = Number(left) % Number(right)
}
}
return left
}
// Unary = '!' Unary | '-' Unary | Primary
private parseUnary(): ProblemValue {
if (this.current().type === 'OPERATOR' && this.current().value === '!') {
this.advance()
return !this.parseUnary()
}
if (this.current().type === 'OPERATOR' && this.current().value === '-') {
this.advance()
return -Number(this.parseUnary())
}
return this.parsePrimary()
}
// Primary = NUMBER | STRING | IDENTIFIER | STATE_VAR | '(' Expression ')' | FunctionCall
private parsePrimary(): ProblemValue {
const token = this.current()
// Number literal
if (token.type === 'NUMBER') {
this.advance()
return token.value as number
}
// String literal
if (token.type === 'STRING') {
this.advance()
return token.value as string
}
// State variable ($varName)
if (token.type === 'STATE_VAR') {
this.advance()
const name = token.value as string
// Check userState first, then computed
if (name in this.context.userState) {
return this.context.userState[name]
}
if (name in this.context.computed) {
return this.context.computed[name]
}
throw new Error(`Unknown state variable: $${name}`)
}
// Parenthesized expression
if (token.type === 'LPAREN') {
this.advance()
const value = this.parseExpression()
this.expect('RPAREN')
return value
}
// Identifier: could be keyword, function call, or variable access
if (token.type === 'IDENTIFIER') {
const name = token.value as string
this.advance()
// Keywords
if (name === 'true') return true
if (name === 'false') return false
if (name === 'null') return null as unknown as ProblemValue
// Special "input" variable for checkpoint validation
if (name === 'input') {
if (this.context.input === undefined) {
throw new Error('input is not available in this context')
}
return this.context.input
}
// Function call
if (this.current().type === 'LPAREN') {
return this.parseFunctionCall(name)
}
// Variable access (possibly with dot notation)
return this.parseVariableAccess(name)
}
throw new Error(`Unexpected token ${token.type} at position ${token.position}`)
}
private parseFunctionCall(name: string): ProblemValue {
this.expect('LPAREN')
const args: ProblemValue[] = []
if (this.current().type !== 'RPAREN') {
args.push(this.parseExpression())
while (this.current().type === 'COMMA') {
this.advance()
args.push(this.parseExpression())
}
}
this.expect('RPAREN')
return this.callFunction(name, args)
}
private callFunction(name: string, args: ProblemValue[]): ProblemValue {
switch (name) {
case 'lcm': {
if (args.length !== 2) throw new Error('lcm requires 2 arguments')
return lcm(Number(args[0]), Number(args[1]))
}
case 'gcd': {
if (args.length !== 2) throw new Error('gcd requires 2 arguments')
return gcd(Number(args[0]), Number(args[1]))
}
case 'min': {
if (args.length < 2) throw new Error('min requires at least 2 arguments')
return Math.min(...args.map(Number))
}
case 'max': {
if (args.length < 2) throw new Error('max requires at least 2 arguments')
return Math.max(...args.map(Number))
}
case 'abs': {
if (args.length !== 1) throw new Error('abs requires 1 argument')
return Math.abs(Number(args[0]))
}
case 'floor': {
if (args.length !== 1) throw new Error('floor requires 1 argument')
return Math.floor(Number(args[0]))
}
case 'ceil': {
if (args.length !== 1) throw new Error('ceil requires 1 argument')
return Math.ceil(Number(args[0]))
}
case 'mod': {
if (args.length !== 2) throw new Error('mod requires 2 arguments')
return Number(args[0]) % Number(args[1])
}
default:
throw new Error(`Unknown function: ${name}`)
}
}
private parseVariableAccess(name: string): ProblemValue {
// Start with the base variable from problem context
let value: ProblemValue
if (name in this.context.problem) {
value = this.context.problem[name]
} else if (name in this.context.computed) {
value = this.context.computed[name]
} else if (name in this.context.userState) {
value = this.context.userState[name]
} else {
throw new Error(`Unknown variable: ${name}`)
}
// Handle dot notation for nested access (e.g., left.denom)
while (this.current().type === 'DOT') {
this.advance()
const prop = this.expect('IDENTIFIER').value as string
if (value === null || value === undefined) {
throw new Error(`Cannot access property '${prop}' of ${value}`)
}
if (typeof value === 'object' && value !== null && prop in value) {
// Access property from the object - could be a MixedNumberValue or other nested structure
value = (value as unknown as Record<string, ProblemValue>)[prop]
} else {
throw new Error(`Property '${prop}' does not exist on value`)
}
}
return value
}
}
// =============================================================================
// Math Helpers
// =============================================================================
function gcd(a: number, b: number): number {
a = Math.abs(Math.floor(a))
b = Math.abs(Math.floor(b))
while (b !== 0) {
const t = b
b = a % b
a = t
}
return a
}
function lcm(a: number, b: number): number {
return Math.abs(a * b) / gcd(a, b)
}
// =============================================================================
// Public API
// =============================================================================
/**
* Evaluate an expression string in the given context
*/
export function evaluate(expr: string, context: EvalContext): ProblemValue {
const tokens = tokenize(expr)
const parser = new Parser(tokens, context)
return parser.parse()
}
/**
* Create an empty evaluation context
*/
export function createEmptyContext(): EvalContext {
return {
problem: {},
computed: {},
userState: {},
}
}
/**
* Evaluate a boolean expression (returns true/false)
*/
export function evaluateBoolean(expr: string, context: EvalContext): boolean {
return Boolean(evaluate(expr, context))
}
/**
* Evaluate a numeric expression (returns number)
*/
export function evaluateNumber(expr: string, context: EvalContext): number {
return Number(evaluate(expr, context))
}
/**
* Check if two values are approximately equal (for decimal tolerance)
*/
export function approximatelyEqual(a: number, b: number, tolerance: number): boolean {
return Math.abs(a - b) <= tolerance
}
/**
* Get the numeric value from a mixed number
*/
export function mixedNumberToDecimal(mn: MixedNumberValue): number {
return mn.whole + mn.num / mn.denom
}
/**
* Get the fractional value (num/denom) from a mixed number
*/
export function mixedNumberFraction(mn: MixedNumberValue): number {
return mn.num / mn.denom
}
|