Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Repr improvement #6597

Open
wants to merge 19 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/snippets/other.6597.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- (#6597) Improve the details printed by `repr`: print base class names, function sources, and skip __index tables that reference their parent.
152 changes: 138 additions & 14 deletions lua/system/repr.lua
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
---@field buf table
---@field depth integer
---@field level integer
---@field ids table<any, integer>
---@field ids table<type, integer> | table<any, integer|string>
---@field newline string
---@field meta boolean
---@field indent string
Expand All @@ -47,12 +47,18 @@ local tostring = tostring
local rep = string.rep
local flr = math.floor
local match = string.match
local substr = string.sub
local gsub = string.gsub
local fmt = string.format
local _rawget = rawget
local type = type
local getmetatable = getmetatable
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like this diversity in variable naming. It was discussed 3 years ago and we still mix this and that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have a link to the discussion? I haven't seen it.

local debugGetInfo = debug.getinfo
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you make upvalued functions of certain libraries as Pascal case then follow it.


local TableSort = table.sort
local TableEmpty = table.empty

local DiskToLocal = DiskToLocal

---@param t table
---@return function
Expand Down Expand Up @@ -101,6 +107,7 @@ local luaKeywords = {
---@return boolean
local function isIdentifier(str)
return type(str) == "string" and
---@diagnostic disable-next-line: undefined-field
not not str:match("^[_%a][_%a%d]*$") and
not luaKeywords[str]
end
Expand Down Expand Up @@ -182,11 +189,120 @@ function Inspector:getId(v)
if not id then
local tv = type(v)
id = (ids[tv] or 0) + 1
ids[v], ids[tv] = id, id
ids[tv] = id
if tv == "function" then
local info = debugGetInfo(v, "S")
id = fmt("%s %s(%d)", id, DiskToLocal(substr(info.source, 2)--[[@as FileName]]), info.linedefined)
end
ids[v] = id
end
return tostring(id)
end

local VectorMeta = getmetatable(Vector2(0, 0))
local LazyVarMeta = import('/lua/lazyvar.lua').LazyVarMetaTable

-- Converts the `__name` field added to engine classes in `classes.lua` to a friendlier name
local CClassNameToString = {
-- moho classes that share the same name across user and sim

CPrefetchSet = "CPrefetchSet",
EntityCategory = "Entity Category",
-- sound_methods = "Sound", -- In moho but has no fields, including `__name`

--Sim moho classes

aibrain_methods = "AIBrain",
aipersonality_methods = "AIPersonality",
platoon_methods = "Platoon",

ScriptTask_Methods = "Script Task",

IEffect = "IEffect",
CDecalHandle = "Decal",

entity_methods = "Entity",

unit_methods = "Unit",
navigator_methods = "Navigator",
blip_methods = "Blip",
shield_methods = "Shield",
weapon_methods = "Weapon",
projectile_methods = "Projectile",
CollisionBeamEntity = "Collision Beam",
-- EconomyEvent = "EconomyEvent", -- In moho but has no fields, including `__name`

prop_methods = "Prop",
MotorFallDown = "MotorFallDown",

manipulator_methods = "Manipulator",
AimManipulator = "AimManipulator",
RotateManipulator = "RotateManipulator",
StorageManipulator = "StorageManipulator",
CollisionManipulator = "CollisionManipulator",
SlaveManipulator = "SlaveManipulator",
ThrustManipulator = "ThrustManipulator",
BoneEntityManipulator = "BoneEntityManipulator",
SlideManipulator = "SlideManipulator",
BuilderArmManipulator = "BuilderArmManipulator",
AnimationManipulator = "AnimationManipulator",
FootPlantManipulator = "FootPlantManipulator",

CDamage = "CDamage",
CAiAttackerImpl_methods = "CAiAttackerImpl",

--User moho classes

cursor_methods = "Cursor",

control_methods = "Control",
scrollbar_methods = "Scrollbar",
bitmap_methods = "Bitmap",
dragger_methods = "Dragger",
item_list_methods = "ItemList",
movie_methods = "Movie",
border_methods = "Border",
text_methods = "Text",
edit_methods = "Edit",
group_methods = "Group",
frame_methods = "Frame",

lobby_methods = "Lobby Communications",
discovery_service_methods = "Discovery Service",
ui_map_preview_methods = "Map Preview",
WldUIProvider_methods = "WldUIProvider",

UIWorldView = "WorldView",
userDecal_methods = "UserDecal",
world_mesh_methods = "WorldMesh",

mesh_methods = "mesh_methods",
histogram_methods = "Histogram",
PathDebugger_methods = "PathDebugger",

-- Shared class implemented in Lua
Trashbag = "Trashbag",
}

---@param v table | fa-class | fa-class-state
local function fafTableToString(v)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ObjectToString sounds more reasonable.

local mt = getmetatable(v)
if _rawget(v, "__State") then
return fmt("%s (State %s)", tostring(v), tostring(v.__StateIdentifier))
elseif mt == VectorMeta then
return fmt("%s (%s)", tostring(v), "Vector")
elseif mt == LazyVarMeta then
return fmt("%s (%s)", tostring(v), "LazyVar")
else
local friendlyName = CClassNameToString[mt.__name]
if friendlyName then
return fmt("%s (%s)", tostring(v), friendlyName)
else
return tostring(v)
end
end
end

---@param v any
function Inspector:putValue(v)
local buf = self.buf
Expand All @@ -200,11 +316,11 @@ function Inspector:putValue(v)
local t = v

if self.level >= self.depth then
puts(buf, string.format("{...} -- %s (%g bytes)", tostring(t), debug.allocatedsize(t)))
puts(buf, fmt("{...} -- %s (%g bytes)", fafTableToString(t), debug.allocatedsize(t)))
else
local keys, keysLen, seqLen = getKeys(t)

puts(buf, string.format("{ -- %s (%d bytes)", tostring(t), debug.allocatedsize(t)))
puts(buf, fmt("{ -- %s (%d bytes)", fafTableToString(t), debug.allocatedsize(t)))
self.level = self.level + 1

for i = 1, seqLen + keysLen do
Expand All @@ -223,23 +339,31 @@ function Inspector:putValue(v)
puts(buf, "]")
end
puts(buf, ' = ')
self:putValue(t[k])
if k == "__index" and tostring(t[k]) == tostring(t) then
puts(buf, fmt("{...} -- %s (%g bytes)", 'table (self): ' .. string.sub(tostring(v), 8), debug.allocatedsize(t)))
else
self:putValue(t[k])
end
end
end

local mt = getmetatable(t)
local mt
local checkMeta
if self.meta then
if type(mt) == 'table' and not table.empty(mt) then
if seqLen + keysLen > 0 then puts(buf, ',') end
tabify(self)
puts(buf, '<metatable> = ')
self:putValue(mt)
end
mt = getmetatable(t)
checkMeta = type(mt) == 'table' and not TableEmpty(mt)
4z0t marked this conversation as resolved.
Show resolved Hide resolved
end

if checkMeta then
if seqLen + keysLen > 0 then puts(buf, ',') end
tabify(self)
puts(buf, '<metatable> = ')
self:putValue(mt)
end

self.level = self.level - 1

if keysLen > 0 or (self.meta and type(mt) == 'table' and not table.empty(mt)) then
if keysLen > 0 or checkMeta then
tabify(self)
elseif seqLen > 0 then
puts(buf, ' ')
Expand All @@ -249,7 +373,7 @@ function Inspector:putValue(v)
end

else
puts(buf, fmt('<%s %d>', tv, self:getId(v)))
puts(buf, fmt('<%s %s>', tv, self:getId(v)))
end
end

Expand Down
2 changes: 2 additions & 0 deletions tests/blueprint/unit.spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
--** SOFTWARE.
--******************************************************************************************************

require "./tests/packages/fafMockLibrary.lua"

---@type Luft
local luft = require "./tests/packages/luft"

Expand Down
53 changes: 53 additions & 0 deletions tests/packages/fafMockLibrary.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
--Lazyvar uses {&h &a} table creation, so the tests' lua version isn't compatible
local modules = {
['/lua/lazyvar.lua'] = {
LazyVarMetaTable = {}
}
}

import = function(file)
return modules[file] or require('.'..file)
end

-- Vector2 is needed in utils but not provided outside the game, so it has to be created here
local Vector2Meta = {
__index = function(t, k)
if k == 'x' then
return t[1]
elseif k == 'y' then
return t[2]
elseif k == 'z' then
return t[3]
else
error("bad argument #2 to `?' ('x', 'y', or 'z' expected)", 1)
end
end,

__newindex = function(t, k, v)
if k == 'x' then
t[1] = v
elseif k == 'y' then
t[2] = v
elseif k == 'z' then
t[3] = v
else
error("bad argument #2 to `?' ('x', 'y', or 'z' expected)", 1)
end
end,
}

Vector2 = function(...)
if arg.n ~= 2 then
error("expected 2 args, but got " .. arg.n)
end
if not type(arg[1]) == "number" then
error("number expected but got " .. type(arg[1]))
end
if not type(arg[2]) == "number" then
error("number expected but got " .. type(arg[2]))
end

local newVector2 = {arg[1], arg[2]}
setmetatable(newVector2, Vector2Meta)
return newVector2
end
2 changes: 2 additions & 0 deletions tests/utility/color.spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
--** Shared under the MIT license
--**************************************************************************************************

require "./tests/packages/fafMockLibrary.lua"

local luft = require "./tests/packages/luft"

-- color library
Expand Down
44 changes: 2 additions & 42 deletions tests/utility/string.spec.lua
Original file line number Diff line number Diff line change
@@ -1,48 +1,8 @@
require "./tests/packages/fafMockLibrary.lua"

-- Test framework
local luft = require "./tests/packages/luft"

-- Vector2 is needed in utils but not provided outside the game, so it has to be created here
local Vector2Meta = {
__index = function(t, k)
if k == 'x' then
return t[1]
elseif k == 'y' then
return t[2]
elseif k == 'z' then
return t[3]
else
error("bad argument #2 to `?' ('x', 'y', or 'z' expected)", 1)
end
end,

__newindex = function(t, k, v)
if k == 'x' then
t[1] = v
elseif k == 'y' then
t[2] = v
elseif k == 'z' then
t[3] = v
else
error("bad argument #2 to `?' ('x', 'y', or 'z' expected)", 1)
end
end,
}
Vector2 = function(...)
if arg.n ~= 2 then
error("expected 2 args, but got " .. arg.n)
end
if not type(arg[1]) == "number" then
error("number expected but got " .. type(arg[1]))
end
if not type(arg[2]) == "number" then
error("number expected but got " .. type(arg[2]))
end

local newVector2 = {arg[1], arg[2]}
setmetatable(newVector2, Vector2Meta)
return newVector2
end

-- These functions are imported to the global scope in globalInit and RuleInit
require "./lua/system/utils.lua"

Expand Down
Loading