|
43 | 43 |
|
44 | 44 | getproperties(o::NamedTuple) = o |
45 | 45 | getproperties(o::Tuple) = o |
46 | | -@generated function getproperties(obj) |
47 | | - fnames = fieldnames(obj) |
48 | | - fvals = map(fnames) do fname |
49 | | - Expr(:call, :getproperty, :obj, QuoteNode(fname)) |
| 46 | +if VERSION >= v"1.7" |
| 47 | + function getproperties(obj) |
| 48 | + fnames = propertynames(obj) |
| 49 | + NamedTuple{fnames}(getproperty.(Ref(obj), fnames)) |
| 50 | + end |
| 51 | +else |
| 52 | + @generated function getproperties(obj) |
| 53 | + if which(propertynames, Tuple{obj}).sig != Tuple{typeof(propertynames), Any} |
| 54 | + # custom propertynames defined for this type |
| 55 | + return quote |
| 56 | + msg = """ |
| 57 | + Different fieldnames and propertynames are only supported on Julia v1.7+. |
| 58 | + For older julia versions, consider overloading |
| 59 | + `ConstructionBase.getproperties(obj::$(typeof(obj))`. |
| 60 | + See also https://github.com/JuliaObjects/ConstructionBase.jl/pull/60. |
| 61 | + """ |
| 62 | + error(msg) |
| 63 | + end |
| 64 | + end |
| 65 | + fnames = fieldnames(obj) |
| 66 | + fvals = map(fnames) do fname |
| 67 | + :(obj.$fname) |
| 68 | + end |
| 69 | + :(NamedTuple{$fnames}(($(fvals...),))) |
50 | 70 | end |
51 | | - fvals = Expr(:tuple, fvals...) |
52 | | - :(NamedTuple{$fnames}($fvals)) |
53 | 71 | end |
54 | 72 |
|
55 | 73 | ################################################################################ |
@@ -86,9 +104,8 @@ function validate_setproperties_result( |
86 | 104 | end |
87 | 105 | @noinline function validate_setproperties_result(nt_new, nt_old, obj, patch) |
88 | 106 | O = typeof(obj) |
89 | | - P = typeof(patch) |
90 | 107 | msg = """ |
91 | | - Failed to assign properties $(fieldnames(P)) to object with fields $(fieldnames(O)). |
| 108 | + Failed to assign properties $(propertynames(patch)) to object with properties $(propertynames(obj)). |
92 | 109 | You may want to overload |
93 | 110 | ConstructionBase.setproperties(obj::$O, patch::NamedTuple) |
94 | 111 | ConstructionBase.getproperties(obj::$O) |
|
0 commit comments