All files / src/lib/compiler buildUsage.ts

98.88% Statements 89/90
96.66% Branches 29/30
96.15% Functions 25/26
98.78% Lines 81/82

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 3482x 2x       2x         2x       2x   2x                                                                                                                                                               2x 14x 14x     35x   35x   2x 35x   2x       36x 36x 36x 105x 46x 46x     36x     2x   32x     12x 42x     12x               16x           2x     27x           2x     5x           2x       9x 21x   7x       2x     5x   5x 11x 6x     5x         5x 5x         5x     5x 1x 4x     1x         2x           3x 3x 3x 3x 3x 3x       3x   3x 7x     3x 1x           2x                           2x     12x                 2x                             5x 5x       5x 11x       5x   11x       11x           11x     5x 1x     4x             3x         3x   3x           3x                           2x 2x          
import Path from "path";
import romUsage, { type RomUsageBank, type RomUsageData } from "./romUsage";
import type { CompiledScriptSource } from "./compileData";
import type { CartType } from "shared/lib/resources/types";
import type { BuildManifest } from "lib/compiler/buildManifest";
import {
  analyseBuildObjects,
  analyseMusicDriverUsage,
  type BuildModuleUsage,
} from "lib/compiler/buildModuleUsage";
import {
  capacityForCartType,
  type RegionUsage,
} from "lib/compiler/buildArtifactParsers";
import { RESERVED_WRAM_BYTES } from "shared/lib/compiler/memoryLayout";
 
const ROM_SIZES = [
  128 * 1024,
  256 * 1024,
  512 * 1024,
  1 * 1024 * 1024,
  2 * 1024 * 1024,
  4 * 1024 * 1024,
];
 
export type MemoryRegionUsage = {
  used: number;
  size: number;
};
 
export type RomMemoryUsage = MemoryRegionUsage & {
  maxSize: number;
  nextSize?: number;
};
 
export type BuildUsageMemory = {
  rom: RomMemoryUsage;
  bank0: MemoryRegionUsage;
  wram: MemoryRegionUsage;
};
 
export type BuildUsageScript = {
  symbol: string;
  size: number;
  sources: CompiledScriptSource[];
};
 
export type BuildUsageSource = {
  sourceFile: string;
  usage: RegionUsage;
};
 
export type BuildUsageOverview = {
  cartType: CartType;
  engine: RegionUsage;
  musicDriver: RegionUsage;
  gbdkRuntime: RegionUsage;
  project: RegionUsage;
  plugins: RegionUsage;
  reserved: RegionUsage;
  total: RegionUsage;
  maximum: RegionUsage;
  remaining: RegionUsage;
};
 
export type BuildUsagePluginFile = {
  sourceFile: string;
  usage: RegionUsage;
  replacesDefault: boolean;
};
 
export type BuildUsagePlugin = {
  pluginName: string;
  usage: RegionUsage;
  files: BuildUsagePluginFile[];
};
 
export type UsageData =
  | {
      status: "complete";
      memory: BuildUsageMemory;
      overview: BuildUsageOverview;
      plugins: BuildUsagePlugin[];
      scripts: BuildUsageScript[];
      sources: BuildUsageSource[];
    }
  | {
      status: "partial";
      plugins: BuildUsagePlugin[];
      scripts: BuildUsageScript[];
      sources: BuildUsageSource[];
    }
  | {
      status: "unavailable";
    };
 
export const romCapacityForCartType = (cartType: CartType): number => {
  const capacity = capacityForCartType(cartType);
  return capacity.bank0 + capacity.bankedRom;
};
 
const isRomBank = (bank: RomUsageBank) => bank.name.startsWith("ROM_");
 
const isRomBank0 = (bank: RomUsageBank) => bank.name === "ROM_0";
 
const isWramBank = (bank: RomUsageBank) =>
  bank.name === "WRAM_LO" || bank.name === "WRAM_HI_0";
 
const sumUsage = (
  banks: RomUsageBank[],
  filter: (bank: RomUsageBank) => boolean,
): MemoryRegionUsage => {
  let used = 0;
  let size = 0;
  for (const bank of banks) {
    if (filter(bank)) {
      used += bank.used;
      size += bank.size;
    }
  }
  return { used, size };
};
 
const calculateRomUsage = (used: number, maxSize: number): RomMemoryUsage => {
  const size =
    ROM_SIZES.find((romSize) => romSize >= used && romSize <= maxSize) ??
    maxSize;
 
  const nextSize = ROM_SIZES.find(
    (romSize) => romSize > size && romSize <= maxSize,
  );
 
  return {
    used,
    size,
    maxSize,
    ...(nextSize !== undefined ? { nextSize } : {}),
  };
};
 
const emptyRegionUsage = (): RegionUsage => ({
  bank0: 0,
  wram: 0,
  bankedRom: 0,
});
 
const addRegionUsage = (
  left: RegionUsage,
  right: RegionUsage,
): RegionUsage => ({
  bank0: left.bank0 + right.bank0,
  wram: left.wram + right.wram,
  bankedRom: left.bankedRom + right.bankedRom,
});
 
const subtractRegionUsage = (
  left: RegionUsage,
  right: RegionUsage,
): RegionUsage => ({
  bank0: left.bank0 - right.bank0,
  wram: left.wram - right.wram,
  bankedRom: left.bankedRom - right.bankedRom,
});
 
const usageForOrigin = (
  modules: BuildModuleUsage[],
  origin: "engine" | "project" | "plugin",
): RegionUsage =>
  modules
    .filter((module) => module.origin.type === origin)
    .reduce(
      (total, module) => addRegionUsage(total, module.usage),
      emptyRegionUsage(),
    );
 
const analysePluginUsage = (
  modules: BuildModuleUsage[],
): BuildUsagePlugin[] => {
  const pluginsByName = new Map<string, BuildUsagePlugin>();
 
  for (const module of modules) {
    if (module.origin.type !== "plugin") {
      continue;
    }
 
    const plugin = pluginsByName.get(module.origin.pluginName) ?? {
      pluginName: module.origin.pluginName,
      usage: emptyRegionUsage(),
      files: [],
    };
    plugin.usage = addRegionUsage(plugin.usage, module.usage);
    plugin.files.push({
      sourceFile: module.sourceFile,
      usage: module.usage,
      replacesDefault: module.origin.replacesDefault,
    });
    pluginsByName.set(plugin.pluginName, plugin);
  }
 
  return [...pluginsByName.values()]
    .sort((left, right) => left.pluginName.localeCompare(right.pluginName))
    .map((plugin) => ({
      ...plugin,
      files: plugin.files.sort((left, right) =>
        left.sourceFile.localeCompare(right.sourceFile),
      ),
    }));
};
 
const buildUsageOverview = (
  modules: BuildModuleUsage[],
  musicDriver: RegionUsage,
  cartType: CartType,
  total: RegionUsage,
): BuildUsageOverview => {
  const engine = usageForOrigin(modules, "engine");
  const project = usageForOrigin(modules, "project");
  const plugins = usageForOrigin(modules, "plugin");
  const reserved = { bank0: 0, wram: RESERVED_WRAM_BYTES, bankedRom: 0 };
  const capacity = capacityForCartType(cartType);
  const attributed = [engine, project, plugins, musicDriver, reserved].reduce(
    addRegionUsage,
    emptyRegionUsage(),
  );
  const gbdkRuntime = subtractRegionUsage(total, attributed);
 
  const invalidRegion = (["bank0", "wram", "bankedRom"] as const).find(
    (region) => gbdkRuntime[region] < 0,
  );
 
  if (invalidRegion) {
    throw new Error(
      `Attributed module usage exceeds linked ${invalidRegion} usage ` +
        `(attributed ${attributed[invalidRegion]}, linked ${total[invalidRegion]})`,
    );
  }
 
  return {
    cartType,
    engine,
    musicDriver,
    gbdkRuntime,
    project,
    plugins,
    reserved,
    total,
    maximum: capacity,
    remaining: subtractRegionUsage(capacity, total),
  };
};
 
export const calculateMemoryUsage = (
  usageData: RomUsageData,
  romCapacity: number,
): BuildUsageMemory => ({
  rom: calculateRomUsage(
    sumUsage(usageData.banks, isRomBank).used,
    romCapacity,
  ),
  bank0: sumUsage(usageData.banks, isRomBank0),
  wram: sumUsage(usageData.banks, isWramBank),
});
 
export const collectBuildUsage = async ({
  manifest,
  scriptMap,
  mode,
  tmpPath,
  progress,
  warnings,
}: {
  manifest: BuildManifest;
  scriptMap: Record<string, CompiledScriptSource[]>;
  mode: "complete" | "partial";
  tmpPath: string;
  progress: (message: string) => void;
  warnings: (message: string) => void;
}): Promise<UsageData> => {
  try {
    const modules = await analyseBuildObjects({
      manifest,
      allowMissing: mode === "partial",
    });
    const plugins = analysePluginUsage(modules);
    const usageSources: BuildUsageSource[] = modules.map((module) => ({
      sourceFile: module.sourceFile,
      usage: module.usage,
    }));
    const scripts: BuildUsageScript[] = usageSources
      .map((source) => {
        const symbol = Path.basename(
          source.sourceFile,
          Path.extname(source.sourceFile),
        );
        return {
          symbol,
          size: source.usage.bank0 + source.usage.bankedRom,
          sources: scriptMap[symbol] ?? [],
        };
      })
      .filter((script) => script.sources.length > 0)
      .sort((left, right) => right.size - left.size);
 
    if (mode === "partial") {
      return { status: "partial", plugins, scripts, sources: usageSources };
    }
 
    const usageData = await romUsage({
      manifest,
      tmpPath,
      progress,
      warnings,
    });
 
    const memory = calculateMemoryUsage(
      usageData,
      romCapacityForCartType(manifest.cartType),
    );
 
    const musicDriver = await analyseMusicDriverUsage({ manifest });
 
    const total: RegionUsage = {
      bank0: memory.bank0.used,
      wram: memory.wram.used,
      bankedRom: memory.rom.used - memory.bank0.used,
    };
 
    return {
      status: "complete",
      memory,
      overview: buildUsageOverview(
        modules,
        musicDriver,
        manifest.cartType,
        total,
      ),
      plugins,
      scripts,
      sources: usageSources,
    };
  } catch (error) {
    warnings(error instanceof Error ? error.message : String(error));
    return {
      status: "unavailable",
    };
  }
};