Debian Codegraph @

texmf-dist/tex/lualatex/luacas/_lib/luacas-inspect.lua

raw
1 local inspect ={
2 _VERSION = 'inspect.lua 3.1.0',
3 _URL = 'http://github.com/kikito/inspect.lua',
4 _DESCRIPTION = 'human-readable representations of tables',
5 _LICENSE = [[
6 MIT LICENSE
7
8 Copyright (c) 2013 Enrique GarcĂ­a Cota
9
10 Permission is hereby granted, free of charge, to any person obtaining a
11 copy of this software and associated documentation files (the
12 "Software"), to deal in the Software without restriction, including
13 without limitation the rights to use, copy, modify, merge, publish,
14 distribute, sublicense, and/or sell copies of the Software, and to
15 permit persons to whom the Software is furnished to do so, subject to
16 the following conditions:
17
18 The above copyright notice and this permission notice shall be included
19 in all copies or substantial portions of the Software.
20
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
24 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
25 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
26 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
27 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 ]]
29 }
30
31 local tostring = tostring
32
33 inspect.KEY = setmetatable({}, {__tostring = function() return 'inspect.KEY' end})
34 inspect.METATABLE = setmetatable({}, {__tostring = function() return 'inspect.METATABLE' end})
35
36 local function rawpairs(t)
37 return next, t, nil
38 end
39
40 -- Apostrophizes the string if it has quotes, but not aphostrophes
41 -- Otherwise, it returns a regular quoted string
42 local function smartQuote(str)
43 if str:match('"') and not str:match("'") then
44 return "'" .. str .. "'"
45 end
46 return '"' .. str:gsub('"', '\\"') .. '"'
47 end
48
49 -- \a => '\\a', \0 => nil
50 local shortControlCharEscapes = {
51 ["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
52 ["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v", ["\127"] = "\\127",
53 }
54 local longControlCharEscapes = {["\127"]="\127"} -- \a => nil, \0 => \000, 31 => \031
55 for i=0, 31 do
56 local ch = string.char(i)
57 if not shortControlCharEscapes[ch] then
58 shortControlCharEscapes[ch] = "\\"..i
59 longControlCharEscapes[ch] = string.format("\\%03d", i)
60 end
61 end
62 --longControlCharEscapes["\127"]="\\127"
63
64 local function escape(str)
65 return (str:gsub("\\", "\\\\")
66 :gsub("(%c)%f[0-9]", longControlCharEscapes)
67 :gsub("%c", shortControlCharEscapes))
68 end
69
70 local function isIdentifier(str)
71 return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
72 end
73
74 local function isSequenceKey(k, sequenceLength)
75 return type(k) == 'number'
76 and 1 <= k
77 and k <= sequenceLength
78 and math.floor(k) == k
79 end
80
81 local defaultTypeOrders = {
82 ['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
83 ['function'] = 5, ['userdata'] = 6, ['thread'] = 7
84 }
85
86 local function sortKeys(a, b)
87 local ta, tb = type(a), type(b)
88
89 -- strings and numbers are sorted numerically/alphabetically
90 if ta == tb and (ta == 'string' or ta == 'number') then return a < b end
91
92 local dta, dtb = defaultTypeOrders[ta], defaultTypeOrders[tb]
93 -- Two default types are compared according to the defaultTypeOrders table
94 if dta and dtb then return defaultTypeOrders[ta] < defaultTypeOrders[tb]
95 elseif dta then return true -- default types before custom ones
96 elseif dtb then return false -- custom types after default ones
97 end
98
99 -- custom types are sorted out alphabetically
100 return ta < tb
101 end
102
103 -- For implementation reasons, the behavior of rawlen & # is "undefined" when
104 -- tables aren't pure sequences. So we implement our own # operator.
105 local function getSequenceLength(t)
106 local len = 1
107 local v = rawget(t,len)
108 while v ~= nil do
109 len = len + 1
110 v = rawget(t,len)
111 end
112 return len - 1
113 end
114
115 local function getNonSequentialKeys(t)
116 local keys, keysLength = {}, 0
117 local sequenceLength = getSequenceLength(t)
118 for k,_ in rawpairs(t) do
119 if not isSequenceKey(k, sequenceLength) then
120 keysLength = keysLength + 1
121 keys[keysLength] = k
122 end
123 end
124 table.sort(keys, sortKeys)
125 return keys, keysLength, sequenceLength
126 end
127
128 local function countTableAppearances(t, tableAppearances)
129 tableAppearances = tableAppearances or {}
130
131 if type(t) == 'table' then
132 if not tableAppearances[t] then
133 tableAppearances[t] = 1
134 for k,v in rawpairs(t) do
135 countTableAppearances(k, tableAppearances)
136 countTableAppearances(v, tableAppearances)
137 end
138 countTableAppearances(getmetatable(t), tableAppearances)
139 else
140 tableAppearances[t] = tableAppearances[t] + 1
141 end
142 end
143
144 return tableAppearances
145 end
146
147 local copySequence = function(s)
148 local copy, len = {}, #s
149 for i=1, len do copy[i] = s[i] end
150 return copy, len
151 end
152
153 local function makePath(path, ...)
154 local keys = {...}
155 local newPath, len = copySequence(path)
156 for i=1, #keys do
157 newPath[len + i] = keys[i]
158 end
159 return newPath
160 end
161
162 local function processRecursive(process, item, path, visited)
163 if item == nil then return nil end
164 if visited[item] then return visited[item] end
165
166 local processed = process(item, path)
167 if type(processed) == 'table' then
168 local processedCopy = {}
169 visited[item] = processedCopy
170 local processedKey
171
172 for k,v in rawpairs(processed) do
173 processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited)
174 if processedKey ~= nil then
175 processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited)
176 end
177 end
178
179 local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited)
180 if type(mt) ~= 'table' then mt = nil end -- ignore not nil/table __metatable field
181 setmetatable(processedCopy, mt)
182 processed = processedCopy
183 end
184 return processed
185 end
186
187
188
189 -------------------------------------------------------------------
190
191 local Inspector = {}
192 local Inspector_mt = {__index = Inspector}
193
194 function Inspector:puts(...)
195 local args = {...}
196 local buffer = self.buffer
197 local len = #buffer
198 for i=1, #args do
199 len = len + 1
200 buffer[len] = args[i]
201 end
202 end
203
204 function Inspector:down(f)
205 self.level = self.level + 1
206 f()
207 self.level = self.level - 1
208 end
209
210 function Inspector:tabify()
211 self:puts(self.newline, string.rep(self.indent, self.level))
212 end
213
214 function Inspector:alreadyVisited(v)
215 return self.ids[v] ~= nil
216 end
217
218 function Inspector:getId(v)
219 local id = self.ids[v]
220 if not id then
221 local tv = type(v)
222 id = (self.maxIds[tv] or 0) + 1
223 self.maxIds[tv] = id
224 self.ids[v] = id
225 end
226 return tostring(id)
227 end
228
229 function Inspector:putKey(k)
230 if isIdentifier(k) then return self:puts(k) end
231 self:puts("[")
232 self:putValue(k)
233 self:puts("]")
234 end
235
236 function Inspector:putTable(t)
237 if t == inspect.KEY or t == inspect.METATABLE then
238 self:puts(tostring(t))
239 elseif self:alreadyVisited(t) then
240 self:puts('<table ', self:getId(t), '>')
241 elseif self.level >= self.depth then
242 self:puts('{...}')
243 else
244 if self.tableAppearances[t] > 1 then self:puts('<', self:getId(t), '>') end
245
246 local nonSequentialKeys, nonSequentialKeysLength, sequenceLength = getNonSequentialKeys(t)
247 local mt = getmetatable(t)
248
249 self:puts('{')
250 self:down(function()
251 local count = 0
252 for i=1, sequenceLength do
253 if count > 0 then self:puts(',') end
254 self:puts(' ')
255 self:putValue(t[i])
256 count = count + 1
257 end
258
259 for i=1, nonSequentialKeysLength do
260 local k = nonSequentialKeys[i]
261 if count > 0 then self:puts(',') end
262 self:tabify()
263 self:putKey(k)
264 self:puts(' = ')
265 self:putValue(t[k])
266 count = count + 1
267 end
268
269 if type(mt) == 'table' then
270 if count > 0 then self:puts(',') end
271 self:tabify()
272 self:puts('<metatable> = ')
273 self:putValue(mt)
274 end
275 end)
276
277 if nonSequentialKeysLength > 0 or type(mt) == 'table' then -- result is multi-lined. Justify closing }
278 self:tabify()
279 elseif sequenceLength > 0 then -- array tables have one extra space before closing }
280 self:puts(' ')
281 end
282
283 self:puts('}')
284 end
285 end
286
287 function Inspector:putValue(v)
288 local tv = type(v)
289
290 if tv == 'string' then
291 self:puts(smartQuote(escape(v)))
292 elseif tv == 'number' or tv == 'boolean' or tv == 'nil' or
293 tv == 'cdata' or tv == 'ctype' then
294 self:puts(tostring(v))
295 elseif tv == 'table' then
296 self:putTable(v)
297 else
298 self:puts('<', tv, ' ', self:getId(v), '>')
299 end
300 end
301
302 -------------------------------------------------------------------
303
304 function inspect.inspect(root, options)
305 options = options or {}
306
307 local depth = options.depth or math.huge
308 local newline = options.newline or '\n'
309 local indent = options.indent or ' '
310 local process = options.process
311
312 if process then
313 root = processRecursive(process, root, {}, {})
314 end
315
316 local inspector = setmetatable({
317 depth = depth,
318 level = 0,
319 buffer = {},
320 ids = {},
321 maxIds = {},
322 newline = newline,
323 indent = indent,
324 tableAppearances = countTableAppearances(root)
325 }, Inspector_mt)
326
327 inspector:putValue(root)
328
329 return table.concat(inspector.buffer)
330 end
331
332 setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) end })
333
334 return inspect
335