All files / chart-model/src control-flow.ts

97.87% Statements 138/141
93.28% Branches 125/134
100% Functions 15/15
97.82% Lines 135/138

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                                                                                                      29439x 29439x 1713270x 1495760x   217510x 33400x 33400x   184110x 1713270x   29438x                                         29603x 29603x 29603x 29603x 29603x 1714703x 1714703x 1196570x 217686x 217686x 217686x 217686x 217686x   978884x 978884x   518133x 101045x     29594x 2x       29592x         21609x                                                                           3135972x               16032x 3224x   12808x         8500x                 217686x 217686x 2x   217684x 1x   217683x 33434x 33434x 1x   33433x   184249x 217686x 2x   184247x 3x                     249324x 159308x 159308x   90016x                   1706580x   586685x 586685x 586685x 586685x 586685x     32329x 32329x 11768x 11768x   11768x   20561x 20561x 20561x 32329x 32329x 10301x   20561x     30694x 30694x 440x 440x   440x   30254x 30254x 30254x 30254x     561703x 561703x   142856x 142856x     185064x 185064x     185064x 40975x 40975x 40975x   144089x 31883x 31883x     112206x 83961x 83961x   28245x   112206x 112206x 112206x 75020x   112206x     87152x 87152x 37424x   49728x 49728x 49728x 49728x     80097x 80097x               1207559x 4x   1207555x 1207555x 1x   1207554x 1207554x       138145x 138145x         829396x 1890545x 716504x     112892x         607246x                           999112x 1074837x 1074837x 999112x               784656x 840858x 784656x 784656x        
import type {
  BMSControlFlowCommand,
  BMSControlFlowEntry,
  BMSControlFlowHeaderEntry,
  BMSControlFlowObjectEntry,
} from '@be-music/chart-source';
 
/** The control-flow lines that set a `#RANDOM` / `#SWITCH` value: two that draw it and two that fix it. */
export type RandomDrawCommand = 'RANDOM' | 'SETRANDOM' | 'SWITCH' | 'SETSWITCH';
 
/**
 * The value one `#RANDOM` / `#SETRANDOM` / `#SWITCH` / `#SETSWITCH` line put in force.
 *
 * - `#RANDOM n` / `#SWITCH n` draw `value` from `1..n`; `range` is `n`. A missing, zero, negative or non-numeric `n`
 *   is a single-outcome line: `range` 1, `value` 1, and nothing is drawn for it.
 * - `#SETRANDOM n` / `#SETSWITCH n` fix the value to `n` (1 when `n` is missing or not positive); `range` is 1, since
 *   the line has one outcome, and `value` is `n`.
 */
export interface RandomDraw {
  readonly command: RandomDrawCommand;
  /** Number of outcomes the line offers. */
  readonly range: number;
  /** The value in force after the line, `1..range` for a drawing line. */
  readonly value: number;
}
 
/**
 * The outcome of a chart's control flow for one play: one {@link RandomDraw} per `#RANDOM` / `#SETRANDOM` /
 * `#SWITCH` / `#SETSWITCH` line, in file order. Every such line has an entry, including the ones nested in a branch
 * that is not taken, because the evaluator walks every line whatever the branch state.
 *
 * Draw it once with {@link drawRandomOutcomes}, then hand the same value to everything that needs the play's
 * branches (the resolver, the engine's RANDOM summary, the replay, hashing), so nothing rolls `#RANDOM` again.
 */
export type RandomDraws = ReadonlyArray<RandomDraw>;
 
/** Anything carrying a BMS control-flow list (a `BeMusicJSON`, or just its `bms` part). */
export interface ControlFlowSource {
  readonly bms: { readonly controlFlow: ReadonlyArray<BMSControlFlowEntry> };
}
 
/** A captured `#xxx` header or object line that is active under a set of draws. */
export type ActiveControlFlowEntry = BMSControlFlowHeaderEntry | BMSControlFlowObjectEntry;
 
/**
 * Draws the outcome of every `#RANDOM` / `#SETRANDOM` / `#SWITCH` / `#SETSWITCH` line of `source`, in file order.
 *
 * `random` returns a value in `[0, 1)` (out-of-range and non-finite values are clamped) and is called exactly once
 * per line with more than one outcome; single-outcome lines and the `#SET…` lines do not consume it.
 */
export function drawRandomOutcomes(source: ControlFlowSource, random: () => number): RandomDraws {
  const draws: RandomDraw[] = [];
  for (const entry of source.bms.controlFlow) {
    if (entry.kind !== 'directive' || !isRandomDrawCommand(entry.command)) {
      continue;
    }
    if (entry.command === 'SETRANDOM' || entry.command === 'SETSWITCH') {
      draws.push({ command: entry.command, range: 1, value: parseControlFlowInteger(entry.value) ?? 1 });
      continue;
    }
    const range = parseControlFlowInteger(entry.value) ?? 1;
    draws.push({ command: entry.command, range, value: range <= 1 ? 1 : drawValue(range, random()) });
  }
  return draws;
}
 
/**
 * Lists the captured header and object lines of `source` that are active when its control flow takes `draws`, in
 * file order. This is the one evaluator of the control-flow semantics; the parser applies its result to build the
 * resolved chart.
 *
 * Semantics (LR2 / beatoraja compatible):
 * - One stack holds `#RANDOM`, `#IF` and `#SWITCH` frames. `#ENDIF` / `#ENDRANDOM` / `#ENDSW` remove the innermost
 *   frame of their kind, so an `#IF` left open (a missing `#ENDIF`) outlives its `#ENDRANDOM` and keeps gating the
 *   lines after it.
 * - `#IF n` tests the innermost `#RANDOM` value; `#ELSEIF` / `#ELSE` act on the innermost `#IF`. `#CASE` / `#DEF` /
 *   `#SKIP` act on the innermost `#SWITCH`, with fall-through until `#SKIP`.
 * - A line is active when every `#IF` and `#SWITCH` frame on the stack is active. Header lines inside a taken
 *   branch (`#WAVxx`, `#BPM`, …) take effect for the whole chart, exactly like ones outside control flow.
 *
 * @throws RangeError when `draws` was not drawn for this control flow (another line count, command, range, or a
 *   value outside the line's outcomes).
 */
export function evaluateControlFlow(source: ControlFlowSource, draws: RandomDraws): ActiveControlFlowEntry[] {
  const active: ActiveControlFlowEntry[] = [];
  const stack: ControlFlowFrame[] = [];
  let drawIndex = 0;
  const entries = source.bms.controlFlow;
  for (let index = 0; index < entries.length; index += 1) {
    const entry = entries[index]!;
    if (entry.kind === 'directive') {
      if (isRandomDrawCommand(entry.command)) {
        const draw = draws[drawIndex];
        assertDrawMatches(draw, drawIndex, entry.command, entry.value);
        drawIndex += 1;
        pushValueFrame(stack, entry.command, draw.value, index);
        continue;
      }
      applyBranchCommand(stack, entry.command, entry.value, index);
      continue;
    }
    if (isControlFlowActive(stack)) {
      active.push(entry);
    }
  }
  if (drawIndex !== draws.length) {
    throw new RangeError(
      `RandomDraws do not match the control flow: the chart has ${drawIndex} #RANDOM / #SWITCH lines, the draws ${draws.length}.`,
    );
  }
  return active;
}
 
/** Whether `source` still carries control flow, i.e. has not been resolved yet. */
export function hasControlFlow(source: ControlFlowSource): boolean {
  return source.bms.controlFlow.length > 0;
}
 
// ---------------------------------------------------------------------------------------------------------------------
// The frame-stack semantics. Exported for the chart fingerprint, which runs them over every outcome at once
// (`fingerprint-control-flow.ts`); not part of the package API.
// ---------------------------------------------------------------------------------------------------------------------
 
interface ControlFrameBase {
  /** Index in `bms.controlFlow` of the directive that pushed the frame. */
  origin: number;
}
 
export interface RandomControlFrame extends ControlFrameBase {
  type: 'random';
  value: number;
}
 
export interface IfControlFrame extends ControlFrameBase {
  type: 'if';
  active: boolean;
  matched: boolean;
  hasElse: boolean;
}
 
export interface SwitchControlFrame extends ControlFrameBase {
  type: 'switch';
  value: number;
  active: boolean;
  matched: boolean;
  fallthrough: boolean;
  terminated: boolean;
}
 
/** One frame of the control-flow stack. */
export type ControlFlowFrame = RandomControlFrame | IfControlFrame | SwitchControlFrame;
 
export function isRandomDrawCommand(command: BMSControlFlowCommand): command is RandomDrawCommand {
  return command === 'RANDOM' || command === 'SETRANDOM' || command === 'SWITCH' || command === 'SETSWITCH';
}
 
/**
 * The value a `#SETRANDOM` / `#SETSWITCH` line fixes, or `undefined` for a `#RANDOM` / `#SWITCH` line with more than one
 * outcome (a variable). Single-outcome `#RANDOM` / `#SWITCH` lines are fixed to 1.
 */
export function fixedDrawValue(command: RandomDrawCommand, rawValue: string | undefined): number | undefined {
  if (command === 'SETRANDOM' || command === 'SETSWITCH') {
    return parseControlFlowInteger(rawValue) ?? 1;
  }
  return (parseControlFlowInteger(rawValue) ?? 1) <= 1 ? 1 : undefined;
}
 
/** Number of outcomes a `#RANDOM` / `#SWITCH` line offers (1 for the `#SET…` lines). */
export function drawRange(command: RandomDrawCommand, rawValue: string | undefined): number {
  return command === 'SETRANDOM' || command === 'SETSWITCH' ? 1 : (parseControlFlowInteger(rawValue) ?? 1);
}
 
function assertDrawMatches(
  draw: RandomDraw | undefined,
  index: number,
  command: RandomDrawCommand,
  rawValue: string | undefined,
): asserts draw is RandomDraw {
  const prefix = `RandomDraws do not match the control flow at #${command} line ${index + 1}`;
  if (draw === undefined) {
    throw new RangeError(`${prefix}: no draw for it.`);
  }
  if (draw.command !== command) {
    throw new RangeError(`${prefix}: the draw is for #${draw.command}.`);
  }
  if (command === 'SETRANDOM' || command === 'SETSWITCH') {
    const fixed = parseControlFlowInteger(rawValue) ?? 1;
    if (draw.range !== 1 || draw.value !== fixed) {
      throw new RangeError(`${prefix}: the line fixes ${fixed}, the draw has ${draw.value}.`);
    }
    return;
  }
  const range = parseControlFlowInteger(rawValue) ?? 1;
  if (draw.range !== range) {
    throw new RangeError(`${prefix}: the line offers ${range} outcomes, the draw ${draw.range}.`);
  }
  if (!Number.isInteger(draw.value) || draw.value < 1 || draw.value > range) {
    throw new RangeError(`${prefix}: ${draw.value} is not in 1..${range}.`);
  }
}
 
/** Pushes the frame of a `#RANDOM` / `#SETRANDOM` / `#SWITCH` / `#SETSWITCH` line whose value is `value`. */
export function pushValueFrame(
  stack: ControlFlowFrame[],
  command: RandomDrawCommand,
  value: number,
  origin: number,
): void {
  if (command === 'RANDOM' || command === 'SETRANDOM') {
    stack.push({ type: 'random', value, origin });
    return;
  }
  stack.push({ type: 'switch', value, active: false, matched: false, fallthrough: false, terminated: false, origin });
}
 
/** Applies any other directive (`#IF`, `#ELSE`, `#CASE`, `#ENDSW`, …) to the stack. */
export function applyBranchCommand(
  stack: ControlFlowFrame[],
  command: BMSControlFlowCommand,
  rawValue: string | undefined,
  origin: number,
): void {
  switch (command) {
    case 'IF': {
      const label = parseControlFlowInteger(rawValue);
      const randomValue = getCurrentRandomValue(stack);
      const matched = label !== undefined && randomValue !== undefined && label === randomValue;
      stack.push({ type: 'if', active: matched, matched, hasElse: false, origin });
      return;
    }
    case 'ELSEIF': {
      const frame = getCurrentFrame(stack, 'if');
      if (!frame || frame.hasElse || frame.matched) {
        Eif (frame) {
          frame.active = false;
        }
        return;
      }
      const label = parseControlFlowInteger(rawValue);
      const randomValue = getCurrentRandomValue(stack);
      const matched = label !== undefined && randomValue !== undefined && label === randomValue;
      frame.active = matched;
      if (matched) {
        frame.matched = true;
      }
      return;
    }
    case 'ELSE': {
      const frame = getCurrentFrame(stack, 'if');
      if (!frame || frame.hasElse) {
        Eif (frame) {
          frame.active = false;
        }
        return;
      }
      frame.hasElse = true;
      frame.active = !frame.matched;
      frame.matched = true;
      return;
    }
    case 'ENDIF':
      removeCurrentFrame(stack, 'if');
      return;
    case 'ENDRANDOM':
      removeCurrentFrame(stack, 'random');
      return;
    case 'CASE':
    case 'DEF': {
      const frame = getCurrentFrame(stack, 'switch');
      Iif (!frame) {
        return;
      }
      if (frame.terminated) {
        frame.active = false;
        frame.fallthrough = false;
        return;
      }
      if (frame.fallthrough) {
        frame.active = true;
        return;
      }
      let matched: boolean;
      if (command === 'CASE') {
        const label = parseControlFlowInteger(rawValue);
        matched = label !== undefined && label === frame.value;
      } else {
        matched = !frame.matched;
      }
      frame.active = matched;
      frame.fallthrough = matched;
      if (matched) {
        frame.matched = true;
      }
      return;
    }
    case 'SKIP': {
      const frame = getCurrentFrame(stack, 'switch');
      if (!frame || !frame.active) {
        return;
      }
      frame.terminated = true;
      frame.active = false;
      frame.fallthrough = false;
      return;
    }
    case 'ENDSW':
      removeCurrentFrame(stack, 'switch');
      return;
    default:
      return;
  }
}
 
/** A control-flow line's positive integer argument (`#RANDOM n`, `#IF n`, …), or `undefined`. */
export function parseControlFlowInteger(value?: string): number | undefined {
  if (!value || value.length === 0) {
    return undefined;
  }
  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed)) {
    return undefined;
  }
  const normalized = Math.floor(parsed);
  return normalized <= 0 ? undefined : normalized;
}
 
function drawValue(range: number, randomValue: number): number {
  const clamped = Number.isFinite(randomValue) ? Math.max(0, Math.min(0.999999999, randomValue)) : 0;
  return Math.floor(clamped * range) + 1;
}
 
/** A header or object line is applied when every `#IF` and `#SWITCH` frame on the stack is active. */
export function isControlFlowActive(stack: ReadonlyArray<ControlFlowFrame>): boolean {
  for (const frame of stack) {
    if (frame.type !== 'random' && !frame.active) {
      return false;
    }
  }
  return true;
}
 
/** The value of the innermost `#RANDOM` / `#SETRANDOM` frame, which `#IF` / `#ELSEIF` compare with. */
function getCurrentRandomValue(stack: ReadonlyArray<ControlFlowFrame>): number | undefined {
  return getCurrentFrame(stack, 'random')?.value;
}
 
/**
 * The innermost frame of a kind: `#IF` / `#ELSEIF` compare with the innermost `#RANDOM`, `#ELSE` / `#ELSEIF` act on the
 * innermost `#IF`, and `#CASE` / `#DEF` / `#SKIP` on the innermost `#SWITCH`.
 */
export function getCurrentFrame(stack: ReadonlyArray<ControlFlowFrame>, type: 'random'): RandomControlFrame | undefined;
export function getCurrentFrame(stack: ReadonlyArray<ControlFlowFrame>, type: 'if'): IfControlFrame | undefined;
export function getCurrentFrame(stack: ReadonlyArray<ControlFlowFrame>, type: 'switch'): SwitchControlFrame | undefined;
export function getCurrentFrame(
  stack: ReadonlyArray<ControlFlowFrame>,
  type: ControlFlowFrame['type'],
): ControlFlowFrame | undefined {
  for (let index = stack.length - 1; index >= 0; index -= 1) {
    const frame = stack[index]!;
    if (frame.type === type) {
      return frame;
    }
  }
  return undefined;
}
 
/** `#ENDIF` / `#ENDRANDOM` / `#ENDSW` remove the innermost frame of their kind, wherever it is on the stack. */
export function removeCurrentFrame(stack: ControlFlowFrame[], type: ControlFlowFrame['type']): void {
  for (let index = stack.length - 1; index >= 0; index -= 1) {
    if (stack[index]!.type === type) {
      stack.splice(index, 1);
      return;
    }
  }
}