All files / chart-parser/src/core control-flow.ts

95.89% Statements 70/73
92.75% Branches 64/69
100% Functions 7/7
97.1% Lines 67/69

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                                                                                29535x     29535x 29535x 625x     28905x   10318x 10318x 10318x   28905x 28905x 144x   28905x 100829x         28905x 28905x     28905x 29535x 29535x       1261904x 141021x 141021x   1120883x 81865x 81865x   1039018x 274928x 274928x   764090x 255044x 255044x   509046x 132172x 132172x   376874x 73880x                             1566155x 3x 3x 2x   1x   1566152x 28054x 28054x 1x 1x     1566151x       59x     59x 59x                             59x           461096x 513188x 461096x 461096x                     100829x   26069x 26060x   26069x   74760x 74760x 3035x   74760x 74760x   81757x           81757x 81757x 81757x        
import { evaluateControlFlow, type ActiveControlFlowEntry, type RandomDraws } from '@be-music/chart-model';
import {
  cloneJSON,
  type BMSControlFlowCommand,
  type BMSControlFlowEntry,
  type BeMusicEvent,
  type BeMusicJSON,
  normalizeChannel,
  normalizeObjectKey,
} from '@be-music/chart-source';
import { sortAndNormalizeEvents, upsertMeasureLength } from './event-utils.ts';
 
type ControlFlowCommand = BMSControlFlowCommand;
 
export type ControlFlowCaptureFrameType = 'random' | 'if' | 'switch';
 
type MeasureLengthEntry = BeMusicJSON['measures'][number];
 
export interface ResolveControlFlowOptions {
  /**
   * Re-applies a captured `#xxx ...` header entry against `json`.
   *
   * `command` is the uppercased canonical form used for keyword dispatch. `commandRaw` is the case-preserved original —
   * set only when the captured entry differed in case (typically a lowercase indexed-header key from a `#BASE 62`
   * chart). Callers should fall back to `command` when `commandRaw` is undefined, which is the common base-36
   * case-insensitive path.
   */
  applyHeader: (json: BeMusicJSON, command: string, commandRaw: string | undefined, value: string) => void;
}
 
/**
 * Builds the chart `input`'s control flow resolves to under `draws`: the header and object lines
 * `evaluateControlFlow` (`@be-music/chart-model`) reports active are applied on a copy of `input`, in file order, and the
 * copy's `bms.controlFlow` is emptied.
 */
export function resolveControlFlow(
  input: BeMusicJSON,
  draws: RandomDraws,
  options: ResolveControlFlowOptions,
): BeMusicJSON {
  const json = cloneJSON(input);
  // Evaluated on the copy so the applied events never share `position` / `bmson` objects with `input`. Draws that do
  // not belong to this chart throw here, including for a chart without control flow handed non-empty draws.
  const activeEntries = evaluateControlFlow(json, draws);
  if (json.bms.controlFlow.length === 0) {
    return json;
  }
 
  if (json.bms.optionHeadersInControlFlow) {
    // This complete program owns option declaration order; do not append its unconditional base twice.
    delete json.bms.option;
    delete json.bms.options;
    delete json.bms.optionHeadersInControlFlow;
  }
  const measureByIndex = new Map<number, MeasureLengthEntry>();
  for (const measure of json.measures) {
    measureByIndex.set(measure.index, measure);
  }
  for (const entry of activeEntries) {
    applyActiveControlFlowEntry(json, entry, options.applyHeader, measureByIndex);
  }
 
  // The branches are applied: the result is a resolved chart. Dropping the control flow makes that visible to every
  // consumer and makes resolving twice a no-op instead of stacking a second branch on top.
  json.bms.controlFlow = [];
  json.measures.sort((left, right) => left.index - right.index);
  // Honor `#BASE 62` so post-control-flow event normalization preserves lowercase IDs instead of folding them. The
  // base was recorded on the chart by the initial `parseBMS` pass.
  const replayBase: 36 | 62 = json.bms.base === 62 ? 62 : 36;
  json.events = sortAndNormalizeEvents(json.events, replayBase);
  return json;
}
 
export function updateControlFlowCaptureStack(stack: ControlFlowCaptureFrameType[], command: ControlFlowCommand): void {
  if (command === 'RANDOM' || command === 'SETRANDOM') {
    stack.push('random');
    return;
  }
  if (command === 'SWITCH' || command === 'SETSWITCH') {
    stack.push('switch');
    return;
  }
  if (command === 'IF') {
    stack.push('if');
    return;
  }
  if (command === 'ENDIF') {
    removeCurrentCaptureFrame(stack, 'if');
    return;
  }
  if (command === 'ENDRANDOM') {
    removeCurrentCaptureFrame(stack, 'random');
    return;
  }
  if (command === 'ENDSW') {
    removeCurrentCaptureFrame(stack, 'switch');
  }
}
 
/**
 * Maps real-world control-flow spelling variants onto their canonical commands: `#END IF` / bare `#END` → `#ENDIF`,
 * `#ELSE IF n` → `#ELSEIF n`. hitkey's command memo records these misspellings in released charts; without the
 * aliases the enclosing `#IF` never closes, and on a non-matching `#RANDOM` roll every line down to EOF silently
 * disappears. `#END <anything else>` and a plain `#ELSE` are NOT aliased — they fall through to normal header
 * handling.
 */
export function resolveControlFlowAliasDirective(
  command: string,
  value: string,
): { command: ControlFlowCommand; value?: string } | undefined {
  if (command === 'END') {
    const trimmed = value.trim();
    if (trimmed.length === 0 || trimmed.toUpperCase() === 'IF') {
      return { command: 'ENDIF' };
    }
    return undefined;
  }
  if (command === 'ELSE') {
    const match = value.match(/^IF\b\s*(.*)$/i);
    if (match) {
      const rest = match[1]!.trim();
      return { command: 'ELSEIF', value: rest.length > 0 ? rest : undefined };
    }
  }
  return undefined;
}
 
export function normalizeControlFlowCommand(input: unknown): ControlFlowCommand | undefined {
  Iif (typeof input !== 'string') {
    return undefined;
  }
  const normalized = input.toUpperCase();
  Eif (
    normalized === 'RANDOM' ||
    normalized === 'SETRANDOM' ||
    normalized === 'IF' ||
    normalized === 'ELSEIF' ||
    normalized === 'ELSE' ||
    normalized === 'ENDIF' ||
    normalized === 'ENDRANDOM' ||
    normalized === 'SWITCH' ||
    normalized === 'SETSWITCH' ||
    normalized === 'CASE' ||
    normalized === 'SKIP' ||
    normalized === 'DEF' ||
    normalized === 'ENDSW'
  ) {
    return normalized;
  }
  return undefined;
}
 
function removeCurrentCaptureFrame(stack: ControlFlowCaptureFrameType[], type: ControlFlowCaptureFrameType): void {
  for (let index = stack.length - 1; index >= 0; index -= 1) {
    if (stack[index] === type) {
      stack.splice(index, 1);
      return;
    }
  }
}
 
function applyActiveControlFlowEntry(
  json: BeMusicJSON,
  entry: ActiveControlFlowEntry,
  applyHeader: (json: BeMusicJSON, command: string, commandRaw: string | undefined, value: string) => void,
  measureByIndex?: Map<number, MeasureLengthEntry>,
): void {
  if (entry.kind === 'header') {
    // A later top-level line defines the same header and already won, as file order decides in LR2 and beatoraja.
    if (entry.overriddenByLaterHeader !== true) {
      applyHeader(json, entry.command, entry.commandRaw, entry.value);
    }
    return;
  }
  Eif (entry.kind === 'object') {
    if (typeof entry.measureLength === 'number' && entry.measureLength > 0) {
      upsertMeasureLength(json, entry.measure, entry.measureLength, measureByIndex);
    }
    const replayBase: 36 | 62 = json.bms.base === 62 ? 62 : 36;
    for (const event of entry.events) {
      // Optional fields are assigned, not spread, to keep the hidden classes of the parser's other events.
      const resolved: BeMusicEvent = {
        measure: entry.measure,
        channel: normalizeChannel(entry.channel),
        position: event.position,
        value: normalizeObjectKey(event.value, replayBase),
      };
      if (event.bmsLineOrder !== undefined) resolved.bmsLineOrder = event.bmsLineOrder;
      Iif (event.bmson) resolved.bmson = event.bmson;
      json.events.push(resolved);
    }
  }
}