object SwitchC singleton inherit: Construct // MANIFEST manifest get return: 'constructs': 'switch': repeats false clauses: 'switch': #exprout 'case': #exprsblock 'else': #block handler bind SwitchConstruct docs get return !Documents /////////////// SWITCH // // SwitchConstruct task expects $clauses, $tools if ($clauses | last).clause isnt 'else' return: error "SAI Complier: Every SWITCH statement should have an ELSE clause at the end. (If it's in the middle of the CASES, move it to the end.)" with ($clauses | has .clause is 'else') | count if it > 1 return: error "SAI Compiler: Found ${it} ELSE clauses in SWITCH; only one is required." set body '' outs !@OutVarHelper $clauses.0.args.out trialvar fields 'trial' outs.0 or !$tools.addlocal ply $clauses switch .type case 'switch.exprout' set vars to trialvar | update: 'condition' .args.expr text ''' switch (^{trial}=(^{condition})) { body + !$tools.replacer text, vars case 'case.exprsblock' set cases to .args.exprs.2 | total 'case ${.}:\n' vars trialvar | update: 'cases' cases 'block' .args.block text ''' ^{cases} ^{block} break; body + !$tools.replacer text, vars case 'else.block' set vars trialvar | update: 'block' .args.block text ''' default: ^{block} break; body + !$tools.replacer text, vars else return: error "Unhandled construct type ${.type} in SwitchConstruct" set body + '}' return: body body Documents task return: 'constructs': 'switch': subtitle 'choice-based conditional' summary ''' Choose among alternatives based on expression equality. detail ''' The expression under evaluation is available to all codepaths as **trial** (which can be renamed with the **as** clause). Unlike the native Javascript `switch` these __case__ clauses do not fall through; the break is implicit. (Though you can break out early.) switch ~System.IO.Keypress() as key case 'n', 'N' Move 0,-1 case 's', 'S' Move 0,1 case 'e', 'E' Move 1,0 case 'w', 'W' Move -1,0 case ' ' Jump case '?' Help else Emit 'Key [$\{key}] isn't used; type ? for help.' The compiler will insist on an __else__ clause as a matter of good programming hygeine.