Skip to content

Commit

Permalink
Fix invalid treesitter query caused by special node name
Browse files Browse the repository at this point in the history
The "prefix" and "suffix" fields of string nodes have non-identifier name,
caused invalid TS query like

    (string prefix: """ string_content: (string_content) @_1 (#eq? @_1 "s") suffix: """)
  • Loading branch information
cshuaimin committed Apr 17, 2023
1 parent a30674d commit e576851
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
11 changes: 3 additions & 8 deletions lua/ssr/search.lua
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,15 @@ local function build_sexpr(node, source)
-- Special identifier __ssr_var_name is a named wildcard.
local var = text:match("^" .. wildcard_prefix .. "([_%a%d]+)$")
if var then
-- local row = node:start()
-- local indent = api.nvim_buf_get_lines(source, row, row + 1, true)[1]
-- indent = string.match(indent, "^%s*")
wildcards[var] = next_idx
next_idx = next_idx + 1
return "(_) @" .. var
end

-- Leaf nodes (keyword, identifier, literal and symbol) should match text.
if node:named_child_count() == 0 then
text = text:gsub([[\]], [[\\]])
text = text:gsub('"', '\\"')
text = text:gsub("\n", "\\n")
local sexpr = string.format('(%s) @_%d (#eq? @_%d "%s")', node:type(), next_idx, next_idx, text)
local sexpr =
string.format("(%s) @_%d (#eq? @_%d %s)", node:type(), next_idx, next_idx, utils.to_ts_query_str(text))
next_idx = next_idx + 1
return sexpr
end
Expand All @@ -65,7 +60,7 @@ local function build_sexpr(node, source)
if name and child:named() then
sexpr = sexpr .. string.format(" %s: %s", name, build(child))
elseif name and not child:named() then
sexpr = sexpr .. string.format(' %s: "%s"', name, child:type())
sexpr = sexpr .. string.format(" %s: %s", name, utils.to_ts_query_str(child:type()))
elseif not name and child:named() then
-- Pin child position with anchor `.`
sexpr = string.format(" %s . %s", sexpr, build(child))
Expand Down
9 changes: 9 additions & 0 deletions lua/ssr/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,13 @@ function M.remove_indent(lines, indent)
end
end

--- Escape special characters in s and quote it in double quotes.
---@param s string
function M.to_ts_query_str(s)
s = s:gsub([[\]], [[\\]])
s = s:gsub([["]], [[\"]])
s = s:gsub("\n", [[\n]])
return '"' .. s .. '"'
end

return M

0 comments on commit e576851

Please sign in to comment.