1286 lines
67 KiB
Python
1286 lines
67 KiB
Python
#!/usr/bin/env python3
|
|
"""REPENTOGON coverage: every item of REPENTOGON's surface, one row each, with its status in this rebuild.
|
|
|
|
Usage: python3 -I scripts/repentogon_coverage.py [--mods DIR]
|
|
Writes analysis/repentogon_coverage.tsv and prints counts by kind, area and status.
|
|
With --mods, also writes one test mod per area under DIR (tools/harness/repentogon by default when DIR is omitted).
|
|
|
|
Sources (repentogon/ is the pinned clone)
|
|
function, property, constructor
|
|
every registration in repentogon/repentogon (LuaInterfaces, ImGuiFeatures, Patches, LuaInit): luaL_Reg tables
|
|
consumed by lua::RegisterFunctions, lua::RegisterNewClass or luaL_setfuncs, lua::RegisterFunction,
|
|
lua::RegisterGlobalClassFunction, lua::RegisterVariable(Getter|Setter), lua::RegisterGlobalClassVariable,
|
|
lua::TableAssoc with a C function, lua_pushcfunction followed by lua_rawset or lua_setfield, lua_register.
|
|
A table filled inside "__propget" or "__propset" gives properties. "__call" and lua_register give the constructor,
|
|
named after its class. Functions main_ex.lua adds in Lua (rawset(Isaac, ...), function Isaac.X) are rows too.
|
|
Documented members found in no registration (vanilla functions changed through a hook) are rows marked "docs only".
|
|
callback ModCallbacks in resources/scripts/enums_ex.lua and docs/enums/ModCallbacks.md, merged by name
|
|
enum each table enums_ex.lua defines, and each vanilla enum it extends (one row, its value count in summary)
|
|
xml_attribute the attribute tables (and "Supported attributes" lists) of docs/xml/*.md
|
|
xml_tag each documented XML file and each tag its examples use
|
|
option each ini["Section"]["Key"] REPENTOGONOptions reads or writes
|
|
behaviour_patch each file in repentogon/repentogon/Patches, with a hand-written summary
|
|
|
|
Class of an unnamed table (luaL_setfuncs, TableAssoc, pushcfunction): the last luaL_newmetatable, PushMetatable,
|
|
lua_getglobal or "__class" string before it in the same function since the last lua_setglobal, else the next
|
|
lua_setglobal after it, else the class at the call site of the helper holding it, else the file's most common class.
|
|
|
|
Status rules (against this repository)
|
|
function, property, constructor
|
|
the rebuild registers a name on a class when src/ (src/lua, src/repentogon and helpers they call) passes it to
|
|
lua_method, lua_static, lua_field, lua_field_get or lua_property, or as {"Name", function} or lua_table_set,
|
|
inside lua_class_begin(state, "Class") or lua_namespace_begin(state, "Class"), or after lua_pushglobaltable for
|
|
_G. A helper with no class of its own takes the class at its call site. Class names are compared after
|
|
REPENTOGON's aliases (RoomConfig.Room is RoomConfig_Room, the _CBindings namespace is _Internals). A constructor is registered when the class registers "__call", and is vanilla when its class is.
|
|
done registered, and neither vanilla (dump/lua_bindings.tsv, analysis/lua_all.tsv) nor under a docs "Modified"
|
|
section
|
|
review registered, but vanilla or documented as modified: the vanilla behaviour exists, REPENTOGON's change
|
|
is unchecked
|
|
todo not registered
|
|
callback done when src/**/*.cpp names MC_X (comments stripped) for this id or an alias of it, review when that
|
|
callback is vanilla (id below 1000 or documented as modified), todo otherwise
|
|
Lua-defined function or property (summary "defined in Lua"): done when a .lua file under assets/repentogon or src
|
|
holds its defining line unchanged
|
|
enum done when a .lua file under assets/repentogon or src defines it (Name = { for a new enum, every
|
|
Name.Key = for an extension)
|
|
option done when a src/ .cpp or .h file holds the key as a string literal
|
|
behaviour_patch started when a src/ file names Patches/<File> in a comment
|
|
xml_attribute, xml_tag todo
|
|
analysis/repentogon_overrides.tsv (kind, class, name, status, optional), when present, is applied last: a later phase
|
|
that verifies an item by hand (an xml attribute, a patch, a reviewed vanilla change) records it there.
|
|
"""
|
|
|
|
import argparse
|
|
import bisect
|
|
import re
|
|
import sys
|
|
import time
|
|
from collections import Counter, defaultdict
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
RGON = ROOT / "repentogon"
|
|
SOURCES = RGON / "repentogon"
|
|
DOCS = RGON / "docs" / "docs"
|
|
ENUMS_EX = SOURCES / "resources" / "scripts" / "enums_ex.lua"
|
|
MAIN_EX = SOURCES / "resources" / "scripts" / "main_ex.lua"
|
|
LUA_CORE = RGON / "libzhl" / "LuaCore.cpp"
|
|
OPTIONS = SOURCES / "REPENTOGONOptions.h"
|
|
OUT = ROOT / "analysis" / "repentogon_coverage.tsv"
|
|
OVERRIDES = ROOT / "analysis" / "repentogon_overrides.tsv"
|
|
MODS_DEFAULT = ROOT / "tools" / "harness" / "repentogon"
|
|
VANILLA_TABLES = (ROOT / "dump" / "lua_bindings.tsv", ROOT / "analysis" / "lua_all.tsv")
|
|
|
|
COLUMNS = ("kind", "class", "name", "location", "docs", "area", "status", "summary")
|
|
KINDS = ("function", "property", "constructor", "callback", "xml_attribute", "xml_tag", "enum", "option",
|
|
"behaviour_patch")
|
|
AREAS = ("entities", "player", "npc", "familiar", "pickup", "tear and weapons", "game", "level and room",
|
|
"items and pools", "render and sprites", "hud and menus", "persistent data and saves", "audio", "input",
|
|
"console and debug", "misc")
|
|
VANILLA_CALLBACK_LIMIT = 1000
|
|
SUMMARY_WIDTH = 120
|
|
|
|
# Metamethods and LuaBridge plumbing, not part of the API a mod calls.
|
|
SKIPPED_NAMES = {"__index", "__newindex", "__gc", "__name", "__type", "__class", "__parent", "__propget", "__propset",
|
|
"__const", "__metatable"}
|
|
SKIPPED_DIRS = ("lua/", "resources", "resources-repentogon")
|
|
|
|
# Docs pages named differently from the metatable their functions are registered on.
|
|
DOC_CLASS_ALIASES = {"ItemConfig_Item": "Item", "ItemConfig_Costume": "Costume", "ItemConfig_Card": "Card",
|
|
"ItemConfig_PillEffect": "PillEffect", "ItemConfig": "Config", "RoomConfigRoom": "RoomConfig_Room",
|
|
"Pathfinder": "PathFinder", "Repentogon": "REPENTOGON", "EntitiesSaveState": "EntitySaveState",
|
|
"CcpContainer_RoomConfigSet": "RoomConfigSet"}
|
|
DOC_SKIPPED = {"docs", "index", "install", "install_zh"}
|
|
|
|
# The rebuild's names for REPENTOGON's classes, by namespace.
|
|
REBUILD_CLASS_ALIASES = {("RoomConfig", "Room"): "RoomConfig_Room", ("_CBindings", "_CBindings"): "_Internals"}
|
|
|
|
CLASS_AREAS = {
|
|
"entities": "Entity EntityRef EntityPtr EntityList EntityConfig EntityConfigEntity EntityDesc EntitySaveState "
|
|
"EntitiesSaveStateVector GridEntitiesSaveStateVector EntitySaveStateManager EntityEffect GridEntity "
|
|
"GridEntityDesc Capsule Shape",
|
|
"player": "EntityPlayer PlayerManager TemporaryEffect TemporaryEffects PocketItem History HistoryItem "
|
|
"CostumeSpriteDesc EntityConfigPlayer EntityConfigBaby QueueItemData",
|
|
"npc": "EntityNPC EntityDelirium PathFinder BossPool BossPoolManager",
|
|
"familiar": "EntityFamiliar",
|
|
"pickup": "EntityPickup EntitySlot",
|
|
"tear and weapons": "EntityTear EntityLaser EntityKnife EntityBomb EntityProjectile Weapon TearParams "
|
|
"ProjectileParams MultiShotParams",
|
|
"game": "Game Seeds ChallengeParam DailyChallenge Ambush GenericPrompt StageTransition REPENTOGON",
|
|
"level and room": "Level Room RoomDescriptor RoomConfig RoomConfig_Room RoomConfigSet RoomConfigStage "
|
|
"LevelGenerator LevelGeneratorEntry LevelGeneratorRoom Backdrop FXLayers FXParams Camera "
|
|
"RailManager LRoomAreaDesc LRoomTileDesc RoomTransition Spawn Entry RoomDescriptorDoors "
|
|
"RoomDescriptorDoorsConst",
|
|
"items and pools": "Config Item Card PillEffect Costume ItemPool LootList LootListEntry WeightedOutcomePicker "
|
|
"ProceduralItem ProceduralItemManager ProceduralEffect XMLData",
|
|
"render and sprites": "Sprite AnimationData AnimationFrame AnimationLayer AnimationState LayerState NullFrame "
|
|
"Color KColor ColorModifier ColorParams BlendMode Renderer SourceQuad DestinationQuad Beam "
|
|
"Point DebugRenderer Font FontRenderSettings Shader Image Transformer",
|
|
"hud and menus": "HUD PlayerHUD PlayerHUDHeart HistoryHUD HistoryHUDItem HUDMessage Minimap MinimapConfig "
|
|
"ScoreSheet MenuManager PauseMenu NightmareScene ItemOverlay",
|
|
"persistent data and saves": "PersistentGameData",
|
|
"audio": "MusicManager SFXManager",
|
|
"input": "Input",
|
|
"console and debug": "Console Debug ImGui ASMPatch _G _Internals",
|
|
"misc": "Isaac Vector RNG Options BitSet128",
|
|
}
|
|
CLASS_AREA = {name: area for area, names in CLASS_AREAS.items() for name in names.split()}
|
|
|
|
# Keyword rules for names that carry their area (callbacks, Isaac's functions), first match wins.
|
|
NAME_AREAS = (
|
|
(r"COMPLETION|ACHIEVEMENT|UNLOCK|SAVE|MODDATA|MARK|PERSISTENT", "persistent data and saves"),
|
|
(r"FAMILIAR|WISP|LOCUST", "familiar"),
|
|
(r"PLAYER|HEART|BIRTHRIGHT|COSTUME|POCKET|TRANSFORMATION", "player"),
|
|
(r"NPC|BOSS|DELIRIUM|CHAMPION", "npc"),
|
|
(r"PICKUP|SLOT|COIN", "pickup"),
|
|
(r"TEAR|LASER|KNIFE|BOMB|PROJECTILE|WEAPON|FIRE|BRIMSTONE|SPLIT", "tear and weapons"),
|
|
(r"HUD|MENU|OVERLAY|PAUSE|NIGHTMARE|MINIMAP|CUTSCENE|GIANTBOOK|POPUP|STAT", "hud and menus"),
|
|
(r"RENDER|SPRITE|SHADER|LIGHTING|OPENGL|DRAW|COLOR|ANIM", "render and sprites"),
|
|
(r"ROOM|LEVEL|GRID|BACKDROP|STAGE|AMBUSH|GREED|DOOR|WAVE|FLOOR|CURSE", "level and room"),
|
|
(r"COLLECTIBLE|TRINKET|ITEM|POOL|CARD|PILL|CRAFTING|PLANETARIUM|DEVIL|SHOP|CACHE", "items and pools"),
|
|
(r"SFX|MUSIC|SOUND|JINGLE", "audio"),
|
|
(r"INPUT|MOUSE|CONTROLLER|KEYBOARD|CURSOR", "input"),
|
|
(r"CONSOLE|COMMAND|AUTOCOMPLETE|DEBUG|IMGUI|LOG", "console and debug"),
|
|
(r"ENTITY|SPAWN|DAMAGE|DMG|KILL|DEATH", "entities"),
|
|
(r"GAME|UPDATE|EXIT|START|CHALLENGE|DAILY|SEED", "game"),
|
|
)
|
|
|
|
XML_AREAS = {"items": "items and pools", "pocketitems": "items and pools", "itempools": "items and pools",
|
|
"costumes": "player", "players": "player", "babies": "player", "edenhair": "player",
|
|
"entities": "entities", "bosscolors": "npc", "backdrops": "level and room", "ambush": "level and room",
|
|
"achievements": "persistent data and saves", "challenges": "persistent data and saves",
|
|
"cutscenes": "hud and menus", "giantbook": "hud and menus", "stringtable": "hud and menus"}
|
|
XML_FILE_ALIASES = {"edenahir.xml": "edenhair.xml"}
|
|
XML_CODE_FIRST = ("Patches/XMLData.cpp", "Patches/XMLPlayerExtras.cpp")
|
|
|
|
# One line per file of Patches/: its area and what it changes in the game.
|
|
PATCHES = {
|
|
"ASMPatches.cpp": ("console and debug", "Applies every byte patch at startup: log and console routing, mod and save "
|
|
"folders moved to REPENTOGON's data folder"),
|
|
"ASMPatches/ASMBagOfCrafting.cpp": ("items and pools", "Bag of Crafting pickup adds: MC_TRY_ADD_TO_BAG_OF_CRAFTING "
|
|
"and modded pickups"),
|
|
"ASMPatches/ASMCallbacks.cpp": ("misc", "Inline patches firing the callbacks a hook cannot reach (pause, HUD "
|
|
"messages, room placement, NPC removal and many more)"),
|
|
"ASMPatches/ASMCamera.cpp": ("level and room", "Keeps the room's single Camera alive for Lua and restores it on "
|
|
"destruction"),
|
|
"ASMPatches/ASMDelirium.cpp": ("npc", "Delirium transformation callbacks (pre, transform, post)"),
|
|
"ASMPatches/ASMEntityKnife.cpp": ("tear and weapons", "Melee knife hitbox initialisation"),
|
|
"ASMPatches/ASMEntityNPC.cpp": ("npc", "NPC speed and active enemy checks driven by entity config"),
|
|
"ASMPatches/ASMFixes.cpp": ("misc", "Vanilla bug fixes: modded crafting quality, smelted trinkets, pill "
|
|
"identification and effects, game state load, render target overflow, "
|
|
"familiar pathing"),
|
|
"ASMPatches/ASMGridEntityCollision.cpp": ("level and room", "Grid collision callbacks, deduplicated per frame "
|
|
"and grid index"),
|
|
"ASMPatches/ASMGridEntitySpawn.cpp": ("level and room", "Routes inlined grid spawns through "
|
|
"MC_PRE/POST_GRID_ENTITY_SPAWN"),
|
|
"ASMPatches/ASMGridEntitySpawn_Definitions.cpp": ("level and room", "Signature table of the inlined grid spawn "
|
|
"sites"),
|
|
"ASMPatches/ASMHud.cpp": ("hud and menus", "HistoryHUD render and recompute callbacks, smelted item images"),
|
|
"ASMPatches/ASMLevel.cpp": ("level and room", "Custom stage ids, level generation and room placement callbacks, "
|
|
"stage binaries"),
|
|
"ASMPatches/ASMLocalization.cpp": ("hud and menus", "Localised resource lookup in archives with an English "
|
|
"fallback"),
|
|
"ASMPatches/ASMMenu.cpp": ("hud and menus", "Mods menu font, language change from options, online and daily "
|
|
"menu selection"),
|
|
"ASMPatches/ASMPlayer.cpp": ("player", "Familiar checks, Mars double tap window, active charge, custom hurt "
|
|
"and death sounds, Lost Soul puddle"),
|
|
"ASMPatches/ASMPlayerManager.cpp": ("player", "Controller reassignment on restore and disconnect"),
|
|
"ASMPatches/ASMRender.cpp": ("hud and menus", "Planetarium chance on the stat HUD (option)"),
|
|
"ASMPatches/ASMRoom.cpp": ("level and room", "Ambush wave count, boss wave difficulty, Mega Satan ending, water, "
|
|
"room save state, clear delay, Blue Womb door"),
|
|
"ASMPatches/ASMSplitTears.cpp": ("tear and weapons", "MC_POST_FIRE_SPLIT_TEAR for every tear split"),
|
|
"ASMPatches/ASMStatusEffects.cpp": ("entities", "Status effect targets and Weakness for custom status effects"),
|
|
"ASMPatches/ASMTweaks.cpp": ("misc", "Small tweaks: Godhead partition, Tear Detonator, Hush veins, archive "
|
|
"checksums, console online, resource paths, exit prompt, music bound, "
|
|
"language"),
|
|
"AchievementsStuff.cpp": ("persistent data and saves", "Modded achievements: XML, saving, popups, "
|
|
"lockachievement, Isaac.GetAchievementIdByName"),
|
|
"Anm2Extras.cpp": ("render and sprites", "Per ANM2 and per layer extras: shaders and render flags"),
|
|
"CardsExtras.cpp": ("items and pools", "Card XML extras: availability conditions, hidden cards, weights in "
|
|
"GetCard"),
|
|
"ChallengesStuff.cpp": ("persistent data and saves", "Modded challenge completion, saving and menus"),
|
|
"CompletionTracker.cpp": ("persistent data and saves", "Completion marks for modded characters: saving, the "
|
|
"character menu and Isaac's completion functions"),
|
|
"ConsoleHooks.cpp": ("console and debug", "Console: REPENTOGON branding, command history kept on crash, new "
|
|
"commands, autocomplete"),
|
|
"CustomCache.cpp": ("items and pools", "Custom cache flags (customcache XML) evaluated on item, trinket and "
|
|
"effect changes"),
|
|
"CustomDevilPlanetariumChance.cpp": ("items and pools", "Devil and planetarium chance split into callback "
|
|
"steps"),
|
|
"CustomModManager.cpp": ("misc", "Per mod curses and mod entry extras"),
|
|
"CutsceneSkip.cpp": ("hud and menus", "Cutscenes skippable with input"),
|
|
"EntityConfigEx.cpp": ("entities", "entities2.xml extras: tags, erased enemies, Jera and reroll flags, familiar "
|
|
"buddies"),
|
|
"EntityManager.cpp": ("entities", "Entity lifetime tracking: factory, list reset, removal"),
|
|
"EntityPlus.cpp": ("entities", "Extra per entity data: water clip, flying override, init and remove"),
|
|
"EvaluateStats.cpp": ("items and pools", "XML item stats (tears, damage, range ...) applied at the vanilla steps "
|
|
"of EvaluateItems"),
|
|
"ExtraDebugRender.cpp": ("console and debug", "Draws FindInRadius and capsule queries (debug option)"),
|
|
"ExtraLives.cpp": ("player", "Custom extra lives and revives, MC_PRE_TRIGGER_PLAYER_DEATH"),
|
|
"ExtraRenderSteps.cpp": ("render and sprites", "Cursor initialised and rendered for the mouse control option"),
|
|
"FamiliarTags.cpp": ("familiar", "Familiar XML tags: damageable, blocks projectiles, charmable"),
|
|
"GetCoinValue.cpp": ("pickup", "Custom coin values, MC_PICKUP_GET_COIN_VALUE"),
|
|
"GridEntityPlus.cpp": ("level and room", "Extra per grid entity data and water clip"),
|
|
"ImagePatches.cpp": ("render and sprites", "Transparent render batch reuse fixes"),
|
|
"Init.cpp": ("misc", "Starts REPENTOGON's systems in Manager::Init"),
|
|
"InterpolV2.cpp": ("render and sprites", "Interpolated rendering between updates (option)"),
|
|
"ItemConfigEx.cpp": ("items and pools", "items.xml extras and custom item sounds"),
|
|
"ItemPoolManager.cpp": ("items and pools", "Custom item pools from XML, pool queries, Isaac.GetPoolIdByName"),
|
|
"ItemSpoofSystem.cpp": ("player", "Innate collectibles and trinkets counted by HasCollectible and friends"),
|
|
"JsonSavedata.h": ("persistent data and saves", "JSON helpers for REPENTOGON's own save data"),
|
|
"LagMetric.cpp": ("render and sprites", "Lag metric and laser sample caching"),
|
|
"MainMenuBlock.cpp": ("hud and menus", "Main menu input mask (MenuManager.SetInputMask)"),
|
|
"MesaShaderFix.cpp": ("render and sprites", "Shader loading fix for Mesa drivers"),
|
|
"MinimapPatches.cpp": ("hud and menus", "Minimap shader before its image renders"),
|
|
"MiscFixes.cpp": ("misc", "Fixes: null frames, missing entity configs, familiar followers, innate collectibles, "
|
|
"font drawing"),
|
|
"ModReloading.cpp": ("misc", "Mod reloading and workshop updates"),
|
|
"ModsMenuStuff.cpp": ("hud and menus", "Mods menu search bar and input"),
|
|
"NullItemsAndCostumes.cpp": ("player", "Custom null items and their costumes"),
|
|
"PlayerFeatures.cpp": ("player", "Modded character trinket handling, Greed donations, per save state"),
|
|
"PlayerTags.cpp": ("player", "players.xml tags: no shake, no Metronome, no expansion pack, nightmare portraits"),
|
|
"PocketItems.cpp": ("player", "Pocket item adds and removals with callbacks"),
|
|
"Quickstart.cpp": ("hud and menus", "Quickstart into the last save slot"),
|
|
"RoomConfigExtras.h": ("level and room", "Stage id mapping for Greed and alternate stages"),
|
|
"SaveImport.cpp": ("persistent data and saves", "Imports vanilla saves into REPENTOGON's save folder"),
|
|
"StagesStuff.cpp": ("level and room", "Custom floor music, backdrop and name, stage config ids, stage command"),
|
|
"VanillaTweaks.cpp": ("misc", "Option tweaks: better Void generation, Hush laser speed, quick room clear, "
|
|
"Hornfel, archive checks"),
|
|
"XMLData.cpp": ("misc", "Loads every content XML into XMLData, merges content and resources, custom backdrops, "
|
|
"cutscenes and stages"),
|
|
"XMLPlayerExtras.cpp": ("player", "players.xml extras: starting health and stats, health limit, custom "
|
|
"character menu"),
|
|
"Xml/XmlBossPools.cpp": ("npc", "bosspools.xml parsing for custom boss pools"),
|
|
}
|
|
|
|
STATE = r"\s*[^,()]+?\s*"
|
|
ARG = r"\s*([^,()]+?)\s*"
|
|
FN = r"\s*([\w:]+)\s*"
|
|
STR = r'\s*"([^"]*)"\s*'
|
|
EVENT_PATTERNS = {
|
|
"regfuncs": r"lua::RegisterFunctions\(" + STATE + "," + ARG + "," + FN + r"\)",
|
|
"newclass": r"lua::RegisterNewClass\(" + STATE + "," + ARG + "," + ARG + "," + FN + r"[,)]",
|
|
"setfuncs": r"luaL_setfuncs\(" + STATE + "," + FN + ",",
|
|
"regfunc": r"lua::RegisterFunction\(" + STATE + "," + ARG + "," + ARG + "," + FN + r"\)",
|
|
"globalfunc": r"lua::RegisterGlobalClassFunction\(" + STATE + "," + ARG + "," + STR + "," + FN + r"\)",
|
|
"regvar": r"lua::RegisterVariable(?:Getter|Setter)?\(" + STATE + "," + ARG + "," + ARG + ",",
|
|
"globalvar": r"lua::RegisterGlobalClassVariable(?:Setter)?\(" + STATE + "," + ARG + "," + STR + ",",
|
|
"tableassoc": r"lua::TableAssoc\(" + STATE + "," + STR + "," + FN + r"\)",
|
|
"pushstring": r"lua_pushstring\(" + STATE + "," + STR + r"\)",
|
|
"pushcfunction": r"lua_pushcfunction\(" + STATE + "," + FN + r"\)",
|
|
"rawset": r"lua_rawset\(",
|
|
"pop": r"lua_pop\(",
|
|
"setfield": r"lua_setfield\(" + STATE + "," + ARG + "," + STR + r"\)",
|
|
"register": r"lua_register\(" + STATE + "," + ARG + "," + FN + r"\)",
|
|
"marker": r"(?:luaL_newmetatable|lua::PushMetatable|lua_getglobal)\(" + STATE + "," + ARG + r"\)",
|
|
"setglobal": r"lua_setglobal\(" + STATE + "," + ARG + r"\)",
|
|
}
|
|
EVENT_RE = re.compile("|".join(f"(?P<{name}>{pattern})" for name, pattern in EVENT_PATTERNS.items()))
|
|
GROUP_INDEX = {name: EVENT_RE.groupindex[name] - 1 for name in EVENT_PATTERNS}
|
|
COMMENT_RE = re.compile(r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'', re.S)
|
|
ARRAY_RE = re.compile(r"luaL_Reg\s+([\w:]+)\s*\[\s*\w*\s*\]\s*=\s*\{")
|
|
ENTRY_RE = re.compile(r'\{\s*"([^"]+)"\s*,\s*&?([\w:]+)\s*\}')
|
|
FUNCTION_NAME_RE = re.compile(r"LUA_FUNCTION\(\s*(\w+)\s*\)|\bint\s+(\w+)\s*\(\s*lua_State\s*\*")
|
|
STRING_CONST_RE = re.compile(r'\b(\w+)\s*=\s*"([^"]+)"\s*;')
|
|
|
|
|
|
# A row of the table, keyed by kind, class and name.
|
|
class Item:
|
|
def __init__(self, kind, className, name, location="", summary=""):
|
|
self.kind = kind
|
|
self.className = className
|
|
self.name = name
|
|
self.location = location
|
|
self.summary = summary
|
|
self.docs = ""
|
|
self.area = ""
|
|
self.status = "todo"
|
|
self.isDocsModified = False
|
|
|
|
|
|
# Collects rows, merging duplicates, the first location winning.
|
|
class Table:
|
|
def __init__(self):
|
|
self.items = {}
|
|
|
|
def item_add(self, kind, className, name, location="", summary=""):
|
|
key = (kind, className, name)
|
|
item = self.items.get(key)
|
|
if item is None:
|
|
item = self.items[key] = Item(kind, className, name, location, summary)
|
|
elif not item.location:
|
|
item.location = location
|
|
return item
|
|
|
|
|
|
# Comments blanked (newlines kept) and, for the masked copy, string contents too, so offsets match the original.
|
|
def text_strip(text):
|
|
stripped = COMMENT_RE.sub(lambda m: m.group(0) if m.group(0)[0] in "\"'" else re.sub(r"[^\n]", " ", m.group(0)),
|
|
text)
|
|
masked = COMMENT_RE.sub(lambda m: m.group(0)[0] + " " * (len(m.group(0)) - 2) + m.group(0)[-1]
|
|
if m.group(0)[0] in "\"'" else re.sub(r"[^\n]", " ", m.group(0)), text)
|
|
return stripped, masked
|
|
|
|
|
|
def braces_match(masked):
|
|
matches = {}
|
|
stack = []
|
|
for index, char in enumerate(masked):
|
|
if char == "{":
|
|
stack.append(index)
|
|
elif char == "}" and stack:
|
|
matches[stack.pop()] = index
|
|
return matches
|
|
|
|
|
|
# Function bodies (name, params, body start, body end), walking into namespaces, classes and structs.
|
|
def functions_find(masked, matches):
|
|
spans = []
|
|
|
|
def blocks_walk(start, end):
|
|
index = start
|
|
segmentStart = start
|
|
while index < end:
|
|
char = masked[index]
|
|
if char in ";}":
|
|
segmentStart = index + 1
|
|
elif char == "{":
|
|
close = matches.get(index, end)
|
|
header = re.sub(r"(?m)^\s*#.*$", "", masked[segmentStart:index]).strip()
|
|
if re.search(r"\b(namespace|class|struct)\b", header) and not header.endswith(")"):
|
|
blocks_walk(index + 1, close)
|
|
elif re.search(r"\)[\w\s:<>&*\->]*$", header) and "=" not in header.split("(")[0]:
|
|
spans.append((function_name(header), function_params(header), index + 1, close))
|
|
index = close
|
|
segmentStart = close + 1
|
|
index += 1
|
|
|
|
blocks_walk(0, len(masked))
|
|
return spans
|
|
|
|
|
|
def function_name(header):
|
|
hook = re.search(r"HOOK_\w+\(\s*(\w+)\s*,\s*(\w+)", header)
|
|
if hook:
|
|
return f"HOOK:{hook.group(1)}::{hook.group(2)}"
|
|
named = re.search(r"(\w+)\s*\(", header)
|
|
return named.group(1) if named else ""
|
|
|
|
|
|
def function_params(header):
|
|
opened = header.find("(")
|
|
if opened < 0:
|
|
return []
|
|
params = args_split(header[opened + 1:header.rfind(")")])
|
|
return [re.sub(r"=.*", "", param).split()[-1].strip("*&") if param.split() else "" for param in params]
|
|
|
|
|
|
def args_split(text):
|
|
args = []
|
|
depth = 0
|
|
current = ""
|
|
for char in text:
|
|
if char in "(<{[":
|
|
depth += 1
|
|
elif char in ")>}]":
|
|
depth -= 1
|
|
if char == "," and depth == 0:
|
|
args.append(current.strip())
|
|
current = ""
|
|
else:
|
|
current += char
|
|
if current.strip():
|
|
args.append(current.strip())
|
|
return args
|
|
|
|
|
|
# What REPENTOGON's sources say a class expression names: metatable enums, MT constants, literals, local variables.
|
|
class Resolver:
|
|
def __init__(self, metaNames, stringConsts):
|
|
self.metaNames = metaNames
|
|
self.stringConsts = stringConsts
|
|
|
|
def class_resolve(self, expr, body=""):
|
|
expr = expr.strip()
|
|
literal = re.fullmatch(r'"([^"]+)"', expr)
|
|
if literal:
|
|
return literal.group(1)
|
|
metas = re.findall(r"Metatables::(\w+)", expr)
|
|
if metas:
|
|
meta = next((meta for meta in metas if not meta.startswith("CONST_")), metas[0])
|
|
return self.metaNames.get(meta.removeprefix("CONST_"))
|
|
globalClass = re.search(r"GlobalClasses::(\w+)", expr)
|
|
if globalClass:
|
|
return globalClass.group(1)
|
|
ident = re.search(r"(\w+)$", expr)
|
|
if not ident:
|
|
return None
|
|
name = ident.group(1)
|
|
if name in self.stringConsts:
|
|
return self.stringConsts[name]
|
|
assigned = re.search(rf"\b{name}\s*=\s*([^;]+);", body)
|
|
if assigned and assigned.group(1).strip() != expr:
|
|
return self.class_resolve(assigned.group(1), "")
|
|
loop = re.search(rf"for\s*\(\s*[\w:]+\s+{name}\s*:\s*(\w+)\s*\)", body)
|
|
if loop:
|
|
array = re.search(rf"\b{loop.group(1)}\s*\[\s*\d*\s*\]\s*=\s*\{{([^}}]*)\}}", body)
|
|
if array:
|
|
return self.class_resolve(array.group(1), "")
|
|
return None
|
|
|
|
|
|
# One C++ file's registrations: explicit rows go straight in, unnamed tables wait for their class.
|
|
class SourceFile:
|
|
def __init__(self, path, text, resolver, knownFunctions):
|
|
self.path = path
|
|
self.relative = str(path.relative_to(RGON))
|
|
self.stripped, masked = text_strip(text)
|
|
self.resolver = resolver
|
|
self.knownFunctions = knownFunctions
|
|
self.lineStarts = [0] + [m.end() for m in re.finditer("\n", self.stripped)]
|
|
matches = braces_match(masked)
|
|
self.functions = functions_find(masked, matches)
|
|
self.arrays = []
|
|
for match in ARRAY_RE.finditer(masked):
|
|
close = matches.get(match.end() - 1, len(masked))
|
|
entries = [(entry.group(1), entry.group(2), entry.start() + match.end())
|
|
for entry in ENTRY_RE.finditer(self.stripped[match.end():close])]
|
|
self.arrays.append((match.group(1), match.start(), entries))
|
|
self.usedArrays = set()
|
|
self.debugLines = debug_lines(text)
|
|
self.explicit = []
|
|
self.anonymous = []
|
|
self.unnamed = []
|
|
self.markersByFunction = {}
|
|
|
|
def location(self, offset):
|
|
return f"{self.relative}:{bisect.bisect_right(self.lineStarts, offset)}"
|
|
|
|
def array_find(self, name, offset):
|
|
candidates = [array for array in self.arrays if array[0] == name or array[0].endswith("::" + name)
|
|
or name.endswith("::" + array[0])]
|
|
before = [array for array in candidates if array[1] < offset]
|
|
chosen = before[-1] if before else (candidates[0] if candidates else None)
|
|
if chosen:
|
|
self.usedArrays.add(chosen[1])
|
|
return chosen[2] if chosen else []
|
|
|
|
def name_values(self, functionIndex, expr):
|
|
literal = re.fullmatch(r'\s*"([^"]+)"\s*', expr)
|
|
if literal:
|
|
return [(literal.group(1), None)]
|
|
name, params, _, _ = self.functions[functionIndex]
|
|
ident = expr.strip()
|
|
if ident not in params:
|
|
return []
|
|
position = params.index(ident)
|
|
values = []
|
|
for _, _, start, end in self.functions:
|
|
for call in re.finditer(rf"\b{name}\s*\(", self.stripped[start:end]):
|
|
args = args_split(self.call_args(start + call.end()))
|
|
if position < len(args):
|
|
value = re.fullmatch(r'\s*"([^"]+)"\s*', args[position])
|
|
if value:
|
|
values.append((value.group(1), start + call.start()))
|
|
return values
|
|
|
|
def call_args(self, offset):
|
|
depth = 1
|
|
index = offset
|
|
while index < len(self.stripped) and depth:
|
|
depth += {"(": 1, ")": -1}.get(self.stripped[index], 0)
|
|
index += 1
|
|
return self.stripped[offset:index - 1]
|
|
|
|
def events_parse(self):
|
|
for functionIndex, (_, _, start, end) in enumerate(self.functions):
|
|
self.function_parse(functionIndex, start, end)
|
|
|
|
def explicit_add(self, kind, classExpr, nameExpr, functionIndex, offset, body):
|
|
className = self.resolver.class_resolve(classExpr, body)
|
|
values = self.name_values(functionIndex, nameExpr)
|
|
if not values:
|
|
self.unnamed.append(f"{self.location(offset)} name {nameExpr.strip()} not found at any call site")
|
|
for name, callOffset in values:
|
|
self.explicit.append((kind, className, name, self.location(callOffset or offset), classExpr))
|
|
|
|
def function_parse(self, functionIndex, start, end):
|
|
body = self.stripped[start:end]
|
|
markers = []
|
|
setglobals = []
|
|
mode = None
|
|
pendingKey = None
|
|
pendingFunction = None
|
|
isClassNext = False
|
|
isParentNext = False
|
|
for event in EVENT_RE.finditer(body):
|
|
kind = event.lastgroup
|
|
groups = [group for group in event.groups()[GROUP_INDEX[kind]:GROUP_INDEX[kind] + 6]]
|
|
offset = start + event.start()
|
|
if kind != "pushstring" and isClassNext:
|
|
isClassNext = False
|
|
if kind != "marker" and isParentNext and kind != "pushstring":
|
|
isParentNext = False
|
|
if kind == "pushstring":
|
|
value = groups[1]
|
|
if value in ("__propget", "__propset"):
|
|
mode = "property"
|
|
pendingKey = None
|
|
elif value in ("__class", "__type"):
|
|
isClassNext = True
|
|
elif isClassNext:
|
|
markers.append((offset, value))
|
|
isClassNext = False
|
|
elif value == "__parent":
|
|
isParentNext = True
|
|
elif value == "__const":
|
|
mode = None
|
|
else:
|
|
pendingKey = (value, offset)
|
|
pendingFunction = None
|
|
elif kind == "pushcfunction":
|
|
pendingFunction = groups[1]
|
|
elif kind == "rawset":
|
|
if pendingKey and pendingFunction:
|
|
self.anonymous.append((mode or "function", pendingKey[0], pendingKey[1], functionIndex))
|
|
else:
|
|
mode = None
|
|
pendingKey = None
|
|
pendingFunction = None
|
|
elif kind == "pop":
|
|
mode = None
|
|
elif kind == "setfield":
|
|
if pendingFunction:
|
|
self.anonymous.append((mode or "function", groups[2], offset, functionIndex))
|
|
pendingFunction = None
|
|
pendingKey = None
|
|
elif kind == "tableassoc":
|
|
if groups[2].split("::")[-1] in self.knownFunctions:
|
|
self.anonymous.append((mode or "function", groups[1], offset, functionIndex))
|
|
elif kind == "setfuncs":
|
|
for name, _, entryOffset in self.array_find(groups[1], offset):
|
|
self.anonymous.append((mode or "function", name, entryOffset, functionIndex))
|
|
elif kind == "regfuncs":
|
|
className = self.resolver.class_resolve(groups[1], body)
|
|
for name, _, entryOffset in self.array_find(groups[2], offset):
|
|
self.explicit.append(("function", className, name, self.location(entryOffset), groups[1]))
|
|
elif kind == "newclass":
|
|
className = self.resolver.class_resolve(groups[1], body)
|
|
for name, _, entryOffset in self.array_find(groups[3], offset):
|
|
self.explicit.append(("function", className, name, self.location(entryOffset), groups[1]))
|
|
elif kind == "regfunc":
|
|
self.explicit_add("function", groups[1], groups[2], functionIndex, offset, body)
|
|
elif kind == "globalfunc":
|
|
self.explicit.append(("function", self.resolver.class_resolve(groups[1], body), groups[2],
|
|
self.location(offset), groups[1]))
|
|
elif kind == "regvar":
|
|
self.explicit_add("property", groups[1], groups[2], functionIndex, offset, body)
|
|
elif kind == "globalvar":
|
|
self.explicit.append(("property", self.resolver.class_resolve(groups[1], body), groups[2],
|
|
self.location(offset), groups[1]))
|
|
elif kind == "register":
|
|
className = self.resolver.class_resolve(groups[1], body)
|
|
self.explicit.append(("constructor", className, className, self.location(offset), groups[1]))
|
|
elif kind == "marker":
|
|
if isParentNext:
|
|
isParentNext = False
|
|
else:
|
|
className = self.resolver.class_resolve(groups[1], body)
|
|
if className:
|
|
markers.append((offset, className))
|
|
elif kind == "setglobal":
|
|
className = self.resolver.class_resolve(groups[1], body)
|
|
setglobals.append((offset, className))
|
|
markers.append((offset, None))
|
|
self.markersByFunction[functionIndex] = (markers, setglobals)
|
|
|
|
# The class an unnamed table entry at offset belongs to, from the markers around it or its helper's call site.
|
|
def class_at(self, functionIndex, offset, depth=0):
|
|
markers, setglobals = self.markersByFunction.get(functionIndex, ([], []))
|
|
before = [className for markerOffset, className in markers if markerOffset < offset]
|
|
if before and before[-1]:
|
|
return before[-1]
|
|
after = [className for globalOffset, className in setglobals if globalOffset > offset and className]
|
|
if after:
|
|
return after[0]
|
|
if depth > 2:
|
|
return None
|
|
name = self.functions[functionIndex][0]
|
|
for callerIndex, (_, _, start, end) in enumerate(self.functions):
|
|
call = re.search(rf"\b{re.escape(name)}\s*\(", self.stripped[start:end])
|
|
if call and callerIndex != functionIndex:
|
|
className = self.class_at(callerIndex, start + call.start(), depth + 1)
|
|
if className:
|
|
return className
|
|
return None
|
|
|
|
def rows_resolve(self):
|
|
rows = [(kind, className, name, location, expr) for kind, className, name, location, expr in self.explicit]
|
|
unresolved = []
|
|
for kind, name, offset, functionIndex in self.anonymous:
|
|
className = self.class_at(functionIndex, offset)
|
|
rows.append((kind, className, name, self.location(offset), ""))
|
|
counts = Counter(row[1] for row in rows if row[1])
|
|
fallback = counts.most_common(1)[0][0] if counts else self.path.stem.removeprefix("Lua")
|
|
resolved = []
|
|
for kind, className, name, location, expr in rows:
|
|
if className is None:
|
|
className = fallback
|
|
unresolved.append(f"{location} {name}: class guessed as {fallback} ({expr or 'unnamed table'})")
|
|
isDebug = int(location.rsplit(":", 1)[1]) in self.debugLines
|
|
resolved.append((kind, className, name, location, "debug builds only" if isDebug else ""))
|
|
unused = [f"{self.location(offset)} luaL_Reg {name}" for name, offset, entries in self.arrays
|
|
if offset not in self.usedArrays and entries]
|
|
return resolved, unresolved + unused + self.unnamed
|
|
|
|
|
|
# Lines inside #ifndef NDEBUG or #ifdef _DEBUG: registrations only debug builds make.
|
|
def debug_lines(text):
|
|
lines = set()
|
|
stack = []
|
|
for number, line in enumerate(text.splitlines(), 1):
|
|
directive = re.match(r"\s*#\s*(if\w*|endif)\b\s*(\w*)", line)
|
|
if directive and directive.group(1).startswith("if"):
|
|
stack.append(directive.group(1) == "ifndef" and directive.group(2) == "NDEBUG"
|
|
or directive.group(2) in ("_DEBUG", "DEBUG"))
|
|
elif directive and stack:
|
|
stack.pop()
|
|
if any(stack):
|
|
lines.add(number)
|
|
return lines
|
|
|
|
|
|
def metatable_names():
|
|
text = LUA_CORE.read_text(errors="replace")
|
|
names = dict((meta, name) for name, meta in
|
|
re.findall(r'_metatable_idx_from_name\["([^"]+)"\]\s*=\s*Metatables::(\w+)', text)
|
|
if not name.startswith("const "))
|
|
return names
|
|
|
|
|
|
def cpp_sources():
|
|
for path in sorted(SOURCES.rglob("*.cpp")):
|
|
relative = str(path.relative_to(SOURCES))
|
|
if not relative.startswith(SKIPPED_DIRS):
|
|
yield path
|
|
|
|
|
|
def registrations_load(table, problems):
|
|
texts = {path: path.read_text(errors="replace") for path in cpp_sources()}
|
|
knownFunctions = set()
|
|
stringConsts = {}
|
|
for text in list(texts.values()) + [LUA_CORE.read_text(errors="replace")] + \
|
|
[path.read_text(errors="replace") for path in SOURCES.rglob("*.h")]:
|
|
for match in FUNCTION_NAME_RE.finditer(text):
|
|
knownFunctions.add(match.group(1) or match.group(2))
|
|
for name, value in STRING_CONST_RE.findall(text):
|
|
stringConsts.setdefault(name, value)
|
|
resolver = Resolver(metatable_names(), stringConsts)
|
|
rawCount = 0
|
|
allRows = []
|
|
for path, text in texts.items():
|
|
source = SourceFile(path, text, resolver, knownFunctions)
|
|
source.events_parse()
|
|
rows, unresolved = source.rows_resolve()
|
|
problems.extend(unresolved)
|
|
rawCount += len(rows)
|
|
allRows += rows
|
|
classes = Counter(row[1] for row in allRows if row[0] != "constructor")
|
|
for kind, className, name, location, summary in allRows:
|
|
if name in SKIPPED_NAMES:
|
|
continue
|
|
if kind == "constructor" and not classes[className]:
|
|
kind = "function"
|
|
className = "_G"
|
|
if name == "__call":
|
|
kind = "constructor"
|
|
name = className
|
|
table.item_add(kind, className, name, location, summary)
|
|
return rawCount
|
|
|
|
|
|
# Functions and properties main_ex.lua and repentogon_api add from Lua: rawset on a class or its metatable, function
|
|
# Class.Name, Class.Name = function, a global table of functions, and calls of local helpers that rawset a preset.
|
|
def lua_functions_load(table):
|
|
for path in [MAIN_EX] + sorted((SOURCES / "resources" / "scripts" / "repentogon_api").glob("*.lua")):
|
|
text = path.read_text(errors="replace")
|
|
lines = text.splitlines()
|
|
localFunctions = set(re.findall(r"(?m)^\s*(?:local\s+)?function\s+(\w+)\s*\(", text))
|
|
presetHelpers = dict(re.findall(r"function\s+(\w+)\s*\([^)]*\)\s*\n\s*rawset\(getmetatable\((\w+)\),\s*\w+", text))
|
|
tableName = None
|
|
for number, line in enumerate(lines, 1):
|
|
location = f"{path.relative_to(RGON)}:{number}"
|
|
opened = re.match(r"([A-Z]\w*)\s*=\s*\{\s*$", line)
|
|
if opened:
|
|
tableName = opened.group(1)
|
|
continue
|
|
if tableName:
|
|
if line.startswith("}"):
|
|
tableName = None
|
|
continue
|
|
key = re.match(r"\s*(\w+)\s*=", line)
|
|
if key:
|
|
table_lua_add(table, "function", tableName, key.group(1), location, line)
|
|
continue
|
|
preset = re.match(r'\s*rawset\(getmetatable\(([A-Z]\w*)\),\s*"(\w+)"', line)
|
|
helper = re.match(r'\s*(\w+)\("(\w+)"', line)
|
|
if preset or (helper and helper.group(1) in presetHelpers):
|
|
className, name = preset.groups() if preset else (presetHelpers[helper.group(1)], helper.group(2))
|
|
table_lua_add(table, "property", className, name, location, line)
|
|
continue
|
|
found = re.match(r'\s*rawset\(\s*([A-Z]\w*)\s*,\s*"(\w+)"\s*,\s*(.*)', line) \
|
|
or re.match(r"\s*function\s+([A-Z]\w*)[.:](\w+)\s*\(()", line) \
|
|
or re.match(r"\s*([A-Z]\w*)\.(\w+)\s*=\s*(function\b.*|\w+\s*$)", line)
|
|
if not found:
|
|
continue
|
|
className, name, value = found.groups()
|
|
valueName = re.match(r"[\w.]*", value.strip()).group(0)
|
|
if value.strip() and valueName != "function" and valueName not in localFunctions:
|
|
continue
|
|
className = className.removesuffix("MT") if className.endswith("MT") else className
|
|
isCall = name == "__call"
|
|
table_lua_add(table, "constructor" if isCall else "function", className, className if isCall else name,
|
|
location, line)
|
|
|
|
|
|
def table_lua_add(table, kind, className, name, location, line):
|
|
if name in SKIPPED_NAMES:
|
|
return
|
|
item = table.item_add(kind, className, name, location, "defined in Lua")
|
|
if not item.summary:
|
|
item.summary = "defined in Lua"
|
|
item.luaLine = line.strip()
|
|
|
|
|
|
def docs_load(table):
|
|
docs = {}
|
|
for path in sorted(DOCS.glob("*.md")):
|
|
if path.stem in DOC_SKIPPED:
|
|
continue
|
|
className = DOC_CLASS_ALIASES.get(path.stem, path.stem)
|
|
section = ""
|
|
for line in path.read_text(errors="replace").splitlines():
|
|
if line.startswith("## "):
|
|
section = line[3:].strip()
|
|
elif line.startswith("### ") and section:
|
|
name = re.match(r"###\s+([\w.:]+)", line)
|
|
if not name:
|
|
continue
|
|
isVariable = bool(re.search(r"Variable|Constant|Attribute", section))
|
|
kind = "constructor" if "Constructor" in section else "property" if isVariable else "function"
|
|
memberName = name.group(1).split(".")[-1].split(":")[-1]
|
|
docs[(kind, className, memberName)] = (f"{path.name}", section.startswith("Modified"))
|
|
luaLines = [(path, number, line) for path in [MAIN_EX] + sorted((SOURCES / "resources" / "scripts" /
|
|
"repentogon_api").glob("*.lua"))
|
|
for number, line in enumerate(path.read_text(errors="replace").splitlines(), 1)]
|
|
for (kind, className, name), (page, isModified) in docs.items():
|
|
item = table.items.get((kind, className, name)) or \
|
|
next((table.items[key] for key in ((other, className, name) for other in KINDS) if key in table.items),
|
|
None)
|
|
if item is None:
|
|
note = "docs only: vanilla changed through a hook" if isModified else "docs only: no registration found"
|
|
defined = next(((path, number, line) for path, number, line in luaLines
|
|
if re.match(rf"\s*{name}\s*=", line)), None)
|
|
if defined:
|
|
table_lua_add(table, kind, className, name, f"{defined[0].relative_to(RGON)}:{defined[1]}",
|
|
defined[2])
|
|
item = table.item_add(kind, className, name, "", note)
|
|
item.docs = page
|
|
item.isDocsModified = item.isDocsModified or isModified
|
|
return docs
|
|
|
|
|
|
def callbacks_load(table):
|
|
entries = {}
|
|
for number, line in enumerate(ENUMS_EX.read_text().splitlines(), 1):
|
|
found = re.match(r"ModCallbacks\.(MC_\w+)\s*=\s*(\d+)", line)
|
|
if found:
|
|
entries.setdefault(found.group(1), [int(found.group(2)), f"{ENUMS_EX.relative_to(RGON)}:{number}",
|
|
"", False])
|
|
page = DOCS / "enums" / "ModCallbacks.md"
|
|
section = ""
|
|
for line in page.read_text(errors="replace").splitlines():
|
|
if line.startswith("## "):
|
|
section = line
|
|
found = re.match(r"###\s+(MC_\w+)", line)
|
|
if found:
|
|
entry = entries.setdefault(found.group(1), [None, "", "", False])
|
|
entry[2] = "enums/ModCallbacks.md"
|
|
entry[3] = "Modified" in section
|
|
row = re.match(r"\|\s*(\d+)\s*\|\s*(MC_\w+)", line)
|
|
if row and row.group(2) in entries and entries[row.group(2)][0] is None:
|
|
entries[row.group(2)][0] = int(row.group(1))
|
|
for name, (callbackId, location, docs, isModified) in entries.items():
|
|
isVanilla = isModified or (callbackId is not None and callbackId < VANILLA_CALLBACK_LIMIT)
|
|
summary = f"id {callbackId}" + (", vanilla callback REPENTOGON changes" if isVanilla else "")
|
|
item = table.item_add("callback", "ModCallbacks", name, location, summary)
|
|
item.docs = docs
|
|
item.isDocsModified = isVanilla
|
|
item.callbackId = callbackId
|
|
|
|
|
|
def enums_load(table):
|
|
lines = ENUMS_EX.read_text().splitlines()
|
|
extended = defaultdict(list)
|
|
for number, line in enumerate(lines, 1):
|
|
created = re.match(r"(\w+)\s*=\s*\{", line)
|
|
if created:
|
|
table.item_add("enum", "enums_ex.lua", created.group(1), f"{ENUMS_EX.relative_to(RGON)}:{number}",
|
|
"new enum")
|
|
added = re.match(r"(\w+)\.(\w+)\s*=", line)
|
|
if added and added.group(1) != "ModCallbacks":
|
|
extended[added.group(1)].append((number, added.group(2)))
|
|
for name, values in extended.items():
|
|
item = table.item_add("enum", "enums_ex.lua", name, f"{ENUMS_EX.relative_to(RGON)}:{values[0][0]}",
|
|
f"extends the vanilla enum: {len(values)} values")
|
|
item.enumKeys = [key for _, key in values]
|
|
for item in table.items.values():
|
|
if item.kind == "enum" and (DOCS / "enums" / f"{item.name}.md").exists():
|
|
item.docs = f"enums/{item.name}.md"
|
|
|
|
|
|
def xml_load(table):
|
|
codeHits = {}
|
|
files = [SOURCES / relative for relative in XML_CODE_FIRST] + \
|
|
[path for path in sorted(SOURCES.rglob("*.cpp")) if str(path.relative_to(SOURCES)) not in XML_CODE_FIRST]
|
|
for path in files:
|
|
if str(path.relative_to(SOURCES)).startswith(SKIPPED_DIRS):
|
|
continue
|
|
for number, line in enumerate(path.read_text(errors="replace").splitlines(), 1):
|
|
for literal in re.findall(r'"([a-z][a-z0-9_]*)"', line):
|
|
codeHits.setdefault(literal, f"{path.relative_to(RGON)}:{number}")
|
|
for path in sorted((DOCS / "xml").glob("*.md")):
|
|
if path.stem == "overview":
|
|
continue
|
|
text = path.read_text(errors="replace")
|
|
title = re.search(r'# File "([^"]+)"', text)
|
|
fileName = title.group(1).split()[0] if title else path.stem + ".xml"
|
|
fileName = XML_FILE_ALIASES.get(fileName, fileName)
|
|
area = XML_AREAS.get(path.stem, "misc")
|
|
docs = f"xml/{path.name}"
|
|
fileItem = table.item_add("xml_tag", fileName, fileName, "", "file: content and resources support")
|
|
fileItem.docs = docs
|
|
fileItem.area = area
|
|
for tag in sorted(set(re.findall(r"<(\w+)[\s/>]", "".join(re.findall(r"```xml(.*?)```", text, re.S))))):
|
|
item = table.item_add("xml_tag", fileName, tag, codeHits.get(tag, ""), "tag in the docs' examples")
|
|
item.docs = docs
|
|
item.area = area
|
|
section = ""
|
|
isTable = False
|
|
for line in text.splitlines():
|
|
if line.startswith("#"):
|
|
section = line.lstrip("#").strip()
|
|
if line.startswith("|") and "Variable-Name" in line:
|
|
isTable = True
|
|
continue
|
|
if not line.startswith("|"):
|
|
isTable = False
|
|
attributes = []
|
|
if isTable and not line.startswith("|:"):
|
|
cells = [cell.strip() for cell in line.strip("|").split("|")]
|
|
attributes = [(cells[0].strip("` "), cells[-1] if len(cells) > 2 else "")]
|
|
supported = re.match(r"Supported attributes:\s*(.*)", line)
|
|
if supported:
|
|
attributes = [(name, "stat attribute") for name in re.findall(r"`(\w+)`", supported.group(1))]
|
|
for name, description in attributes:
|
|
if not name:
|
|
continue
|
|
summary = section + ": " + re.sub(r"<[^>]+>|\s+", " ", description)
|
|
item = table.item_add("xml_attribute", fileName, name, codeHits.get(name.lower(), ""),
|
|
summary[:SUMMARY_WIDTH].strip())
|
|
item.docs = docs
|
|
item.area = area
|
|
|
|
|
|
def options_load(table):
|
|
for number, line in enumerate(OPTIONS.read_text().splitlines(), 1):
|
|
for section, key in re.findall(r'ini\["(\w+)"\]\["(\w+)"\]', line.split("//")[0]):
|
|
item = table.item_add("option", section, key, f"{OPTIONS.relative_to(RGON)}:{number}", "options.ini")
|
|
item.area = "console and debug" if re.search("Console|ImGui|Font|Debug|Unifont", key) else "misc"
|
|
|
|
|
|
def patches_load(table):
|
|
root = SOURCES / "Patches"
|
|
names = sorted(str(path.relative_to(root)) for path in root.rglob("*.cpp"))
|
|
names += sorted(str(path.relative_to(root)) for path in root.rglob("*.h")
|
|
if not path.with_suffix(".cpp").exists() and str(path.relative_to(root)) in PATCHES)
|
|
for name in names:
|
|
area, summary = PATCHES.get(name, ("misc", "no summary yet"))
|
|
item = table.item_add("behaviour_patch", "Patches", name, f"repentogon/Patches/{name}:1", summary)
|
|
item.area = area
|
|
|
|
|
|
def area_find(item):
|
|
if item.area:
|
|
return item.area
|
|
upperName = re.sub(r"(?<=[a-z])(?=[A-Z])", "_", item.name).upper()
|
|
if item.kind in ("callback", "enum"):
|
|
return name_area(upperName) or "misc"
|
|
area = CLASS_AREA.get(item.className)
|
|
if area is None and item.className.endswith("Menu"):
|
|
area = "hud and menus"
|
|
if area is None and item.className.startswith("GridEntity"):
|
|
area = "level and room"
|
|
if item.className in ("Isaac", "_G") or area is None:
|
|
area = name_area(upperName) or area
|
|
return area or "misc"
|
|
|
|
|
|
def name_area(name):
|
|
return next((area for pattern, area in NAME_AREAS if re.search(pattern, name)), None)
|
|
|
|
|
|
# What src/ registers, as {class: names}, following helpers without a class of their own to their call sites.
|
|
def rebuild_registrations():
|
|
files = {}
|
|
for path in sorted((ROOT / "src").rglob("*.cpp")) + sorted((ROOT / "src").rglob("*.h")):
|
|
text = path.read_text(errors="replace")
|
|
if "lua/api.h" not in text and path.parent.name not in ("lua", "repentogon"):
|
|
continue
|
|
stripped, masked = text_strip(text)
|
|
files[path] = (stripped, functions_find(masked, braces_match(masked)))
|
|
contextRe = re.compile(r'lua_(class|namespace)_begin\(\s*\w+\s*,\s*"(\w+)"|lua_push(global)table\(')
|
|
nameRe = re.compile(r'lua_(?:method|static|field|field_get|property)\s*(?:<[^;]*?>)?\s*\(\s*\w+\s*,\s*"(\w+)"'
|
|
r'|\{\s*"(\w+)"\s*,|lua_table_set\(\s*\w+\s*,\s*-?\d+\s*,\s*"(\w+)"\)')
|
|
bodies = {}
|
|
for path, (stripped, functions) in files.items():
|
|
for name, _, start, end in functions:
|
|
bodies[(path, name, start)] = stripped[start:end]
|
|
|
|
def class_name(namespace, name):
|
|
return REBUILD_CLASS_ALIASES.get((namespace, name), name)
|
|
|
|
def contexts(body):
|
|
events = []
|
|
namespace = None
|
|
for match in contextRe.finditer(body):
|
|
if match.group(3):
|
|
events.append((match.start(), "_G"))
|
|
continue
|
|
if match.group(1) == "namespace":
|
|
namespace = match.group(2)
|
|
events.append((match.start(), class_name(namespace, match.group(2))))
|
|
return events
|
|
|
|
callers = {}
|
|
|
|
def caller_classes(functionName, depth=0):
|
|
if functionName in callers:
|
|
return callers[functionName]
|
|
found = callers[functionName] = set()
|
|
for (path, name, start), body in bodies.items():
|
|
for call in re.finditer(rf"\b{re.escape(functionName)}\s*\(", body):
|
|
before = [className for offset, className in contexts(body) if offset < call.start()]
|
|
if before:
|
|
found.add(before[-1])
|
|
elif depth < 2:
|
|
found |= caller_classes(name, depth + 1)
|
|
return found
|
|
|
|
registered = defaultdict(set)
|
|
for (path, functionName, start), body in bodies.items():
|
|
events = contexts(body)
|
|
if not events and not re.search(r"\blua_(method|static|field|field_get|property|table_set|functions_add)\b", body):
|
|
continue
|
|
for match in nameRe.finditer(body):
|
|
name = match.group(1) or match.group(2) or match.group(3)
|
|
before = [className for offset, className in events if offset < match.start()]
|
|
for className in ([before[-1]] if before else caller_classes(functionName)):
|
|
registered[className].add(name)
|
|
return registered
|
|
|
|
|
|
def vanilla_names():
|
|
names = set()
|
|
for path in VANILLA_TABLES:
|
|
if not path.exists():
|
|
continue
|
|
for line in path.read_text(errors="replace").splitlines():
|
|
fields = line.split("\t")
|
|
if path.name == "lua_bindings.tsv" and len(fields) >= 2:
|
|
names.add((fields[0], fields[1]))
|
|
elif len(fields) >= 2 and "::" in fields[1]:
|
|
names.add(tuple(fields[1].split("::", 1)))
|
|
return names
|
|
|
|
|
|
def callbacks_fired():
|
|
fired = set()
|
|
for path in (ROOT / "src").rglob("*.cpp"):
|
|
stripped, _ = text_strip(path.read_text(errors="replace"))
|
|
fired |= set(re.findall(r"\bMC_[A-Z0-9_]+\b", COMMENT_RE.sub(" ", stripped)))
|
|
return fired
|
|
|
|
|
|
def status_compute(table):
|
|
registered = rebuild_registrations()
|
|
vanilla = vanilla_names()
|
|
vanillaClasses = {className for className, _ in vanilla}
|
|
fired = callbacks_fired()
|
|
firedIds = {item.callbackId for item in table.items.values()
|
|
if item.kind == "callback" and item.name in fired}
|
|
luaText = "\n".join(path.read_text(errors="replace") for folder in (ROOT / "assets" / "repentogon", ROOT / "src")
|
|
if folder.exists() for path in folder.rglob("*.lua"))
|
|
cppText = "\n".join(path.read_text(errors="replace") for path in (ROOT / "src").rglob("*.cpp"))
|
|
srcText = cppText + "\n".join(path.read_text(errors="replace") for path in (ROOT / "src").rglob("*.h"))
|
|
for item in table.items.values():
|
|
if getattr(item, "luaLine", None):
|
|
item.status = "done" if item.luaLine in luaText else "todo"
|
|
elif item.kind in ("function", "property", "constructor"):
|
|
names = registered.get(item.className, set())
|
|
isRegistered = ("__call" in names) if item.kind == "constructor" else item.name in names
|
|
isVanilla = (item.className, item.name) in vanilla or item.isDocsModified or \
|
|
(item.kind == "constructor" and item.className in vanillaClasses)
|
|
item.status = ("review" if isVanilla else "done") if isRegistered else "todo"
|
|
elif item.kind == "callback":
|
|
if item.callbackId in firedIds or item.name in fired:
|
|
item.status = "review" if item.isDocsModified else "done"
|
|
elif item.kind == "enum":
|
|
keys = getattr(item, "enumKeys", None)
|
|
isDefined = all(re.search(rf"\b{item.name}\.{key}\s*=", luaText) for key in keys) if keys else \
|
|
re.search(rf"(?m)^\s*{item.name}\s*=\s*\{{", luaText)
|
|
item.status = "done" if luaText and isDefined else "todo"
|
|
elif item.kind == "option":
|
|
item.status = "done" if f'"{item.name}"' in srcText else "todo"
|
|
elif item.kind == "behaviour_patch":
|
|
item.status = "started" if f"Patches/{item.name}" in srcText else "todo"
|
|
if OVERRIDES.exists():
|
|
for line in OVERRIDES.read_text().splitlines():
|
|
fields = line.split("\t")
|
|
if len(fields) >= 4 and (fields[0], fields[1], fields[2]) in table.items:
|
|
table.items[(fields[0], fields[1], fields[2])].status = fields[3]
|
|
|
|
|
|
def table_write(table):
|
|
rows = sorted(table.items.values(), key=lambda item: (KINDS.index(item.kind), item.className, item.name))
|
|
with OUT.open("w") as out:
|
|
out.write("\t".join(COLUMNS) + "\n")
|
|
for item in rows:
|
|
out.write("\t".join(str(value).replace("\t", " ") for value in (
|
|
item.kind, item.className, item.name, item.location, item.docs, item.area, item.status,
|
|
item.summary)) + "\n")
|
|
return rows
|
|
|
|
|
|
def summary_print(rows, rawCount, problems, elapsed):
|
|
statuses = sorted({item.status for item in rows})
|
|
print(f"{OUT.relative_to(ROOT)}: {len(rows)} rows ({rawCount} registrations read before merging), "
|
|
f"{elapsed:.1f}s")
|
|
for title, key, order in (("kind", "kind", KINDS), ("area", "area", AREAS)):
|
|
print(f"\n{'by ' + title:<28}{'total':>7}" + "".join(f"{status:>9}" for status in statuses))
|
|
counts = defaultdict(Counter)
|
|
for item in rows:
|
|
counts[getattr(item, key)][item.status] += 1
|
|
for name in order:
|
|
if counts[name]:
|
|
print(f"{name:<28}{sum(counts[name].values()):>7}" +
|
|
"".join(f"{counts[name][status]:>9}" for status in statuses))
|
|
totals = Counter(item.status for item in rows)
|
|
print(f"{'all':<28}{len(rows):>7}" + "".join(f"{totals[status]:>9}" for status in statuses))
|
|
docsOnly = sum(1 for item in rows if item.summary.startswith("docs only"))
|
|
undocumented = sum(1 for item in rows if item.kind in ("function", "property", "constructor") and not item.docs)
|
|
print(f"\nfunction rows only in the docs: {docsOnly}, registered but undocumented: {undocumented}")
|
|
if problems:
|
|
print(f"\nunparsed ({len(problems)}):")
|
|
for problem in problems:
|
|
print(f" {problem}")
|
|
|
|
|
|
def lua_string(text):
|
|
return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
|
|
|
|
# One mod per area: lists its functions, properties, constructors and callbacks, and checks each exists.
|
|
def mods_write(rows, folder):
|
|
for area in AREAS:
|
|
members = [item for item in rows if item.area == area and item.kind in ("function", "property", "constructor")]
|
|
callbacks = [item for item in rows if item.area == area and item.kind == "callback"]
|
|
if not members and not callbacks:
|
|
continue
|
|
slug = "rgon_" + area.replace(" and ", "_").replace(" ", "_")
|
|
directory = folder / slug
|
|
directory.mkdir(parents=True, exist_ok=True)
|
|
(directory / "metadata.xml").write_text(METADATA_TEMPLATE.format(name=f"REPENTOGON test {area}",
|
|
directory=slug))
|
|
checks = "\n".join(f"\t{{{lua_string(item.className)}, {lua_string(item.name)}, {lua_string(item.kind)}}},"
|
|
for item in members)
|
|
callbackNames = "\n".join(f"\t{lua_string(item.name)}," for item in callbacks)
|
|
(directory / "main.lua").write_text(MOD_TEMPLATE.replace("@AREA@", area).replace("@CHECKS@", checks)
|
|
.replace("@CALLBACKS@", callbackNames))
|
|
expected = directory / "expected.lua"
|
|
if not expected.exists():
|
|
expected.write_text(EXPECTED_TEMPLATE)
|
|
print(f"\ntest mods written to {folder}")
|
|
|
|
|
|
METADATA_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
|
|
<metadata>
|
|
<name>{name}</name>
|
|
<directory>{directory}</directory>
|
|
<description>Generated by scripts/repentogon_coverage.py: checks REPENTOGON's surface for one area.</description>
|
|
<version>1.0</version>
|
|
<visibility>Private</visibility>
|
|
</metadata>
|
|
"""
|
|
|
|
EXPECTED_TEMPLATE = """-- Hand-written expectations for this area's checks, kept when scripts/repentogon_coverage.py regenerates main.lua.
|
|
-- ["Class.Name"] = {args = {...}, result = value}: the check calls the member on its object with args and compares.
|
|
return {
|
|
}
|
|
"""
|
|
|
|
MOD_TEMPLATE = """-- Generated by scripts/repentogon_coverage.py for the area "@AREA@": regenerating rewrites this file, not expected.lua.
|
|
-- When a run starts it prints one line per item: PASS, FAIL (with the reason) or SKIP (no object to test on).
|
|
-- An item passes when it exists, and with an entry in expected.lua, when calling it with args returns result.
|
|
|
|
local AREA = "@AREA@"
|
|
|
|
-- {class, name, kind} from analysis/repentogon_coverage.tsv.
|
|
local CHECKS = {
|
|
@CHECKS@
|
|
}
|
|
|
|
local CALLBACKS = {
|
|
@CALLBACKS@
|
|
}
|
|
|
|
local isLoaded, loaded = pcall(include, "expected")
|
|
local EXPECTED = isLoaded and type(loaded) == "table" and loaded or {}
|
|
|
|
local mod = RegisterMod("REPENTOGON test " .. AREA, 1)
|
|
local game = Game()
|
|
|
|
-- An object of the class to test on: a singleton, a fresh value or the class's global table.
|
|
local OBJECTS = {
|
|
Game = function() return game end,
|
|
Room = function() return game:GetRoom() end,
|
|
Level = function() return game:GetLevel() end,
|
|
HUD = function() return game:GetHUD() end,
|
|
Seeds = function() return game:GetSeeds() end,
|
|
ItemPool = function() return game:GetItemPool() end,
|
|
Config = function() return Isaac.GetItemConfig() end,
|
|
RoomDescriptor = function() return game:GetLevel():GetCurrentRoomDesc() end,
|
|
EntityPlayer = function() return Isaac.GetPlayer(0) end,
|
|
Entity = function() return Isaac.GetPlayer(0) end,
|
|
TemporaryEffects = function() return Isaac.GetPlayer(0):GetEffects() end,
|
|
CostumeSpriteDesc = function() return Isaac.GetPlayer(0):GetCostumeSpriteDescs()[1] end,
|
|
EntityConfigPlayer = function() return Isaac.GetPlayer(0):GetEntityConfigPlayer() end,
|
|
EntityConfigBaby = function() return EntityConfig.GetBaby(0) end,
|
|
Backdrop = function() return game:GetRoom():GetBackdrop() end,
|
|
Camera = function() return game:GetRoom():GetCamera() end,
|
|
FXLayers = function() return game:GetRoom():GetFXLayers() end,
|
|
FXParams = function() return game:GetRoom():GetFXParams() end,
|
|
RailManager = function() return game:GetRoom():GetRailManager() end,
|
|
LRoomAreaDesc = function() return game:GetRoom():GetLRoomAreaDesc() end,
|
|
LRoomTileDesc = function() return game:GetRoom():GetLRoomTileDesc() end,
|
|
RoomConfigStage = function() return RoomConfig.GetStage(1) end,
|
|
RoomConfigSet = function() return RoomConfig.GetStage(1):GetRoomSet(0) end,
|
|
RoomConfig_Room = function() return game:GetLevel():GetCurrentRoomDesc().Data end,
|
|
LevelGeneratorEntry = function() return Isaac.LevelGeneratorEntry() end,
|
|
PersistentGameData = function() return Isaac.GetPersistentGameData() end,
|
|
History = function() return Isaac.GetPlayer(0):GetHistory() end,
|
|
HistoryItem = function() return Isaac.GetPlayer(0):GetHistory():GetCollectiblesHistory()[1] end,
|
|
PocketItem = function() return Isaac.GetPlayer(0):GetPocketItem(0) end,
|
|
ChallengeParam = function() return game:GetChallengeParams() end,
|
|
GenericPrompt = function() return GenericPrompt() end,
|
|
GridEntityDoor = function() for i = 0, 7 do local d = game:GetRoom():GetDoor(i) if d then return d end end end,
|
|
GridEntityRock = function() local r = game:GetRoom() for i = 0, r:GetGridSize() - 1 do local g = r:GetGridEntity(i) if g and g:ToRock() then return g:ToRock() end end end,
|
|
Sprite = function() return Sprite() end,
|
|
RNG = function() return RNG() end,
|
|
Vector = function() return Vector(0, 0) end,
|
|
Color = function() return Color(1, 1, 1, 1) end,
|
|
KColor = function() return KColor(1, 1, 1, 1) end,
|
|
MusicManager = function() return MusicManager() end,
|
|
SFXManager = function() return SFXManager() end,
|
|
Font = function() return Font() end,
|
|
Capsule = function() return Capsule(Vector(0, 0), Vector(10, 0), 5) end,
|
|
Shape = function() return Isaac.GetPlayer(0):GetDebugShape(false) end,
|
|
EntityDesc = function() return EntityDesc() end,
|
|
EntityConfigEntity = function() return EntityConfig.GetEntity(10) end,
|
|
EntityEffect = function() return Isaac.Spawn(1000, 54, 0, Vector(0, 0), Vector(0, 0), nil):ToEffect() end,
|
|
GridEntity = function() local r = game:GetRoom() for i = 0, r:GetGridSize() - 1 do if r:GetGridEntity(i) then return r:GetGridEntity(i) end end end,
|
|
EntitiesSaveStateVector = function() return game:GetLevel():GetCurrentRoomDesc():GetEntitiesSaveState() end,
|
|
GridEntitiesSaveStateVector = function() return game:GetLevel():GetCurrentRoomDesc():GetGridEntitiesSaveState() end,
|
|
EntitySaveState = function() return game:GetLevel():GetCurrentRoomDesc():GetEntitiesSaveState():Get(0) end,
|
|
}
|
|
|
|
local function object_get(class)
|
|
local getter = OBJECTS[class]
|
|
if getter then return getter() end
|
|
return rawget(_G, class)
|
|
end
|
|
|
|
local function result_print(outcome, class, name, reason)
|
|
print(string.format("%s %s %s.%s%s", outcome, AREA, class, name, reason and (" " .. reason) or ""))
|
|
end
|
|
|
|
local function check_run(check, counts)
|
|
local class, name, kind = check[1], check[2], check[3]
|
|
if kind == "constructor" then
|
|
local global = rawget(_G, class)
|
|
local isCallable = type(global) == "function" or (getmetatable(global) or {}).__call ~= nil
|
|
counts[isCallable and "pass" or "fail"] = counts[isCallable and "pass" or "fail"] + 1
|
|
return result_print(isCallable and "PASS" or "FAIL", class, name, not isCallable and "not callable" or nil)
|
|
end
|
|
local isFound, object = pcall(object_get, class)
|
|
if not isFound or object == nil then
|
|
counts.skip = counts.skip + 1
|
|
return result_print("SKIP", class, name, "no object")
|
|
end
|
|
local isRead, value = pcall(function() return object[name] end)
|
|
if not isRead or (kind ~= "property" and value == nil) then
|
|
counts.fail = counts.fail + 1
|
|
return result_print("FAIL", class, name, isRead and "missing" or tostring(value))
|
|
end
|
|
local expected = EXPECTED[class .. "." .. name]
|
|
if expected then
|
|
local isCalled, result = pcall(value, object, table.unpack(expected.args or {}))
|
|
if not isCalled or result ~= expected.result then
|
|
counts.fail = counts.fail + 1
|
|
return result_print("FAIL", class, name, "got " .. tostring(result))
|
|
end
|
|
end
|
|
counts.pass = counts.pass + 1
|
|
result_print("PASS", class, name)
|
|
end
|
|
|
|
mod:AddCallback(ModCallbacks.MC_POST_GAME_STARTED, function()
|
|
local counts = {pass = 0, fail = 0, skip = 0}
|
|
for _, check in ipairs(CHECKS) do check_run(check, counts) end
|
|
for _, name in ipairs(CALLBACKS) do
|
|
local isKnown = ModCallbacks[name] ~= nil
|
|
counts[isKnown and "pass" or "fail"] = counts[isKnown and "pass" or "fail"] + 1
|
|
result_print(isKnown and "PASS" or "FAIL", "ModCallbacks", name, not isKnown and "missing" or nil)
|
|
end
|
|
print(string.format("DONE %s pass %d fail %d skip %d", AREA, counts.pass, counts.fail, counts.skip))
|
|
end)
|
|
"""
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="REPENTOGON coverage table")
|
|
parser.add_argument("--mods", nargs="?", const=str(MODS_DEFAULT), help="also write the per area test mods")
|
|
args = parser.parse_args()
|
|
started = time.time()
|
|
table = Table()
|
|
problems = []
|
|
rawCount = registrations_load(table, problems)
|
|
lua_functions_load(table)
|
|
docs_load(table)
|
|
callbacks_load(table)
|
|
enums_load(table)
|
|
xml_load(table)
|
|
options_load(table)
|
|
patches_load(table)
|
|
for item in table.items.values():
|
|
item.area = area_find(item)
|
|
status_compute(table)
|
|
rows = table_write(table)
|
|
summary_print(rows, rawCount, problems, time.time() - started)
|
|
if args.mods:
|
|
mods_write(rows, Path(args.mods))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|