Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Definition of function with keyword arguments via macro does not work as expected #8338

Closed
jonas-hagen opened this issue Sep 13, 2014 · 2 comments

Comments

@jonas-hagen
Copy link

Consider the following example:

macro myDef1(name)
    return esc(:( $name(x; y=3) = x*y ))
end
@myDef1 f1
f1(4) # gives 3 but 12 expected
f1(4, y=5) # gives 5 but 20 expected

Or:

macro myDef2(name)
    return esc(:( $name(x; y=3) = x )) # not using y here!
end
@myDef2 f2 # gives ERROR: syntax: malformed expression

Whereas if the return statment within the function is expicitly written, it works:

macro myDef3(name)
    return esc(:( $name(x; y=3) = return (x*y) ))
end
@myDef3 f3
f3(4) # now gives 12, as expected
f3(4, y=5) # now gives 20, as expected

Julia Version 0.3.0
Commit 7681878 (2014-08-20 20:43 UTC)

@eschnett
Copy link
Contributor

Keyword arguments look like assignments, but they are not -- they are :kw expressions:

julia> dump(:(f(a=2,b)))
Expr 
  head: Symbol call
  args: Array(Any,(3,))
    1: Symbol f
    2: Expr 
      head: Symbol kw
      args: Array(Any,(2,))
        1: Symbol a
        2: Int64 2
      typ: Any
    3: Symbol b
  typ: Any

I assume that, in the first case, the parser treats the content of esc(...) expression as assignment statement, so that its LHS (left hand side) is a sequence of statements ("x" and "y=3"), where "y=3" is an assignment again. In your second case, the return statement forces the parser to treat this as function definition, and "y=3" is then correctly parsed as keyword argument.

If this is true, then using the "function" syntax for your function definition should help as well.

@JeffBezanson
Copy link
Sponsor Member

cc @JuliaBackports

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants