Skip to content

Commit

Permalink
support interpolation in sel"" macro. (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
lmiq authored Feb 12, 2025
1 parent a2e3fa0 commit 211f4aa
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/select.jl
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ Trivial selector that returns `true` for any structural element.
allselector(el) = true

# Acts as a function when used within typical julia filtering functions
# by converting a string selection into a query call
# by converting a string selection into a query call
struct Select{Q} <: Function
query_string::String
query::Q
Expand All @@ -450,9 +450,30 @@ end

Base.show(io::IO, ::MIME"text/plain", s::Select) = print(io, """Select("$(s.query_string)")""")

#
# Parse selection string allowing interpolation in sel macro:
# https://discourse.julialang.org/t/str-string-interpolation/125766/11?u=lmiq
#
_select(args...) = Select(string(args...))
"String selection syntax."
macro sel_str(str)
Select(str)
macro sel_str(s)
ex = Expr(:call, GlobalRef(BioStructures, :_select))
i = firstindex(s)
buf = IOBuffer(maxsize=ncodeunits(s))
while i <= ncodeunits(s)
c = @inbounds s[i]
i = nextind(s, i)
if c === '$'
position(buf) > 0 && push!(ex.args, String(take!(buf)))
val, i = Meta.parse(s, i; greedy=false)
Meta.isexpr(val, :incomplete) && error(val.args[1])
val !== nothing && push!(ex.args, val)
else
print(buf, c)
end
end
position(buf) > 0 && push!(ex.args, String(take!(buf)))
return esc(ex)
end

const operators = (
Expand Down
5 changes: 5 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,11 @@ end
@test length(collectatoms(struc, sel"disordered")) == 68
@test length(collectatoms(struc, sel"sscode E")) == 2448
@test length(collectatoms(struc, sel"helix")) == 4047
# check interpolation support
ss_type = "helix"
@test length(collectatoms(struc, sel"$ss_type")) == 4047
sel_chains = ('A', 'B')
@test length(collectresidues(struc, sel"chain $(first(sel_chains)) or chain $(last(sel_chains))")) == 544

@test length(collectresidues(struc, sel"chain A or chain B")) == 544
@test length(collectresidues(struc, sel"standard")) == 1420
Expand Down

0 comments on commit 211f4aa

Please sign in to comment.