Skip to content

Commit 9899954

Browse files
authored
[JuliaSyntax] Return generator from attrnames(::SyntaxTree) (#61522)
Return a generator instead of a `Vector{Symbol}` from `attrnames` to avoid unnecessary allocation. `attrnames` is called from `hasproperty(::SyntaxTree, ::Symbol)` and similar hot-path queries, so avoiding the allocation would be worthwhile. This is compatible with the `propertynames` interface which accepts any iterable of properties, although `node_string` needed to be updated since the return value is now `Tuple{Vararg{Symbol}}` instead of a vector of the symbols. Also wrap inference tests in a `@testset` and add a test for `hasproperty` return type inference. Follows up #61518.
1 parent a992d84 commit 9899954

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

JuliaSyntax/src/porcelain/syntax_graph.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ end
208208
# fallback printing
209209
function node_string(ex::SyntaxTree, depth=2)
210210
out = "(_id="*string(ex._id)
211-
for n in sort!(attrnames(ex))
211+
for n in sort!(collect(attrnames(ex)))
212212
out *= ", "*string(n)*"="*repr(getproperty(ex, n))
213213
end
214214
if is_leaf(ex)
@@ -283,7 +283,7 @@ end
283283

284284
function attrnames(ex::SyntaxTree)
285285
attrs = ex._graph.attributes
286-
Symbol[name for (name, value) in pairs(attrs) if haskey(value, ex._id)]
286+
(name::Symbol for (name, value) in pairs(attrs) if haskey(value, ex._id))
287287
end
288288

289289
function copy_node(ex::SyntaxTree)

JuliaSyntax/test/runtests.jl

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,10 @@ end
4545

4646
include("serialization.jl")
4747

48-
# Basic inference tests
4948
@static if isdefined(Base, :infer_return_type)
50-
@test Base.infer_return_type(JuliaSyntax.sourcetext, (JuliaSyntax.SyntaxTree,)) <: AbstractString
51-
@test Base.infer_return_type(JuliaSyntax.byte_range, (JuliaSyntax.SyntaxTree,)) == UnitRange{Int}
49+
@testset "Basic inference tests" begin
50+
@test Base.infer_return_type(JuliaSyntax.sourcetext, (JuliaSyntax.SyntaxTree,)) <: AbstractString
51+
@test Base.infer_return_type(JuliaSyntax.byte_range, (JuliaSyntax.SyntaxTree,)) == UnitRange{Int}
52+
@test Base.infer_return_type(JuliaSyntax.hasproperty, (JuliaSyntax.SyntaxTree,Symbol)) == Bool
53+
end
5254
end

0 commit comments

Comments
 (0)