Skip to content

Commit 0588cd4

Browse files
authored
remove unnecessary true && part from at-view macro (#53064)
The modification that expands `@view A[i]` to `true && view(A, i)` appears to go back as far as #20247. However, I'm not entirely sure why this is necessary. Considering that just expanding it to `view(A, i)` still seems to pass the base test suite, I wonder if it might be just better to get rid of that part.
1 parent 5b64a0d commit 0588cd4

File tree

2 files changed

+30
-11
lines changed

2 files changed

+30
-11
lines changed

base/views.jl

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -123,20 +123,21 @@ julia> A
123123
```
124124
"""
125125
macro view(ex)
126+
Meta.isexpr(ex, :ref) || throw(ArgumentError(
127+
"Invalid use of @view macro: argument must be a reference expression A[...]."))
128+
ex = replace_ref_begin_end!(ex)
129+
# NOTE We embed `view` as a function object itself directly into the AST.
130+
# By doing this, we prevent the creation of function definitions like
131+
# `view(A, idx) = xxx` in cases such as `@view(A[idx]) = xxx.`
126132
if Meta.isexpr(ex, :ref)
127-
ex = replace_ref_begin_end!(ex)
128-
if Meta.isexpr(ex, :ref)
129-
ex = Expr(:call, view, ex.args...)
130-
else # ex replaced by let ...; foo[...]; end
131-
if !(Meta.isexpr(ex, :let) && Meta.isexpr(ex.args[2], :ref))
132-
error("invalid expression")
133-
end
134-
ex.args[2] = Expr(:call, view, ex.args[2].args...)
135-
end
136-
Expr(:&&, true, esc(ex))
133+
ex = Expr(:call, view, ex.args...)
134+
elseif Meta.isexpr(ex, :let) && (arg2 = ex.args[2]; Meta.isexpr(arg2, :ref))
135+
# ex replaced by let ...; foo[...]; end
136+
ex.args[2] = Expr(:call, view, arg2.args...)
137137
else
138-
throw(ArgumentError("Invalid use of @view macro: argument must be a reference expression A[...]."))
138+
error("invalid expression")
139139
end
140+
return esc(ex)
140141
end
141142

142143
############################################################################

test/subarray.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -937,3 +937,21 @@ end
937937
v = view(1:2, r)
938938
@test v == view(1:2, collect(r))
939939
end
940+
941+
# https://github.com/JuliaLang/julia/pull/53064
942+
# `@view(A[idx]) = xxx` should raise syntax error always
943+
@test try
944+
Core.eval(@__MODULE__, :(@view(A[idx]) = 2))
945+
false
946+
catch err
947+
err isa ErrorException && startswith(err.msg, "syntax:")
948+
end
949+
module Issue53064
950+
import Base: view
951+
end
952+
@test try
953+
Core.eval(Issue53064, :(@view(A[idx]) = 2))
954+
false
955+
catch err
956+
err isa ErrorException && startswith(err.msg, "syntax:")
957+
end

0 commit comments

Comments
 (0)