inspect.lua 8.9 KB

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