aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/vim/treesitter.lua
blob: 3c1cfa6a33e50d23876e06e827b1505b62c7b49c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
local api = vim.api

---@type table<integer,vim.treesitter.LanguageTree>
local parsers = setmetatable({}, { __mode = 'v' })

local M = vim._defer_require('vim.treesitter', {
  _fold = ..., --- @module 'vim.treesitter._fold'
  _query_linter = ..., --- @module 'vim.treesitter._query_linter'
  _range = ..., --- @module 'vim.treesitter._range'
  dev = ..., --- @module 'vim.treesitter.dev'
  highlighter = ..., --- @module 'vim.treesitter.highlighter'
  language = ..., --- @module 'vim.treesitter.language'
  languagetree = ..., --- @module 'vim.treesitter.languagetree'
  query = ..., --- @module 'vim.treesitter.query'
  _select = ..., --- @module 'vim.treesitter._select'
})

local LanguageTree = M.languagetree

--- @nodoc
M.language_version = vim._ts_get_language_version()

--- @nodoc
M.minimum_language_version = vim._ts_get_minimum_language_version()

--- Creates a new parser
---
--- It is not recommended to use this; use |get_parser()| instead.
---
---@param buf integer Buffer the parser will be tied to (0 for current buffer)
---@param lang string Language of the parser
---@param opts (table|nil) Options to pass to the created language tree
---
---@return vim.treesitter.LanguageTree object to use for parsing
function M._create_parser(buf, lang, opts)
  buf = vim._resolve_bufnr(buf)

  local self = LanguageTree.new(buf, lang, opts)

  local function bytes_cb(_, ...)
    self:_on_bytes(...)
  end

  local function detach_cb(_, ...)
    if parsers[buf] == self then
      parsers[buf] = nil
    end
    self:_on_detach(...)
  end

  local function reload_cb(_)
    self:_on_reload()
  end

  local source = self:source() --[[@as integer]]

  api.nvim_buf_attach(
    source,
    false,
    { on_bytes = bytes_cb, on_detach = detach_cb, on_reload = reload_cb, preview = true }
  )

  return self
end

--- @param lang string?
local function valid_lang(lang)
  return lang and lang ~= ''
end

--- Returns the parser for a specific buffer and attaches it to the buffer
---
--- If needed, this will create the parser.
---
--- If no parser can be created, nil (and an error message) is returned.
---
---@param buf integer|nil (default: current buffer) Buffer the parser should be tied to
---@param lang string|nil (default: from 'filetype') Language of this parser
---@param opts table|nil Options to pass to the created language tree
---
---@return vim.treesitter.LanguageTree? object to use for parsing
---@return string? error message, if applicable
function M.get_parser(buf, lang, opts)
  opts = opts or {}

  buf = vim._resolve_bufnr(buf)

  if not valid_lang(lang) then
    lang = M.language.get_lang(vim.bo[buf].filetype)
  end

  if not valid_lang(lang) then
    if not parsers[buf] then
      return nil,
        string.format('Parser not found for buffer %s: language could not be determined', buf)
    end
  elseif parsers[buf] == nil or parsers[buf]:lang() ~= lang then
    if not api.nvim_buf_is_loaded(buf) then
      return nil, string.format('Buffer %s must be loaded to create parser', buf)
    end
    local status, res = pcall(M._create_parser, buf, assert(lang), opts)
    if not status then
      local msg = 'Parser could not be created for buffer %s and language "%s": %s'
      return nil, string.format(msg, buf, lang, res)
    end
    parsers[buf] = res
  end

  parsers[buf]:register_cbs(opts.buf_attach_cbs)

  return parsers[buf]
end

--- Returns a string parser
---
---@param str string Text to parse
---@param lang string Language of this string
---@param opts (table|nil) Options to pass to the created language tree
---
---@return vim.treesitter.LanguageTree object to use for parsing
function M.get_string_parser(str, lang, opts)
  vim.validate('str', str, 'string')
  vim.validate('lang', lang, 'string')

  return LanguageTree.new(str, lang, opts)
end

--- Determines whether a node is the ancestor of another
---
---@param dest TSNode Possible ancestor
---@param source TSNode Possible descendant
---
---@return boolean True if {dest} is an ancestor of {source}
function M.is_ancestor(dest, source)
  if not (dest and source) then
    return false
  end

  return dest:child_with_descendant(source) ~= nil
end

--- Returns the node's range or an unpacked range table
---
---@param node_or_range TSNode|Range4 Node or table of positions
---
---@return integer start_row
---@return integer start_col # (byte offset)
---@return integer end_row
---@return integer end_col # (byte offset)
function M.get_node_range(node_or_range)
  if type(node_or_range) == 'table' then
    --- @cast node_or_range -TSNode LuaLS bug
    return M._range.unpack4(node_or_range)
  else
    return node_or_range:range(false)
  end
end

---@param node TSNode
---@param source integer|string Buffer or string from which the {node} is extracted
---@param offset Range4
---@return Range6
local function apply_range_offset(node, source, offset)
  ---@diagnostic disable-next-line: missing-fields LuaLS varargs bug
  local range = { node:range() } ---@type Range4
  local start_row_offset = offset[1]
  local start_col_offset = offset[2]
  local end_row_offset = offset[3]
  local end_col_offset = offset[4]

  range[1] = range[1] + start_row_offset
  range[2] = range[2] + start_col_offset
  range[3] = range[3] + end_row_offset
  range[4] = range[4] + end_col_offset

  if range[1] < range[3] or (range[1] == range[3] and range[2] <= range[4]) then
    return M._range.add_bytes(source, range)
  end

  -- If this produces an invalid range, we just skip it.
  return { node:range(true) }
end

---Get the range of a |TSNode|. Can also supply {source} and {metadata}
---to get the range with directives applied.
---@param node TSNode
---@param source integer|string|nil Buffer or string from which the {node} is extracted
---@param metadata vim.treesitter.query.TSMetadata|nil
---@return Range6
function M.get_range(node, source, metadata)
  if metadata then
    if metadata.range then
      return M._range.add_bytes(assert(source), metadata.range)
    elseif metadata.offset then
      return apply_range_offset(node, assert(source), metadata.offset)
    end
  end
  return { node:range(true) }
end

---@param buf integer
---@param range Range
---@return string
local function buf_range_get_text(buf, range)
  local start_row, start_col, end_row, end_col = M._range.unpack4(range)
  local append_newline = end_col == 0 and start_row ~= end_row

  if end_col == 0 then
    if start_row == end_row then
      start_col = -1
      start_row = start_row - 1
    end
    end_col = -1
    end_row = end_row - 1
  end

  local lines = api.nvim_buf_get_text(buf, start_row, start_col, end_row, end_col)
  if append_newline then
    table.insert(lines, '')
  end

  return table.concat(lines, '\n')
end

--- Gets the text corresponding to a given node
---
---@param node TSNode
---@param source (integer|string) Buffer or string from which the {node} is extracted
---@param opts (table|nil) Optional parameters.
---          - metadata (table) Metadata of a specific capture. This would be
---            set to `metadata[capture_id]` when using |vim.treesitter.query.add_directive()|.
---@return string
function M.get_node_text(node, source, opts)
  opts = opts or {}
  local metadata = opts.metadata or {}

  if metadata.text then
    return metadata.text
  elseif type(source) == 'number' then
    local range = M.get_range(node, source, metadata)
    return buf_range_get_text(source, range)
  end

  ---@cast source string
  return source:sub(select(3, node:start()) + 1, select(3, node:end_()))
end

--- Determines whether (line, col) position is in node range
---
---@param node TSNode defining the range
---@param line integer Line (0-based)
---@param col integer Column (0-based)
---
---@return boolean True if the position is in node range
function M.is_in_node_range(node, line, col)
  return M.node_contains(node, { line, col, line, col + 1 })
end

--- Determines if a node contains a range
---
---@param node TSNode
---@param range table
---
---@return boolean True if the {node} contains the {range}
function M.node_contains(node, range)
  -- allow a table so nodes can be mocked
  vim.validate('node', node, { 'userdata', 'table' })
  vim.validate('range', range, M._range.validate, 'integer list with 4 or 6 elements')
  --- @diagnostic disable-next-line: missing-fields LuaLS bug
  local nrange = { node:range() } --- @type Range4
  return M._range.contains(nrange, range)
end

--- @class vim.treesitter.CaptureInfo
--- @field capture string Capture name
--- @field lang string Language name
--- @field metadata vim.treesitter.query.TSMetadata Query metadata, e.g. `priority` or `conceal`
--- @field id integer 1-based capture id in the query
--- @field pattern_id integer 1-based id of the matched pattern in the query
--- @field row integer Start row
--- @field col integer Start column
--- @field end_row integer End row
--- @field end_col integer End column (excluded)

---@deprecated Use vim.treesitter.get_captures() instead.
---@param buf integer
---@param row integer
---@param col integer
---@return vim.treesitter.CaptureInfo[]
function M.get_captures_at_pos(buf, row, col)
  vim.deprecate('vim.treesitter.get_captures_at_pos()', 'vim.treesitter.get_captures()', '0.15')
  return M.get_captures(buf, { row, col })
end

--- Returns highlight captures at a position, on a line, or overlapping a range.
---
--- {start} and {stop} can be a row number or a `{row, col}` pair. All rows and
--- columns are 0-based; columns are byte offsets.
---
--- Without {stop}, a row number queries the whole line and a `{row, col}` pair
--- queries one position.
---
--- With {stop}, return captures that overlap the range. The stop position is
--- excluded; a row number excludes that row. Empty ranges return no captures.
---
--- Each result includes the full captured node range, which may extend outside the
--- requested range. Returns an empty list if treesitter highlighting is not active
--- in {buf}.
---
---@since 15
---@param buf integer Buffer number (0 for current buffer)
---@param start integer|[integer,integer] Start row or `{row, col}`
---@param stop? integer|[integer,integer] Stop row or `{row, col}` (excluded)
---@return vim.treesitter.CaptureInfo[]
function M.get_captures(buf, start, stop)
  buf = vim._resolve_bufnr(buf)

  --- @type integer, integer, integer, integer
  local start_row, start_col, end_row, end_col
  if type(start) == 'number' then
    start_row, start_col = start, 0
  else
    start_row, start_col = start[1], start[2]
  end

  if stop == nil then
    end_row = type(start) == 'number' and start_row + 1 or start_row
    end_col = type(start) == 'number' and 0 or start_col + 1
  elseif type(stop) == 'number' then
    end_row, end_col = stop, 0
  else
    end_row, end_col = stop[1], stop[2]
  end

  local buf_highlighter = M.highlighter.active[buf]

  if not buf_highlighter or M._range.cmp_pos.ge(start_row, start_col, end_row, end_col) then
    return {}
  end

  local matches = {} --- @type vim.treesitter.CaptureInfo[]
  local query_range = { start_row, start_col, end_row, end_col } --- @type Range4

  -- Highlighting only parses visible ranges, so offscreen injections may be missing.
  buf_highlighter.tree:parse(query_range)
  buf_highlighter.tree:for_each_tree(function(tstree, tree)
    if not tstree then
      return
    end

    local root = tstree:root()
    if not M._range.intercepts({ root:range() }, query_range) then
      return
    end

    local q = buf_highlighter:get_query(tree:lang())
    local query = q:query()

    -- Some injected languages may not have highlight queries.
    if not query then
      return
    end

    local iter = query:iter_captures(root, buf_highlighter.bufnr, start_row, end_row, {
      start_col = start_col,
      end_col = end_col,
    })
    for id, node, metadata, match in iter do
      local nsrow, nscol, nerow, necol = node:range()
      if M._range.intercepts({ nsrow, nscol, nerow, necol }, query_range) then
        ---@diagnostic disable-next-line: invisible
        local capture = query.captures[id] -- name of the capture in the query
        if capture ~= nil then
          local _, pattern_id = match:info()
          matches