@@ -110,7 +110,7 @@ Designate a function signature `sig` that should dispatch on keyword arguments.
110
110
function can also be provided, in which case _all_ calls to that function are will
111
111
dispatch to keyword methods.
112
112
113
- Note that no keywords should appear in `sig` signatures .
113
+ It is possible to specify keyword aliases by specifying `from => to` pairs in the keyword position .
114
114
115
115
The optional `methods` argument allows a block of keyword methods specified as anonymous
116
116
functions. To define additional keyword methods, use the [`@kwmethod`](@ref) macro.
131
131
# @kwdispatch f(x)
132
132
# @kwmethod f(x;a) = x+a
133
133
# @kwmethod f(x;b) = x-b
134
+
135
+ @kwdispatch f(; alpha=>α) # specifies alpha as an alias to α
134
136
```
135
137
"""
136
138
macro kwdispatch (fexpr,methods= nothing )
@@ -143,10 +145,19 @@ macro kwdispatch(fexpr,methods=nothing)
143
145
144
146
@assert fcall isa Expr && fcall. head == :call
145
147
148
+ rename_expr = :(kw)
149
+
146
150
f = fcall. args[1 ]
147
151
posargs = fcall. args[2 : end ]
148
152
if length (posargs) >= 1 && posargs[1 ] isa Expr && posargs[1 ]. head == :parameters
149
- error (" keyword arguments should only appear in @kwdispatch expressions" )
153
+ parameters = popfirst! (posargs)
154
+ for p in parameters. args
155
+ if p isa Expr && p. head == :call && p. args[1 ] == :(=> )
156
+ rename_expr = :(kw == $ (QuoteNode (p. args[2 ])) ? $ (QuoteNode (p. args[3 ])) : $ rename_expr)
157
+ else
158
+ error (" Only renames (from => to) are allowed in keyword position of `@kwdispatch`" )
159
+ end
160
+ end
150
161
end
151
162
f = argmeth (f)
152
163
@@ -160,8 +171,11 @@ macro kwdispatch(fexpr,methods=nothing)
160
171
ff = esc (argsym (f))
161
172
162
173
quote
163
- $ (wrap_where (:($ (esc (f))($ (esc .(posargs_method)... ); kwargs... )), wherestack)) =
164
- KeywordDispatch. kwcall (ntsort (kwargs. data), $ ff, $ (esc .(argsym .(posargs_method))... ))
174
+ $ (wrap_where (:($ (esc (f))($ (esc .(posargs_method)... ); kwargs... )), wherestack)) = begin
175
+ N = map (kw -> $ rename_expr, propertynames (kwargs. data))
176
+ nt = NamedTuple {N} (Tuple (kwargs. data))
177
+ KeywordDispatch. kwcall (ntsort (nt), $ ff, $ (esc .(argsym .(posargs_method))... ))
178
+ end
165
179
$ (generate_kwmethods (methods, f, posargs, wherestack))
166
180
end
167
181
end
0 commit comments