mirror of
https://gitea.invidious.io/iv-org/shard-ameba.git
synced 2024-08-15 00:53:29 +00:00
AST node source code
This commit is contained in:
parent
adfe654733
commit
a9421ee79b
2 changed files with 49 additions and 0 deletions
|
@ -45,5 +45,31 @@ module Ameba::AST
|
||||||
subject.string_literal?(Crystal::Nop.new).should be_false
|
subject.string_literal?(Crystal::Nop.new).should be_false
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "#node_source" do
|
||||||
|
it "returns original source of the node" do
|
||||||
|
s = %(
|
||||||
|
a = 1
|
||||||
|
)
|
||||||
|
node = Crystal::Parser.new(s).parse
|
||||||
|
source = subject.node_source node, s.split("\n")
|
||||||
|
source.should eq ["a = 1"]
|
||||||
|
end
|
||||||
|
|
||||||
|
it "returns original source of multiline node" do
|
||||||
|
s = %(
|
||||||
|
if ()
|
||||||
|
:ok
|
||||||
|
end
|
||||||
|
)
|
||||||
|
node = Crystal::Parser.new(s).parse
|
||||||
|
source = subject.node_source node, s.split("\n")
|
||||||
|
source.should eq([
|
||||||
|
"if ()",
|
||||||
|
" :ok",
|
||||||
|
" end",
|
||||||
|
])
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -6,4 +6,27 @@ module Ameba::AST::Util
|
||||||
def string_literal?(node)
|
def string_literal?(node)
|
||||||
node.is_a? Crystal::StringLiteral
|
node.is_a? Crystal::StringLiteral
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def node_source(node, code_lines)
|
||||||
|
loc, end_loc = node.location, node.end_location
|
||||||
|
|
||||||
|
return unless loc && end_loc
|
||||||
|
|
||||||
|
line, column = loc.line_number - 1, loc.column_number - 1
|
||||||
|
end_line, end_column = end_loc.line_number - 1, end_loc.column_number - 1
|
||||||
|
node_lines = code_lines[line..end_line]
|
||||||
|
first_line, last_line = node_lines[0]?, node_lines[-1]?
|
||||||
|
|
||||||
|
return unless first_line && last_line
|
||||||
|
|
||||||
|
node_lines[0] = first_line.sub(0...column, "")
|
||||||
|
|
||||||
|
if line == end_line # one line
|
||||||
|
end_column = end_column - column
|
||||||
|
last_line = node_lines[0]
|
||||||
|
end
|
||||||
|
node_lines[-1] = last_line.sub(end_column + 1...last_line.size, "")
|
||||||
|
|
||||||
|
node_lines
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue