Skip to content

Add "traditional" function call syntax #9116

Closed as not planned
Closed as not planned

Description

@kubouch

Related problem

Add "traditional" function call syntax as a solution to the "flag-passing" problem:

def func [--bar: int, --flag] { }

def spam [--bar: int, --flag] {
    func  # How to pass --bar and --flag forward?
}

Currently, the only solution is to use if or match to go through all the combinations which quickly gets out of hand with growing number of parameters.

Describe the solution you'd like

Allow "traditional" function call syntax known from other languages:

func(bar: $bar, flag: $flag)

If the parameters are named the same, you could use the following shorthand (inspired by https://github.com/SerenityOS/jakt):

func($bar, $flag)

Describe alternatives you've considered

This solution intentionally does not provides fully dynamic variable-length arguments in the style of kwargs known from Python. "kwargs"-like functionality would bypass signature type checking and it also tends to produce less readable APIs turning the signature into a black box. If you need a fully dynamic parameter, you can pass a record.

For externals, you can use newly allowed blocks to extern (#8956). The variable-length args are stored as strings under $rest which makes creating custom wrappers around externals much easier.

We could also use = instead of ::

func(bar: $bar, flag: $flag)

vs.

func(bar = $bar, flag = $flag)

I might lean towards : here.

A possible caveat:

func($bar, $flag)

vs.

func ($bar, $flag)

In the second case, it would try to call func with one subexpression arg which might produce strange errors.

Additional context and details

The function call syntax also allows nice inlining of calls into expressions: 3 + add-ten(7) + 20 vs. 3 + (add-ten 7) + 20

Related issues: #7758 #7260 #7033

Activity

  1. added
    category:enhancement
    A:parser
    category:meta-issue
    on May 6, 2023
  2. cumber commented on May 20, 2023

    @cumber

    Given that nushell generally does whitespace-separated arguments rather than C-like arguments, using C-like syntax for this one thing feels a little "off" to me. The func($bar, $flag) vs func ($bar, $flag) caveat is a manifestation of this infelicity.

    In a way the (bar: $bar, flag: $flag) part of the syntax looks rather like a funny way of writing a record: { bar: $bar, flag: $flag }. So maybe a more fitting way of doing this would be to have special syntax for applying a command to a record. Something like:

    func @ { bar: $bar, flag: $flag }
    

    Some sort of special syntax (like @) would be required to distinguish this apply-to-record feature from applying func to a single positional argument which happened to be a record. (If the "special syntax" we use is to swap the braces for parentheses rather than adding an operator or keyword, we get back to the "traditional function call syntax", so if we stop here my suggestion is merely bikeshedding the syntax)

    But I wonder, if we see this as an ability to apply a command to a record, rather than merely as unusual syntax required for passing flags, would it be possible to do this with a runtime record value rather than only a record-literal? E.g. would it be possible to implement a feature that would allow:

    let args = { bar: $bar, flag: $flag }
    func @ $args
    

    Or even:

    def wrapper [args] {
      func @ $args
    }
    

    I would expect the fields accessed in $args to be determined by the signature for func, and a runtime error if $args turns out not to have the required fields (or not to be a record). Much like the behaviour of this:

    def extract-some-fields [args] {
      [ $args.bar, $args.flag ]
    }
    

    So if it's possible to tell the signature of func at parse time, this wouldn't even necessarily require any more runtime type checking than things like extract-some-fields already do. And yet it would provide a lot of the flexibility of python-like **kwargs application (not receiving **kwargs) while (I think) remaining within the existing style and principles of Nushell.

    But if only a static version with record-literals would be possible, then maybe the "traditional-function-call" idea is indeed better, as looking like "real" records could mislead people into trying to use it more dynamically.

  3. kubouch commented on May 21, 2023

    @kubouch
    ContributorAuthor

    These are good points. A problematic aspect of the proposed syntax are:

    1. Multi-word commands:
    spam func(bar: $bar, flag: $flag)
    

    or

    `spam func`(bar: $bar, flag: $flag)
    

    ???
    2. Space being significant: func(bar: $bar, flag: $flag) vs func (bar: $bar, flag: $flag) being two completely different things.

    The applying record method is interesting. One important part of the design is to be able to shorten func(bar: $bar, flag: $flag) to func($bar, $flag) BUT WHAT IF we allowed this shortening for records in general, e.g., let record = { $bar, $flag }?

  4. cumber commented on May 21, 2023

    @cumber

    @kubouch I would definitely use such shorthand syntax for records in general, yes!

  5. cumber commented on May 21, 2023

    @cumber

    @kubouch I suppose using an operator rather than parentheses to indicate that the command is being applied to an argument list rather than normal arguments (whether it's a record or special-purpose argument list syntax) would help the multi-word command case as well? At least I think I would be less confused to see

    spam func @ { bar: $bar, flag: $flag }
    

    than

    spam func(bar: $bar, flag: $flag)
    

    (Especially if there is no permitted space between the func and the (). My brain just has an easier time reading the operator as "lower precedence" than the grouping of spam and func.

    I don't know whether it would be possible to extend that to allow partially applying a command to some arguments normally and then filling in the rest from a record, but that would be useful too. e.g.

    def func [foo: int, --bar: int, --flag] { }
    
    let result = func 17 @ { $bar: 29, $flag: false }
    

    I'd imagine that would be added implementation complexity that shouldn't be in the first draft, but it would be cool if it eventually developed that way. It's still all theoretically determinable what it means just from knowledge of the signature of func, I think. Maybe some tricky spots with $rest arguments. The other way around (partially applying to a record and then filling in more arguments via normal application) would be more problematic, as you'd have to also know the contents of the record to tell how to interpret any following positional arguments.

  6. kubouch commented on May 21, 2023

    @kubouch
    ContributorAuthor

    I think it could all be a record because all signature parameters are named. For example:

    def foo [x: int, --foo, --bar(b): string, ...rest] { ... }
    

    would be called as

    foo(x, $foo, bar: ''foo", 1, 2, 4)
    # or
    foo($x, $foo, bar: ''foo", rest: [ 1 2 4 ])
    

    with the traditional syntax or

    foo @ { $x, $foo, bar: $bar, rest: [ 1 2 4 ] }
    

    with your proposed syntax.

    The problem with the @ syntax is that it might not be obvious what it means. Imagine seeing this when you just learned about Nushell:

    spam @ { $bar, flag: $x }
    

    Is it clear enough? To me, definitely less clear than spam($bar, flag: $x) . Maybe we could find something more intuitive? For example @pingiun proposed apply command some time ago in #7758 (comment) that would look like this:

    apply spam { $bar, flag: $x }
    
  7. amtoine commented on May 21, 2023

    @amtoine
    Member

    i think i like the more shell-like feeling of

    foo @ { $x, $foo, bar: $bar, rest: [ 1 2 4 ] }
    spam @ { $bar, flag: $x }
    

    or

    apply foo { $x, $foo, bar: $bar, rest: [ 1 2 4 ] }
    apply spam { $bar, flag: $x }
    

    compared to the standard calling syntax

    foo($x, $foo, bar: $bar, rest: [ 1 2 4 ])
    spam($bar, flag: $x)
    

    🤔

  8. amtoine commented on May 21, 2023

    @amtoine
    Member

    other ideas to replace @

    • foo <- { ... }
    • foo ^ { ... }
    • foo % { ... }

    (i prefer @ 😕)

  9. kubouch commented on May 21, 2023

    @kubouch
    ContributorAuthor

    One benefit of the functional syntax we'd lose with is being able to use it directly in expressions without wrapping into ():

    10 + add(3, 7) + 20
    
  10. kubouch commented on May 21, 2023

    @kubouch
    ContributorAuthor

    If we allow "traditional namespace syntax" then, we could write

    spam::foo($bar, flag: $x)
    

    which would solve the subcommand naming problem.

    Just throwing ideas here.

  11. amtoine commented on May 21, 2023

    @amtoine
    Member

    these are also nice 🤔

  12. cumber commented on May 21, 2023

    @cumber

    Yeah, @ was a suggestion with very little thought behind it. It could be a different operator, or a keyword (like apply), or any other syntax.

    The meat of my idea was to encode the argument list as a standard record, so that the argument list as a whole is a first-class value and you can use any existing tools for working with records to assemble an argument list. That's the main downside of the traditional call syntax; it's dedicated syntax for associating parameter names with argument values, instead of piggy-backing on the syntactic structures we already have for associating names and values.

    Also, I think it's easy to overestimate how intuitive the traditional call syntax. It only seems that way because it's common elsewhere, so a lot of people already know it. That's not really inherently intuitive though, it's relying on users already having memorised the notation; everything is intuitive once you've memorised it. It wouldn't be obvious to anyone for whom nushell is their first programming language. A keyword like apply has a claim that the word "apply" communicates some of the idea, but using symbols like ( ) (or @) doesn't; it's just something you have to learn about and memorise.

    There's even an argument to be made that the parenthesis-based syntax might be less intuitive than some other arbitrary symbol, since nushell already uses parentheses for other purposes. It's easier for users to learn what syntactic structures do if they always do the same thing (and it prevents issues like needing to use whitespace to distinguish func ($bar) from func($bar)).

  13. cumber commented on May 21, 2023

    @cumber

    One benefit of the functional syntax we'd lose with is being able to use it directly in expressions without wrapping into ():

    10 + add(3, 7) + 20
    

    Why couldn't that work with an operator? It's just a matter of giving it a high enough precedence isn't it?

    10 + add @ { x: 3, y: 7 } + 20
    
  14. 4 remaining items

  15. added
    semantics
    on May 24, 2023
  16. kubouch commented on May 24, 2023

    @kubouch
    ContributorAuthor

    func x y --flag is again obvious to anyone who has ever interacted with a CLI tool :-).

    If you have a command printfoo that takes no parameters, then in 10 + printfoo + 20 the "printfoo" is still interpreted as a string. That's how the language currently works that bare words in value positions are interpreted as strings. You could enforce a command call with 10 + printfoo() + 20 with the "traditional" syntax. The @ syntax would need something similar: 10 + printfoo @ {} + 20. Maybe would be clearer without the spaces: 10 + printfoo@{} + 20, not sure.

    Also, going back to your original message, the records would need to be record literals, or maybe const, but you wouldn't have the full flexibility of Python's kwargs. Even having const record could create confusing situations:

    const args = { bar: $bar, flag: $flag }
    
    # ... 100 lines later:
    
    func @ $args  # what is args, I forgot...
    

    It could make the code less readable. Fully dynamic kwargs were recently dismissed as they can create very confusing APIs. If you need a full Python-like kwargs, you could just pass the record itself as a parameter.

    It's an interesting idea, though. The traditional call syntax still suffers from the space problem (foo($bar) vs foo ($bar)), so no solution is without drawbacks.

  17. cumber commented on May 25, 2023

    @cumber

    "100 lines later, what is $foo I forgot" goes for any variable, it has nothing to do with this specific usage. You can't avoid confusion for users by denying them any features that could possibly be confusing! Not unless you give them a system that does nothing.

    I saw that having a kwargs-style parameter for receiving arguments had already been discussed and rejected, but that's not what I'm proposing. Python has two syntactic features you might call "kwargs" and they're actually independent; don't confuse them.

    Receiving kwargs would mean the function is defined like def foo [**kwargs] {...} and then called with the ordinary foo --x=13 --y=hello syntax, and inside foo you would have $kwargs bound to { x: 13, y: "hello" }. I agree this would be a bad idea; it means any call has to be closely coupled to the implementation of the command (because that's what determines which parameters it will examine in the $kwargs record, which is its actual interface), basically requiring fragile and hard-to-understand code. And as you point out, taking an untyped record parameter is equivalent anyway. Any API that needs this flexibility can already be written in Nushell today. Receiving kwargs would only provide the minor syntactic shortcut of letting you fill a dynamic structure (a record) from a static argument list. --foo=1 --bar=$whatever contains the exact same information as { foo: 1, bar: $whatever }, and it's only 3 characters shorter!

    What I'm proposing is the other way around. I want kwargs-style specification of arguments I'm passing, not ones I'm receiving. I want to work with things defined like def foo [x : int, y : string] {...} where the arguments it takes are fully specified as normal, with no confusing dynamic API. I just want call foo as foo @ $args if $arg is of type record<x: int, y: string>. This would give me flexibility to dynamically assemble a call to an ordinary pre-defined command, something that is a new capability (unlike receiving kwargs). The alternative is writing a wrapper for every command I want to call this way that takes all the same parameters as fields of a single record and then properly extracts them and passes them as normal arguments; this can be a lot of extra boiler plate if the command has a lot of parameters, and it has to be updated to stay in sync. Passing kwargs allows us to avoid this extra fragile code.

    Note you can already do this in Nushell today:

    def foo [rec : record<x: int, y: string>] { echo $rec }
    
    let kwargs = { x: 13, y: hello }
    
    foo $kwargs
    

    And you get an error if the runtime value of kwargs doesn't have the correct fields. So it clearly is possible for Nushell to check a dynamic record against the signature of a command, without it being a const. All that is required is a way to say "match a command's signature against the fields of a record instead of a hard-coded list of arguments". That would give the ability to use this flexibility on all existing commands, instead of requiring them all to be rewritten to take a single record.

    The traditional-style function call syntax is just another way of writing a static list of arguments. If it weren't for the fact that the CLI style way of writing a static list of arguments doesn't provide any way to pass the value of a boolean flag from a variable, then implementing the traditional syntax would gain absolutely no capability. (Even the ability to avoid parentheses around a call in the middle of an expression isn't really a benefit, since you need to add parentheses around the argument list in the call instead! 10 + printfoo() + 20 is exactly the same characters as 10 + (printfoo) + 20, just in a different order). If that very minor capability is all we're getting, I personally would prefer we just fixed it so that --flag=$var worked, instead of boolean flags ignoring an explicitly passed value. That would be a much smaller change, no dual-syntax to confuse users, no space issue, no drawbacks that I can think of at all.

  18. added
    A:syntax
    and removed
    semantics
    on Sep 5, 2023
  19. dedebenui commented on Oct 11, 2023

    @dedebenui

    I'm on board with the @ syntax. It's a bit tricky to work with positional arguments though since users are not expected to know their internal names. How about flipping the @ syntax to work more like a pipe?

    let result = { $bar: 29, $flag: false } @ func 17
    

    This has two benefits in my view:

    1. the pipe-like syntax is already familiar. It's easy to learn.
    2. positional arguments still come after the piped function, as is the case with normal pipes

    If @ takes precedence over |, working in conjunction with normal pipes is fine too. Putting all together:

    let flags = { $bar: 29, $flag: false }
    glob * | $flags @ func 17
    
  20. bew commented on Nov 30, 2023

    @bew

    Edit: reading this thread made me think about all of this, but it might be a bit too general for this issue and could benefit from a separate issue, or be split. Tell me if I need to move/split this

    Instead of @ what about using the new spread operator?

    Where we could do:

    func ...{$flag1, $flag2} ...[positional params]
    
    # or more complex/realistic:
    
    def some-git [
      --colors
      --no-pager
      --git-dir: string
      ...rest    # (could even allow $in?)
    ] {
      mut global_opts = { $git_dir $no_pager }
      # (with a list, order would be retained, but we loose easy access (/ability to set) an option, like in the if branch below)
      if $colors {
        $global_opts.c = "color.ui=always"
      }
      git ...$global_opts commit ...$rest
    }
    
    some-git --no-pager --colors ./some/file --dry-run
    # => git --no-pager -c color.ui=auto commit ./some/file --dry-run
    
    some-git --git-dir=/custom.git ./file1 ./file2
    # => git --git-dir=/custom.git commit ./file1 ./file2

    The spread operator would learn the ability to apply record/lists to cmd calls
    (in addition to be usable in records, lists, ...)

    WDYT?


    Might be far-fetched, but here's a small brain dump to go further:

    An issue with the above idea is that order of arguments isn't preserved/guaranteed.

    To represent a list of (ordered) arguments (which can be either flags, options or positional args) I'm thinking we could have a new kind of collection that can be used to store that ordered list of args, with easy access to any arg like a record, with ability to append new items like a list, and when using the spread operator on it it would expand to the full list of args..


    More ideas... This looks like the basis of a kind of mini-framework to define structured wrappers to many kind of programs

    In addition we could add dedicated types (or special kind of records with a set of known keys) for each kind of arg:

    • option: like --work-tree=/foo, -c hello (both formats should be supported as some programs don't/only support = between option name and value) or -vvvv
    • flag: like --verbose, --no-pager or -V
      (flag could be a special case of option with no value? or a forced boolean value?)
    • arg: like commit, /path or "some text"
      (the most generic argument item, all others types should resolve to 0+ args)

    These types could be used to define new args on-the-fly without having to define them in a def args list.

    Sample syntax ideas:

    # fully detailed
    # (the `flag` type annotation would ensure the 'flag' schema of the record is respected)
    let version: flag = {
      true: "--version"
      false: null  # optional field, defaults to `null`
      value: true  # must be a boolean
      # closure (optional, this is the default) called when expanding this flag in an argument list
      resolve = {|self| $self | get $self.value? }
    }
    # helper function for the same thing
    let version = arg flag "--version" null true
    # or?
    let version = arg flag --true "--version" true
    # or maybe?
    let version = arg flag {true: "--version"} true
    #
    # NOTE: the flag's `value` or the `true` arg at the end of `arg flag` calls is the actual value of the flag.
    # On argument expansion/resolution of this flag, the value will be used to determine if the 'true' field should be used or the 'false' field (defaulting both to `null`/nothing)
    
    # Then similarly for `option`
    let work_tree: option = {
      name: "--work-tree" # (or this? long_name: "work-tree" ; or just long: "work-tree")
      value: "/foo"
      join: "=" # join option name & value with that (defaults to null, to generate 2 separate args)
      # default resolution/expansion:
      resolve: {|self|
        if $self.join {
          $"($self.name)($self.join)($self.value)"
        } else {
          [$self.name $self.value]
        }
      }
    }
    # helper function for the same thing
    let work_tree = arg option --long work-tree --join "=" /foo
    # or maybe?
    let work_tree = arg option {long: work-tree join: "="} /foo
    
    # Alternate `option` example:
    let verbosity_level: option = {
      value: 0 # An `option` value can be any(multiple) type(s)
      # The `expand` closure is responsible for making something useful with the value
      resolve: {|self| "-v" | std repeat $self.value }
    }
    $verbosity_level.value = 4 # set value after arg definition (prevent modification of other fields?)
    # helper function for the same thing
    let verbosity_level = arg option --repeated-arg "-v" 4
    
    # Simple arg
    let message: arg = {
      value: "some interesting text"
      # default resolution/expansion:
      resolve: {|self| $self.value}
      # but we could also do:
      resolve: {|self| ["-m" $self.value]}
    }
    let message = arg {} "some interesting text"
    
    # Now we put together the args in an argument list
    # (using a function call `args new` until we maybe find a literal syntax)
    let global_opts = args new [
      $version
      $work_tree
    ]
    let rest = args new [
      $verbosity_level
      $message
    ]
    
    # Then we pass our args:
    ^git ...$global_opts commit ...$rest

    WDYT?


    Thinking about this even more...

    This could be a kind of fully detailed declarative arguments definition for nushell functions!

    This basic nushell function:

    def some-git [
      --version(-V)              # Show version
      --work-tree: string = "."  # Use some work-tree
      --message: string          # Commit message
      ...rest                    # Extra args
    ] {
      # ...
    }

    Could be a shortcut for another, more flexible syntax:

    # args definition looks like a record, but it should keep order
    def some-git {
      version?: (arg flag {
        doc: "Show version"
        true: "--version"
        default: false # the default for a `flag`
      })
      work_tree?: (arg option {
        doc: "Use some work-tree"
        type: string
        default: "."
        long: work-tree
        join: "="
      })
      message: (arg {
        doc: "Commit message"
        type: string
      })
      rest: (arg --rest {doc: "Extra args"})
    } {
      # ...
    }

    This could open-up the ability to share a set of args between multiple functions, without having to re-write it, maintain duplicated definitions/documentations/completion/...
    => more composable

    WDYT?


    Well this blew up, if you're not allergic to these kind of ideas I'll probably make a separate issue/RFC with this... (or multiple?)

  21. amtoine commented on Nov 30, 2023

    @amtoine
    Member

    @bew
    i just tried and the following already works without the spread operator 😋

    let global_opts = [--no-pager]
    let rest = [--graph --oneline --decorate]
    
    git $global_opts log $rest
  22. bew commented on Dec 3, 2023

    @bew

    the following already works without the spread operator 😋

    let global_opts = [--no-pager]
    let rest = [--graph --oneline --decorate]
    
    git $global_opts log $rest

    Well that would be a solution for the first part 🤔
    Why does it work? Does the parser detects if the target command is an external one?

    Although to me this is not something that should happen automagically.

    From a readability point of view it doesn't feel right, because the implicit spread is not predictable, unless you know that the command you're passing this into is an external command.
    Having to explicitly spread the args would be more predictable and easy to read and understand.

  23. amtoine commented on Dec 3, 2023

    @amtoine
    Member

    @bew
    yup, i think the parser detects that!

    we are currently adding a spread operator to Nushell, see #11006 and #11144, and we might reconsider the automatic spreading for externals at some point 👍

  24. bew commented on Dec 3, 2023

    @bew

    Allright 👌
    What about the rest of my brain dump, do you have thoughts on this kind of mini-framework to define and manipulate args in a structured way? 🤔

  25. amtoine commented on Dec 3, 2023

    @amtoine
    Member

    Allright 👌 What about the rest of my brain dump, do you have thoughts on this kind of mini-framework to define and manipulate args in a structured way? 🤔

    not sure i see what you mean 😕

    ohh, the big post of yours above?! let me have another look 😉

  26. amtoine commented on Dec 3, 2023

    @amtoine
    Member

    @bew
    interesting idea but i'm not sure what hole in the current arg syntax these new types would fill 😕
    i must have missed it but it looks to me like all the more complex examples using arg flag can already be done natively?

  27. kubouch commented on Nov 26, 2024

    @kubouch
    ContributorAuthor

    Because the () syntax looks too much like a subexpression, I think adding this would add too much confusion. The “flag-passing” problem is largely solved by allowing flags to take boolean parameters, like --flag=$value.

    Let's try not to have two ways to do the same thing, I think we can close it for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A:parserA:syntaxcategory:enhancementcategory:meta-issuestatus:needs-core-team-attentionstatus:needs-design

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions