robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
15.0 KiB537 linesraw
1local t = require('test.unit.testutil')
2local describe = t.describe
3local itp = t.gen_itp(t.it)
4local t_viml = require('test.unit.viml.testutil')
5
6local make_enum_conv_tab = t.make_enum_conv_tab
7local child_call_once = t.child_call_once
8local alloc_log_new = t.alloc_log_new
9local kvi_destroy = t.kvi_destroy
10local conv_enum = t.conv_enum
11local debug_log = t.debug_log
12local ptr2key = t.ptr2key
13local cimport = t.cimport
14local ffi = t.ffi
15local neq = t.neq
16local eq = t.eq
17local mergedicts_copy = t.mergedicts_copy
18local format_string = require('test.format_string').format_string
19local format_luav = require('test.format_string').format_luav
20local intchar2lua = t.intchar2lua
21local dictdiff = t.dictdiff
22
23local conv_ccs = t_viml.conv_ccs
24local new_pstate = t_viml.new_pstate
25local conv_cmp_type = t_viml.conv_cmp_type
26local pstate_set_str = t_viml.pstate_set_str
27local conv_expr_asgn_type = t_viml.conv_expr_asgn_type
28
29local lib = cimport('./src/nvim/viml/parser/expressions.h', './src/nvim/syntax.h')
30
31local alloc_log = alloc_log_new()
32
33local predefined_hl_defs = {
34  -- From highlight_init_both
35  Conceal = true,
36  Cursor = true,
37  lCursor = true,
38  DiffText = true,
39  ErrorMsg = true,
40  IncSearch = true,
41  ModeMsg = true,
42  NonText = true,
43  PmenuSbar = true,
44  StatusLine = true,
45  StatusLineNC = true,
46  TabLineFill = true,
47  TabLineSel = true,
48  TermCursor = true,
49  VertSplit = true,
50  WildMenu = true,
51  WinSeparator = true,
52  EndOfBuffer = true,
53  QuickFixLine = true,
54  Substitute = true,
55  Whitespace = true,
56  Error = true,
57  Todo = true,
58  String = true,
59  Character = true,
60  Number = true,
61  Boolean = true,
62  Float = true,
63  Function = true,
64  Conditional = true,
65  Repeat = true,
66  Label = true,
67  Operator = true,
68  Keyword = true,
69  Exception = true,
70  Include = true,
71  Define = true,
72  Macro = true,
73  PreCondit = true,
74  StorageClass = true,
75  Structure = true,
76  Typedef = true,
77  Tag = true,
78  SpecialChar = true,
79  Delimiter = true,
80  SpecialComment = true,
81  Debug = true,
82  Dimmed = true,
83
84  -- From highlight_init_(dark|light)
85  ColorColumn = true,
86  CursorColumn = true,
87  CursorLine = true,
88  CursorLineNr = true,
89  DiffAdd = true,
90  DiffChange = true,
91  DiffDelete = true,
92  Directory = true,
93  FoldColumn = true,
94  Folded = true,
95  LineNr = true,
96  MatchParen = true,
97  MoreMsg = true,
98  Pmenu = true,
99  PmenuSel = true,
100  PmenuThumb = true,
101  Question = true,
102  Search = true,
103  SignColumn = true,
104  SpecialKey = true,
105  SpellBad = true,
106  SpellCap = true,
107  SpellLocal = true,
108  SpellRare = true,
109  TabLine = true,
110  Title = true,
111  Visual = true,
112  WarningMsg = true,
113  Normal = true,
114  Comment = true,
115  Constant = true,
116  Special = true,
117  Identifier = true,
118  Statement = true,
119  PreProc = true,
120  Type = true,
121  Underlined = true,
122  Ignore = true,
123}
124
125local nvim_hl_defs = {}
126
127child_call_once(function()
128  local i = 0
129  while lib.highlight_init_cmdline[i] ~= nil do
130    local hl_args = lib.highlight_init_cmdline[i]
131    local s = ffi.string(hl_args)
132    local err, msg = pcall(function()
133      if s:sub(1, 13) == 'default link ' then
134        local new_grp, grp_link = s:match('^default link (%w+) (%w+)$')
135        neq(nil, new_grp)
136        -- Note: group to link to must be already defined at the time of
137        --       linking, otherwise it will be created as cleared. So existence
138        --       of the group is checked here and not in the next pass over
139        --       nvim_hl_defs.
140        eq(true, not not (nvim_hl_defs[grp_link] or predefined_hl_defs[grp_link]))
141        eq(false, not not (nvim_hl_defs[new_grp] or predefined_hl_defs[new_grp]))
142        nvim_hl_defs[new_grp] = { 'link', grp_link }
143      else
144        local new_grp, grp_args = s:match('^(%w+) (.*)')
145        neq(nil, new_grp)
146        eq(false, not not (nvim_hl_defs[new_grp] or predefined_hl_defs[new_grp]))
147        nvim_hl_defs[new_grp] = { 'definition', grp_args }
148      end
149    end)
150    if not err then
151      msg = format_string('Error while processing string %s at position %u:\n%s', s, i, msg)
152      error(msg)
153    end
154    i = i + 1
155  end
156  for k, _ in ipairs(nvim_hl_defs) do
157    eq('Nvim', k:sub(1, 4))
158    -- NvimInvalid
159    -- 12345678901
160    local err, msg = pcall(function()
161      if k:sub(5, 11) == 'Invalid' then
162        neq(nil, nvim_hl_defs['Nvim' .. k:sub(12)])
163      else
164        neq(nil, nvim_hl_defs['NvimInvalid' .. k:sub(5)])
165      end
166    end)
167    if not err then
168      msg = format_string('Error while processing group %s:\n%s', k, msg)
169      error(msg)
170    end
171  end
172end)
173
174local function hls_to_hl_fs(hls)
175  local ret = {}
176  local next_col = 0
177  for i, v in ipairs(hls) do
178    local group, line, col, str = v:match('^Nvim([a-zA-Z]+):(%d+):(%d+):(.*)$')
179    col = tonumber(col)
180    line = tonumber(line)
181    assert(line == 0)
182    local col_shift = col - next_col
183    assert(col_shift >= 0)
184    next_col = col + #str
185    ret[i] = format_string(
186      'hl(%r, %r%s)',
187      group,
188      str,
189      (col_shift == 0 and '' or (', %u'):format(col_shift))
190    )
191  end
192  return ret
193end
194
195local function format_check(expr, format_check_data, opts)
196  -- That forces specific order.
197  local zflags = opts.flags[1]
198  local zdata = format_check_data[zflags]
199  local dig_len
200  if opts.funcname then
201    print(format_string('\n%s(%r, {', opts.funcname, expr))
202    dig_len = #opts.funcname + 2
203  else
204    print(format_string('\n_check_parsing(%r, %r, {', opts, expr))
205    dig_len = #"_check_parsing(, '" + #(format_string('%r', opts))
206  end
207  local digits = '  --' .. (' '):rep(dig_len - #'  --')
208  local digits2 = digits:sub(1, -10)
209  for i = 0, #expr - 1 do
210    if i % 10 == 0 then
211      digits2 = ('%s%10u'):format(digits2, i / 10)
212    end
213    digits = ('%s%u'):format(digits, i % 10)
214  end
215  print(digits)
216  if #expr > 10 then
217    print(digits2)
218  end
219  if zdata.ast.len then
220    print(('  len = %u,'):format(zdata.ast.len))
221  end
222  print('  ast = ' .. format_luav(zdata.ast.ast, '  ') .. ',')
223  if zdata.ast.err then
224    print('  err = {')
225    print('    arg = ' .. format_luav(zdata.ast.err.arg) .. ',')
226    print('    msg = ' .. format_luav(zdata.ast.err.msg) .. ',')
227    print('  },')
228  end
229  print('}, {')
230  for _, v in ipairs(zdata.hl_fs) do
231    print('  ' .. v .. ',')
232  end
233  local diffs = {}
234  local diffs_num = 0
235  for flags, v in pairs(format_check_data) do
236    if flags ~= zflags then
237      diffs[flags] = dictdiff(zdata, v)
238      if diffs[flags] then
239        if flags == 3 + zflags then
240          if
241            dictdiff(format_check_data[1 + zflags], format_check_data[3 + zflags]) == nil
242            or dictdiff(format_check_data[2 + zflags], format_check_data[3 + zflags]) == nil
243          then
244            diffs[flags] = nil
245          else
246            diffs_num = diffs_num + 1
247          end
248        else
249          diffs_num = diffs_num + 1
250        end
251      end
252    end
253  end
254  if diffs_num ~= 0 then
255    print('}, {')
256    local flags = 1
257    while diffs_num ~= 0 do
258      if diffs[flags] then
259        diffs_num = diffs_num - 1
260        local diff = diffs[flags]
261        print(('  [%u] = {'):format(flags))
262        if diff.ast then
263          print('    ast = ' .. format_luav(diff.ast, '    ') .. ',')
264        end
265        if diff.hl_fs then
266          print('    hl_fs = ' .. format_luav(diff.hl_fs, '    ', {
267            literal_strings = true,
268          }) .. ',')
269        end
270        print('  },')
271      end
272      flags = flags + 1
273    end
274  end
275  print('})')
276end
277
278local east_node_type_tab
279make_enum_conv_tab(
280  lib,
281  {
282    'kExprNodeMissing',
283    'kExprNodeOpMissing',
284    'kExprNodeTernary',
285    'kExprNodeTernaryValue',
286    'kExprNodeRegister',
287    'kExprNodeSubscript',
288    'kExprNodeListLiteral',
289    'kExprNodeUnaryPlus',
290    'kExprNodeBinaryPlus',
291    'kExprNodeNested',
292    'kExprNodeCall',
293    'kExprNodePlainIdentifier',
294    'kExprNodePlainKey',
295    'kExprNodeComplexIdentifier',
296    'kExprNodeUnknownFigure',
297    'kExprNodeLambda',
298    'kExprNodeDictLiteral',
299    'kExprNodeCurlyBracesIdentifier',
300    'kExprNodeComma',
301    'kExprNodeColon',
302    'kExprNodeArrow',
303    'kExprNodeComparison',
304    'kExprNodeConcat',
305    'kExprNodeConcatOrSubscript',
306    'kExprNodeInteger',
307    'kExprNodeFloat',
308    'kExprNodeSingleQuotedString',
309    'kExprNodeDoubleQuotedString',
310    'kExprNodeOr',
311    'kExprNodeAnd',
312    'kExprNodeUnaryMinus',
313    'kExprNodeBinaryMinus',
314    'kExprNodeNot',
315    'kExprNodeMultiplication',
316    'kExprNodeDivision',
317    'kExprNodeMod',
318    'kExprNodeOption',
319    'kExprNodeEnvironment',
320    'kExprNodeAssignment',
321  },
322  'kExprNode',
323  function(ret)
324    east_node_type_tab = ret
325  end
326)
327
328local function conv_east_node_type(typ)
329  return conv_enum(east_node_type_tab, typ)
330end
331
332local eastnodelist2lua
333
334local function eastnode2lua(pstate, eastnode, checked_nodes)
335  local key = ptr2key(eastnode)
336  if checked_nodes[key] then
337    checked_nodes[key].duplicate_key = key
338    return { duplicate = key }
339  end
340  local typ = conv_east_node_type(eastnode.type)
341  local ret = {}
342  checked_nodes[key] = ret
343  ret.children = eastnodelist2lua(pstate, eastnode.children, checked_nodes)
344  local str = pstate_set_str(pstate, eastnode.start, eastnode.len)
345  local ret_str
346  if str.error then
347    ret_str = 'error:' .. str.error
348  else
349    ret_str = ('%u:%u:%s'):format(str.start.line, str.start.col, str.str)
350  end
351  if typ == 'Register' then
352    typ = typ .. ('(name=%s)'):format(tostring(intchar2lua(eastnode.data.reg.name)))
353  elseif typ == 'PlainIdentifier' then
354    typ = typ
355      .. ('(scope=%s,ident=%s)'):format(
356        tostring(intchar2lua(eastnode.data.var.scope)),
357        ffi.string(eastnode.data.var.ident, eastnode.data.var.ident_len)
358      )
359  elseif typ == 'PlainKey' then
360    typ = typ
361      .. ('(key=%s)'):format(ffi.string(eastnode.data.var.ident, eastnode.data.var.ident_len))
362  elseif
363    typ == 'UnknownFigure'
364    or typ == 'DictLiteral'
365    or typ == 'CurlyBracesIdentifier'
366    or typ == 'Lambda'
367  then
368    typ = typ
369      .. ('(%s)'):format(
370        (eastnode.data.fig.type_guesses.allow_lambda and '\\' or '-')
371          .. (eastnode.data.fig.type_guesses.allow_dict and 'd' or '-')
372          .. (eastnode.data.fig.type_guesses.allow_ident and 'i' or '-')
373      )
374  elseif typ == 'Comparison' then
375    typ = typ
376      .. ('(type=%s,inv=%u,ccs=%s)'):format(
377        conv_cmp_type(eastnode.data.cmp.type),
378        eastnode.data.cmp.inv and 1 or 0,
379        conv_ccs(eastnode.data.cmp.ccs)
380      )
381  elseif typ == 'Integer' then
382    typ = typ .. ('(val=%u)'):format(tonumber(eastnode.data.num.value))
383  elseif typ == 'Float' then
384    typ = typ .. format_string('(val=%e)', tonumber(eastnode.data.flt.value))
385  elseif typ == 'SingleQuotedString' or typ == 'DoubleQuotedString' then
386    if eastnode.data.str.value == nil then
387      typ = typ .. '(val=NULL)'
388    else
389      local s = ffi.string(eastnode.data.str.value, eastnode.data.str.size)
390      typ = format_string('%s(val=%q)', typ, s)
391    end
392  elseif typ == 'Option' then
393    typ = ('%s(scope=%s,ident=%s)'):format(
394      typ,
395      tostring(intchar2lua(eastnode.data.opt.scope)),
396      ffi.string(eastnode.data.opt.ident, eastnode.data.opt.ident_len)
397    )
398  elseif typ == 'Environment' then
399    typ = ('%s(ident=%s)'):format(
400      typ,
401      ffi.string(eastnode.data.env.ident, eastnode.data.env.ident_len)
402    )
403  elseif typ == 'Assignment' then
404    typ = ('%s(%s)'):format(typ, conv_expr_asgn_type(eastnode.data.ass.type))
405  end
406  ret_str = typ .. ':' .. ret_str
407  local can_simplify = not ret.children
408  if can_simplify then
409    ret = ret_str
410  else
411    ret[1] = ret_str
412  end
413  return ret
414end
415
416eastnodelist2lua = function(pstate, eastnode, checked_nodes)
417  local ret = {}
418  while eastnode ~= nil do
419    ret[#ret + 1] = eastnode2lua(pstate, eastnode, checked_nodes)
420    eastnode = eastnode.next
421  end
422  if #ret == 0 then
423    ret = nil
424  end
425  return ret
426end
427
428local function east2lua(str, pstate, east)
429  local checked_nodes = {}
430  local len = tonumber(pstate.pos.col)
431  if pstate.pos.line == 1 then
432    len = tonumber(pstate.reader.lines.items[0].size)
433  end
434  if type(str) == 'string' and len == #str then
435    len = nil
436  end
437  return {
438    err = east.err.msg ~= nil and {
439      msg = ffi.string(east.err.msg),
440      arg = ffi.string(east.err.arg, east.err.arg_len),
441    } or nil,
442    len = len,
443    ast = eastnodelist2lua(pstate, east.root, checked_nodes),
444  }
445end
446
447local function phl2lua(pstate)
448  local ret = {}
449  for i = 0, (tonumber(pstate.colors.size) - 1) do
450    local chunk = pstate.colors.items[i]
451    local chunk_tbl = pstate_set_str(pstate, chunk.start, chunk.end_col - chunk.start.col, {
452      group = ffi.string(chunk.group),
453    })
454    ret[i + 1] = ('%s:%u:%u:%s'):format(
455      chunk_tbl.group,
456      chunk_tbl.start.line,
457      chunk_tbl.start.col,
458      chunk_tbl.str
459    )
460  end
461  return ret
462end
463
464describe('Expressions parser', function()
465  local function _check_parsing(opts, str, exp_ast, exp_highlighting_fs, nz_flags_exps)
466    local zflags = opts.flags[1]
467    nz_flags_exps = nz_flags_exps or {}
468    local format_check_data = {}
469    for _, flags in ipairs(opts.flags) do
470      debug_log(('Running test case (%s, %u)'):format(str, flags))
471      local err, msg = pcall(function()
472        if os.getenv('NVIM_TEST_PARSER_SPEC_PRINT_TEST_CASE') == '1' then
473          print(str, flags)
474        end
475        alloc_log:check({})
476
477        local pstate = new_pstate({ str })
478        local east = lib.viml_pexpr_parse(pstate, flags)
479        local ast = east2lua(str, pstate, east)
480        local hls = phl2lua(pstate)
481        if exp_ast == nil then
482          format_check_data[flags] = { ast = ast, hl_fs = hls_to_hl_fs(hls) }
483        else
484          local exps = {
485            ast = exp_ast,
486            hl_fs = exp_highlighting_fs,
487          }
488          local add_exps = nz_flags_exps[flags]
489          if not add_exps and flags == 3 + zflags then
490            add_exps = nz_flags_exps[1 + zflags] or nz_flags_exps[2 + zflags]
491          end
492          if add_exps then
493            if add_exps.ast then
494              exps.ast = mergedicts_copy(exps.ast, add_exps.ast)
495            end
496            if add_exps.hl_fs then
497              exps.hl_fs = mergedicts_copy(exps.hl_fs, add_exps.hl_fs)
498            end
499          end
500          eq(exps.ast, ast)
501          if exp_highlighting_fs then
502            local exp_highlighting = {}
503            local next_col = 0
504            for i, h in ipairs(exps.hl_fs) do
505              exp_highlighting[i], next_col = h(next_col)
506            end
507            eq(exp_highlighting, hls)
508          end
509        end
510        lib.viml_pexpr_free_ast(east)
511        kvi_destroy(pstate.colors)
512        alloc_log:clear_tmp_allocs(true)
513        alloc_log:check({})
514      end)
515      if not err then
516        msg = format_string('Error while processing test (%r, %u):\n%s', str, flags, msg)
517        error(msg)
518      end
519    end
520    if exp_ast == nil then
521      format_check(str, format_check_data, opts)
522    end
523  end
524  local function hl(group, str, shift)
525    return function(next_col)
526      if nvim_hl_defs['Nvim' .. group] == nil then
527        error(('Unknown group: Nvim%s'):format(group))
528      end
529      local col = next_col + (shift or 0)
530      return (('%s:%u:%u:%s'):format('Nvim' .. group, 0, col, str)), (col + #str)
531    end
532  end
533  local function fmtn(typ, args, rest)
534    return ('%s(%s)%s'):format(typ, args, rest)
535  end
536  require('test.unit.viml.expressions.parser_tests')(itp, _check_parsing, hl, fmtn)
537end)