robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
11.8 KiB482 linesraw
1--- @class (private) vim.InspectModule
2--- @overload fun(root: any, options?: vim.inspect.Opts): string
3local inspect = {
4  _VERSION = 'inspect.lua 3.1.0',
5  _URL = 'http://github.com/kikito/inspect.lua',
6  _DESCRIPTION = 'human-readable representations of tables',
7  _LICENSE = [[
8    MIT LICENSE
9
10    Copyright (c) 2013 Enrique García Cota
11
12    Permission is hereby granted, free of charge, to any person obtaining a
13    copy of this software and associated documentation files (the
14    "Software"), to deal in the Software without restriction, including
15    without limitation the rights to use, copy, modify, merge, publish,
16    distribute, sublicense, and/or sell copies of the Software, and to
17    permit persons to whom the Software is furnished to do so, subject to
18    the following conditions:
19
20    The above copyright notice and this permission notice shall be included
21    in all copies or substantial portions of the Software.
22
23    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
26    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
27    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
28    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
29    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30  ]],
31}
32
33inspect.KEY = setmetatable({}, {
34  __tostring = function()
35    return 'inspect.KEY'
36  end,
37})
38inspect.METATABLE = setmetatable({}, {
39  __tostring = function()
40    return 'inspect.METATABLE'
41  end,
42})
43
44local tostring = tostring
45local rep = string.rep
46local match = string.match
47local char = string.char
48local gsub = string.gsub
49local fmt = string.format
50
51local sbavailable, stringbuffer = pcall(require, 'string.buffer')
52local buffnew
53local puts
54local render
55
56if sbavailable then
57  buffnew = stringbuffer.new
58  --- @param buf string.buffer
59  --- @param str string
60  puts = function(buf, str)
61    buf:put(str)
62  end
63  --- @param buf string.buffer
64  render = function(buf)
65    return buf:get()
66  end
67else
68  buffnew = function()
69    return { n = 0 }
70  end
71  --- @param buf { [integer]: string, n: integer }
72  --- @param str string
73  puts = function(buf, str)
74    buf.n = buf.n + 1
75    buf[buf.n] = str
76  end
77  --- @param buf string[]
78  render = function(buf)
79    return table.concat(buf)
80  end
81end
82
83-- The constructor, writer and renderer always use the same buffer backend.
84--- @cast puts fun(buf: string.buffer|{ [integer]: string, n: integer }, str: string)
85--- @cast render fun(buf: string.buffer|{ [integer]: string, n: integer }): string
86
87local _rawget
88if rawget then
89  _rawget = rawget
90else
91  --- @generic K, V
92  --- @param t table<K,V>
93  --- @param k K
94  --- @return V?
95  _rawget = function(t, k)
96    return t[k]
97  end
98end
99
100--- @generic K, V
101--- @param t table<K,V>
102--- @return (fun(t: table<K,V>, key?: K): K?, V?), table<K,V>, nil
103local function rawpairs(t)
104  return next, t, nil
105end
106
107--- Apostrophizes the string if it has quotes, but not aphostrophes
108--- Otherwise, it returns a regular quoted string
109--- @param str string
110local function smartQuote(str)
111  if match(str, '"') and not match(str, "'") then
112    return "'" .. str .. "'"
113  end
114  return '"' .. gsub(str, '"', '\\"') .. '"'
115end
116
117-- \a => '\\a', \0 => '\\0', 31 => '\31'
118local shortControlCharEscapes = {
119  ['\a'] = '\\a',
120  ['\b'] = '\\b',
121  ['\f'] = '\\f',
122  ['\n'] = '\\n',
123  ['\r'] = '\\r',
124  ['\t'] = '\\t',
125  ['\v'] = '\\v',
126  ['\127'] = '\\127',
127}
128local longControlCharEscapes = { ['\127'] = '\127' }
129for i = 0, 31 do
130  local ch = char(i)
131  if not shortControlCharEscapes[ch] then
132    shortControlCharEscapes[ch] = '\\' .. i
133    longControlCharEscapes[ch] = fmt('\\%03d', i)
134  end
135end
136
137--- @param str string
138local function escape(str)
139  return (
140    gsub(
141      gsub(gsub(str, '\\', '\\\\'), '(%c)%f[0-9]', longControlCharEscapes),
142      '%c',
143      shortControlCharEscapes
144    )
145  )
146end
147
148local luaKeywords = {}
149for k in
150  ([[ and break do else elseif end false for function goto if
151             in local nil not or repeat return then true until while
152]]):gmatch('%w+')
153do
154  luaKeywords[k] = true
155end
156
157--- @param str any
158local function isIdentifier(str)
159  return type(str) == 'string'
160    -- identifier must start with a letter and underscore, and be followed by letters, numbers, and underscores
161    and not not str:match('^[_%a][_%a%d]*$')
162    -- lua keywords are not valid identifiers
163    and not luaKeywords[str]
164end
165
166local flr = math.floor
167
168--- @param k any
169--- @param sequenceLength integer
170local function isSequenceKey(k, sequenceLength)
171  return type(k) == 'number' and flr(k) == k and 1 <= k and k <= sequenceLength
172end
173
174local defaultTypeOrders = {
175  ['number'] = 1,
176  ['boolean'] = 2,
177  ['string'] = 3,
178  ['table'] = 4,
179  ['function'] = 5,
180  ['userdata'] = 6,
181  ['thread'] = 7,
182}
183
184--- @param a any
185--- @param b any
186local function sortKeys(a, b)
187  local ta, tb = type(a), type(b)
188
189  -- strings and numbers are sorted numerically/alphabetically
190  if ta == tb and (ta == 'string' or ta == 'number') then
191    return a < b
192  end
193
194  local dta = defaultTypeOrders[ta] or 100
195  local dtb = defaultTypeOrders[tb] or 100
196  -- Two default types are compared according to the defaultTypeOrders table
197
198  -- custom types are sorted out alphabetically
199  return dta == dtb and ta < tb or dta < dtb
200end
201
202--- @generic K
203--- @param t table<K,any>
204--- @return K[], integer, integer
205local function getKeys(t)
206  local seqLen = 1
207  while _rawget(t, seqLen) ~= nil do
208    seqLen = seqLen + 1
209  end
210  seqLen = seqLen - 1
211
212  local keys, keysLen = {}, 0
213  for k in rawpairs(t) do
214    if not isSequenceKey(k, seqLen) then
215      keysLen = keysLen + 1
216      keys[keysLen] = k
217    end
218  end
219  table.sort(keys, sortKeys)
220  return keys, keysLen, seqLen
221end
222
223--- @param x any
224--- @param cycles table<table,integer>
225--- @param depth number
226local function countCycles(x, cycles, depth)
227  if type(x) == 'table' then
228    if cycles[x] then
229      cycles[x] = cycles[x] + 1
230    else
231      cycles[x] = 1
232      if depth > 0 then
233        for k, v in rawpairs(x) do
234          countCycles(k, cycles, depth - 1)
235          countCycles(v, cycles, depth - 1)
236        end
237        countCycles(getmetatable(x), cycles, depth - 1)
238      end
239    end
240  end
241end
242
243--- @generic T
244--- @param path T[]
245--- @param a T
246--- @param b? T
247--- @return T[]
248local function makePath(path, a, b)
249  local newPath = {}
250  local len = #path
251  for i = 1, len do
252    newPath[i] = path[i]
253  end
254
255  newPath[len + 1] = a
256  newPath[len + 2] = b
257
258  return newPath
259end
260
261--- @param process fun(item: any, path: any[]): any
262--- @param item any
263--- @param path any[]
264--- @param visited table<any,any>
265local function processRecursive(process, item, path, visited)
266  if item == nil then
267    return nil
268  end
269  if visited[item] then
270    return visited[item]
271  end
272
273  local processed = process(item, path)
274  if type(processed) == 'table' then
275    local processedCopy = {}
276    visited[item] = processedCopy
277    local processedKey
278
279    for k, v in rawpairs(processed) do
280      processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited)
281      if processedKey ~= nil then
282        processedCopy[processedKey] =
283          processRecursive(process, v, makePath(path, processedKey), visited)
284      end
285    end
286
287    local mt =
288      processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited)
289    if type(mt) ~= 'table' then
290      mt = nil
291    end
292    setmetatable(processedCopy, mt)
293    processed = processedCopy
294  end
295  return processed
296end
297
298--- @class (private) vim.inspect.Inspector
299--- @field buf string.buffer|{ [integer]: string, n: integer }
300--- @field ids table<any,integer>
301--- @field cycles table<table,integer>
302--- @field depth number
303--- @field level integer
304--- @field newline string
305--- @field indent string
306local Inspector = {}
307
308local Inspector_mt = { __index = Inspector }
309
310--- @param inspector vim.inspect.Inspector
311local function tabify(inspector)
312  puts(inspector.buf, inspector.newline .. rep(inspector.indent, inspector.level))
313end
314
315--- @nodoc
316--- @param v any
317function Inspector:getId(v)
318  local id = self.ids[v]
319  local ids = self.ids
320  if not id then
321    local tv = type(v)
322    id = (ids[tv] or 0) + 1
323    ids[v], ids[tv] = id, id
324  end
325  return tostring(id)
326end
327
328--- @nodoc
329--- @param v any
330function Inspector:putValue(v)
331  local buf = self.buf
332  local tv = type(v)
333  if tv == 'string' then
334    puts(buf, smartQuote(escape(v)))
335  elseif
336    tv == 'number'
337    or tv == 'boolean'
338    or tv == 'nil'
339    or tv == 'cdata'
340    or tv == 'ctype'
341    or (vim and v == vim.NIL)
342  then
343    puts(buf, tostring(v))
344  elseif tv == 'table' and not self.ids[v] then
345    local t = v
346
347    if t == inspect.KEY or t == inspect.METATABLE then
348      puts(buf, tostring(t))
349    elseif self.level >= self.depth then
350      puts(buf, '{...}')
351    else
352      if self.cycles[t] > 1 then
353        puts(buf, fmt('<%d>', self:getId(t)))
354      end
355
356      local keys, keysLen, seqLen = getKeys(t)
357      local mt = getmetatable(t)
358
359      if vim and seqLen == 0 and keysLen == 0 and mt == vim._empty_dict_mt then
360        puts(buf, tostring(t))
361        return
362      end
363
364      puts(buf, '{')
365      self.level = self.level + 1
366
367      for i = 1, seqLen + keysLen do
368        if i > 1 then
369          puts(buf, ',')
370        end
371        if i <= seqLen then
372          puts(buf, ' ')
373          self:putValue(t[i])
374        else
375          local k = keys[i - seqLen]
376          tabify(self)
377          if isIdentifier(k) then
378            puts(buf, k)
379          else
380            puts(buf, '[')
381            self:putValue(k)
382            puts(buf, ']')
383          end
384          puts(buf, ' = ')
385          self:putValue(t[k])
386        end
387      end
388
389      if type(mt) == 'table' then
390        if seqLen + keysLen > 0 then
391          puts(buf, ',')
392        end
393        tabify(self)
394        puts(buf, '<metatable> = ')
395        self:putValue(mt)
396      end
397
398      self.level = self.level - 1
399
400      if keysLen > 0 or type(mt) == 'table' then
401        tabify(self)
402      elseif seqLen > 0 then
403        puts(buf, ' ')
404      end
405
406      puts(buf, '}')
407    end
408  else
409    puts(buf, fmt('<%s %d>', tv, self:getId(v)))
410  end
411end
412
413--- @inlinedoc
414--- @class vim.inspect.Opts
415---
416--- Maximum table nesting depth. Deeper tables are shown as `{...}`.
417--- (default: unlimited)
418--- @field depth? integer
419---
420--- String used for line breaks.
421--- (default: `"\n"`)
422--- @field newline? string
423---
424--- String repeated for each level of indentation.
425--- (default: `"  "`)
426--- @field indent? string
427---
428--- Transforms values, keys, and metatables before formatting. Return a replacement value,
429--- or `nil` to omit a table entry. {path} lists the keys leading to {item}, with
430--- `vim.inspect.KEY` appended for keys or `vim.inspect.METATABLE` for metatables.
431--- The root has an empty path.
432--- @field process? fun(item: any, path: any[]): any
433
434--- @nodoc
435--- @param root any
436--- @param options? vim.inspect.Opts
437--- @return string
438function inspect.inspect(root, options)
439  options = options or {}
440
441  local depth = options.depth or math.huge
442  local newline = options.newline or '\n'
443  local indent = options.indent or '  '
444  local process = options.process
445
446  if process then
447    root = processRecursive(process, root, {}, {})
448  end
449
450  local cycles = {}
451  countCycles(root, cycles, depth)
452
453  local inspector = setmetatable({
454    buf = buffnew(),
455    ids = {},
456    cycles = cycles,
457    depth = depth,
458    level = 0,
459    newline = newline,
460    indent = indent,
461  }, Inspector_mt)
462
463  inspector:putValue(root)
464
465  return render(inspector.buf)
466end
467
468setmetatable(inspect, {
469  --- Gets a human-readable representation of the given object.
470  ---
471  --- @see |vim.print()|
472  --- @see https://github.com/kikito/inspect.lua
473  --- @see https://github.com/mpeterv/vinspect
474  --- @param root any
475  --- @param options? vim.inspect.Opts
476  --- @return string
477  __call = function(_, root, options)
478    return inspect.inspect(root, options)
479  end,
480})
481
482return inspect