Skip to content

Commit 25f5f5a

Browse files
authored
Merge pull request #168 from phipsgabler/phg/interpolation
Allow interpolation of properties
2 parents bff69d5 + 8fdfb7f commit 25f5f5a

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "Setfield"
22
uuid = "efcf1570-3423-57d1-acb7-fd33fddbac46"
3-
version = "0.8.1"
3+
version = "0.8.2"
44

55
[deps]
66
ConstructionBase = "187b0558-2788-49d3-abe0-74a17ed4e7c9"

src/sugar.jl

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,12 +123,17 @@ function parse_obj_lenses(ex)
123123
lens = :($IndexLens($index))
124124
end
125125
elseif @capture(ex, front_.property_)
126-
property isa Union{Symbol,String} || throw(ArgumentError(
127-
string("Error while parsing :($ex). Second argument to `getproperty` can only be",
128-
"a `Symbol` or `String` literal, received `$property` instead.")
129-
))
130126
obj, frontlens = parse_obj_lenses(front)
131-
lens = :($PropertyLens{$(QuoteNode(property))}())
127+
if property isa Union{Symbol,String}
128+
lens = :($PropertyLens{$(QuoteNode(property))}())
129+
elseif is_interpolation(property)
130+
lens = :($PropertyLens{$(esc(property.args[1]))}())
131+
else
132+
throw(ArgumentError(
133+
string("Error while parsing :($ex). Second argument to `getproperty` can only be",
134+
"a `Symbol` or `String` literal, received `$property` instead.")
135+
))
136+
end
132137
elseif @capture(ex, f_(front_))
133138
obj, frontlens = parse_obj_lenses(front)
134139
lens = :($FunctionLens($(esc(f))))
@@ -231,6 +236,11 @@ julia> t = ("one", "two")
231236
232237
julia> set(t, (@lens _[1]), "1")
233238
("1", "two")
239+
240+
julia> # Indices are always evaluated in external scope; for properties, you can use interpolation:
241+
n, i = :a, 10
242+
@lens(_.\$n[i, i+1])
243+
(@lens _.a[10, 11])
234244
```
235245
236246
"""

test/test_core.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,13 @@ end
509509
@test @lens($lbc)== lbc
510510
@test @lens(_.a $lbc) == @lens(_.a) lbc
511511
@test @lens(_.a $lbc _[1] $lbc) == @lens(_.a) lbc @lens(_[1]) lbc
512+
513+
# property interpolation
514+
name = :a
515+
fancy(name, suffix) = Symbol("fancy_", name, suffix)
516+
@test @lens(_.$name) == @lens(_.a)
517+
@test @lens(_.x[1, :].$name) == @lens(_.x[1, :].a)
518+
@test @lens(_.x[1, :].$(fancy(name, ""))) == @lens(_.x[1, :].fancy_a✨)
512519
end
513520

514521
end

0 commit comments

Comments
 (0)