Skip to content

Commit 2f96fbc

Browse files
committed
performance
1 parent c00a3a5 commit 2f96fbc

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

src/patch/cst.jl

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
using CSTParser
2-
using CSTParser: EXPR, Call, Location, exprloc, charrange
2+
using CSTParser: EXPR, Call, Location, LocExpr, exprloc, charrange
33

44
expridx(x, ii) = (@assert isempty(ii); x)
55
expridx(x::Expr, ii) = isempty(ii) ? x : expridx(x.args[ii[1]], ii[2:end])
6+
expridx(x::LocExpr, ii) = expridx(x.expr, ii)
67

78
function precedence_level(cst::EXPR, loc::Location)
89
parent = cst[CSTParser.parent(loc)]
@@ -48,16 +49,16 @@ struct SourceFile
4849
path::String
4950
text::String
5051
cst::EXPR
51-
ast::Expr
52+
ast::LocExpr
5253
end
5354

5455
function SourceFile(path::String, text = String(read(path)))
5556
cst = CSTParser.parse(text, true)
56-
SourceFile(path, text, cst, Expr(cst))
57+
SourceFile(path, text, cst, LocExpr(cst))
5758
end
5859

5960
function replacement(src::SourceFile, p::Replace)
60-
loc = exprloc(src.cst, p.idx)
61+
loc = exprloc(src.ast, p.idx)
6162
prec = precedence_level(src.cst, loc)
6263
_, span = charrange(src.cst, loc)
6364
span => sprint(Base.show_unquoted, p.new, 0, prec)
@@ -66,7 +67,7 @@ end
6667
function replacement(src::SourceFile, p::Insert)
6768
append = p.idx[end] > length(expridx(src.ast, p.idx[1:end-1]).args)
6869
append && (p.idx[end] -= 1)
69-
loc = exprloc(src.cst, p.idx)
70+
loc = exprloc(src.ast, p.idx)
7071
# TODO handle cases like this more generally
7172
src.cst[CSTParser.parent(loc)] isa EXPR{Call} && (loc.ii[end] = max(loc.ii[end], 2))
7273
_, span = charrange(src.cst, loc)
@@ -81,7 +82,7 @@ function replacement(src::SourceFile, p::Insert)
8182
end
8283

8384
function replacement(src::SourceFile, p::Delete)
84-
loc = exprloc(src.cst, p.idx)
85+
loc = exprloc(src.ast, p.idx)
8586
span, _ = charrange(src.cst, loc)
8687
sep = separator(src.cst, loc)
8788
sep isa AbstractRange || (sep = span)
@@ -120,16 +121,18 @@ function patch!(src::SourceFile, p)
120121
end
121122

122123
function sourcemap(f, src::SourceFile)
123-
ex = striplines(f(src.ast))
124-
patch(src, diff(src.ast, ex))
124+
expr = CSTParser.striploc(src.ast)
125+
ex = striplines(f(expr))
126+
patch(src, diff(expr, ex))
125127
end
126128

127129
function sourcemap(f, path::AbstractString)
128130
isdir(path) && return sourcemap_dir(f, path)
129131
isfile(path) || error("No file at $path")
130132
s = SourceFile(path)
131-
ex = striplines(f(s.ast))
132-
patch!(s, diff(s.ast, ex))
133+
expr = CSTParser.striploc(s.ast)
134+
ex = striplines(f(expr))
135+
patch!(s, diff(expr, ex))
133136
return
134137
end
135138

0 commit comments

Comments
 (0)