-
Notifications
You must be signed in to change notification settings - Fork 123
feat: implicit argument derivation #5966
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
base: master
Are you sure you want to change the base?
Changes from all commits
7d14732
13fddcf
d33207c
5689c5f
e86c6bb
065b517
59987b8
9b961a3
eb151d2
76f82af
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,25 +3,25 @@ | |
| ## Overview | ||
|
|
||
| Implicit parameters allow you to omit frequently-used function arguments at call sites when the compiler can infer them from context. This feature is particularly useful when working with ordered collections like `Map` and `Set` from the `core` library, which require comparison functions but where the comparison logic is usually obvious from the key type. | ||
| Other exampes are `equal` and `toText` functions. | ||
| Other examples are `equal` and `toText` functions. | ||
|
|
||
| ## Basic usage | ||
|
|
||
| ### Declaring implicit parameters | ||
|
|
||
| When declaring a function, any function parameter can be declared implicit using the `implicit` type constructor: | ||
|
|
||
| For example, the core Map library, declares a function: | ||
| For example, the core `Map` library declares a function: | ||
|
|
||
| ```motoko no-repl | ||
| public func add<K, V>(self: Map<K, V>, compare : (implicit : (K, K) -> Order), key : K, value : V) { | ||
| // ... | ||
| } | ||
| ``` | ||
|
|
||
| The `implicit` marker on the type of parameter `compare` indicates the call-site can omit it the `compare` argument, provided it can be inferred the call site. | ||
| The `implicit` marker on the type of parameter `compare` indicates the call-site can omit the `compare` argument, provided it can be inferred at the call site. | ||
|
|
||
| A function can declare more than on implicit parameter, even of the same name. | ||
| A function can declare more than one implicit parameter, even of the same name. | ||
|
|
||
|
|
||
| ```motoko | ||
|
|
@@ -55,7 +55,7 @@ Map.add(map, 5, "five"); | |
| ``` | ||
| The compiler automatically finds an appropriate comparison function based on the type of the key argument. | ||
|
|
||
| The availabe candidates are: | ||
| The available candidates are: | ||
| * Any value named `compare` whose type matches the parameter type. | ||
|
|
||
| If there is no such value, | ||
|
|
@@ -66,7 +66,7 @@ An ambiguous call can always be disambiguated by supplying the explicit argument | |
|
|
||
| ### Contextual dot notation | ||
|
|
||
| Implicit parameters dovetail nicely with the [contextual dot notation](contextual-dot). | ||
| Implicit parameters dovetail nicely with [contextual dot notation](10-contextual-dot.md). | ||
| The dot notation and implicit arguments can be used in conjunction to shorten code. | ||
|
|
||
| For example, since the first parameter of `Map.add` is called `self`, we can both use `map` as the receiver of `add` "method" calls | ||
|
|
@@ -81,7 +81,7 @@ let map = Map.empty<Nat, Text>(); | |
| // Using contextual dot notation, without implicits - must provide compare function explicitly | ||
| map.add(Nat.compare, 5, "five"); | ||
|
|
||
| // Using contextual dot nation together with implicits - compare function inferred from key type | ||
| // Using contextual dot notation together with implicits - compare function inferred from key type | ||
| map.add(5, "five"); | ||
| ``` | ||
|
|
||
|
|
@@ -147,7 +147,7 @@ let scores = Map.empty<Text, Nat>(); | |
| // Add player scores | ||
| scores.add("Alice", 100); | ||
| scores.add("Bob", 85); | ||
| scores.add( "Charlie", 92); | ||
| scores.add("Charlie", 92); | ||
|
|
||
| // Update a score | ||
| scores.add("Bob", 95); | ||
|
|
@@ -158,7 +158,7 @@ if (scores.containsKey("Alice")) { | |
| }; | ||
|
|
||
| // Get size | ||
| let playerCount = scores.size() | ||
| let playerCount = scores.size(); | ||
| ``` | ||
|
|
||
| ## How inference works | ||
|
|
@@ -167,13 +167,57 @@ The compiler infers an implicit argument by: | |
|
|
||
| 1. Examining the types of the explicit arguments provided. | ||
| 2. Looking for all candidate values for the implicit argument in the current scope that match the required type and name. | ||
| 3. From these, selecting the best unique candidate based on type specifity. | ||
| 3. From these, selecting the best unique candidate based on type specificity. | ||
|
|
||
| If there is no unique best candidate the compiler rejects the call as ambiguous. | ||
|
|
||
| If a callee takes several implicits parameter, either all implicit arguments must be omitted, or all explicit and implicit arguments must be provided at the call site, | ||
| If a callee takes several implicit parameters, either all implicit arguments must be omitted, or all explicit and implicit arguments must be provided at the call site, | ||
| in their declared order. | ||
|
|
||
| ### Resolution order | ||
|
|
||
| The compiler searches for implicit arguments in the following order, stopping at the first tier that produces a unique match: | ||
|
|
||
| 1. **Direct** — values whose type directly matches: | ||
| 1. Local values in the current scope. | ||
| 2. Module fields of modules in scope (e.g., `Nat.compare`). | ||
| 3. Fields of unimported modules (requires `--implicit-package`). | ||
| 2. **Derived** — functions with implicit parameters that, after stripping their own implicits and instantiating type parameters, match the required type (see [Implicit derivation](#implicit-derivation) below): | ||
| 1. Local values in the current scope. | ||
| 2. Module fields (e.g., `Array.compare<T>`). | ||
| 3. Fields of unimported modules (requires `--implicit-package`). | ||
| Within each tier, if multiple candidates match, the compiler picks the most specific one (by subtyping). If no unique best candidate exists, the call is rejected as ambiguous. | ||
|
|
||
| This ordering guarantees that direct matches are always preferred over derived ones, and local definitions take precedence over imported or unimported module definitions. | ||
|
|
||
| ### Implicit derivation | ||
|
|
||
| When no direct match exists, the compiler can **derive** an implicit argument from a function that itself has implicit parameters. This eliminates the need for boilerplate wrapper functions. The candidate function can be polymorphic (the compiler infers the type instantiation) or monomorphic. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think anything here clearly states that the hole must have a (monomorphic) function type although perhaps its implied by saying that stripping the implicit arguments from the candidate produces a matching type. I now realize that's probably why my example in #6054 fails.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've explored this extension in #5991 (see comments there) btw, if you want to allow context-dot syntax like func toCandid<A>(self : A, toCandidImpl : (implicit : A -> Blob)) : Blob {
toCandidImpl(self)
} |
||
|
|
||
| For example, suppose `Array.compare` is declared as: | ||
|
|
||
| ```motoko no-repl | ||
| public func compare<T>(a : [T], b : [T], compare : (implicit : (T, T) -> Order)) : Order | ||
| ``` | ||
|
|
||
| and a function requires an implicit `compare : ([Nat], [Nat]) -> Order`. Without derivation, you would need to write a wrapper: | ||
|
|
||
| ```motoko no-repl | ||
| module MyArray { | ||
| public func compare(a : [Nat], b : [Nat]) : Order { | ||
| Array.compare(a, b) // resolves inner `compare` to Nat.compare | ||
| }; | ||
| }; | ||
| ``` | ||
|
|
||
| With derivation, the compiler handles this automatically. It recognizes that `Array.compare<Nat>`, after removing its implicit `compare` parameter and instantiating `T := Nat`, has the right type. It then recursively resolves the inner implicit (`Nat.compare`) and synthesizes the wrapper for you. | ||
|
|
||
| This works transitively: a `compare` for `[[Nat]]` is derived via `Array.compare<[Nat]>`, which needs `[Nat]` compare, which is derived via `Array.compare<Nat>`, which needs `Nat.compare` — all resolved automatically. | ||
|
|
||
| The resolution depth is bounded to guarantee termination. If you encounter a depth limit, you can increase it with `--implicit-derivation-depth` or provide the argument explicitly. | ||
|
|
||
| When derivation is attempted but fails (for example, because an inner implicit can't be resolved), the compiler reports which inner implicits were missing and, when applicable, a hint about which module to import. | ||
|
|
||
| ### Supported types | ||
|
|
||
| The core library provides comparison functions for common types: | ||
|
|
@@ -275,7 +319,9 @@ There is no need to update existing code unless you want to take advantage of th | |
|
|
||
| ## Performance considerations | ||
|
|
||
| Implicit arguments have no runtime overhead. The comparison function is resolved at compile time, so there is no performance difference between using implicit and explicit arguments. The resulting code is identical. | ||
| Implicit arguments are resolved at compile time. | ||
| - For direct matches, the resulting code is identical to explicitly passing the argument. | ||
| - For derived implicits, the compiler synthesizes a wrapper function at each call site. This creates a small overhead per call site, which could be mitigated by caching in the future. For now, if this becomes a performance issue, consider defining the function explicitly so all call sites share a single definition. | ||
|
|
||
| ## See also | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -88,6 +88,7 @@ let experimental_stable_memory_default = 0 (* _ < 0: error; _ = 0: warn, _ > 0: | |
| let experimental_stable_memory = ref experimental_stable_memory_default | ||
| let typechecker_combine_srcs = ref false (* useful for the language server *) | ||
| let blob_import_placeholders = ref false (* when enabled, blob:file imports resolve as empty blobs *) | ||
| let implicit_derivation_depth = ref 100 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I guess this will affect all imported code too. Maybe that's ok but seems fragile.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yes, but we don't have flags per file/package and we need some default cap |
||
| let generate_view_queries = ref false | ||
|
|
||
| let default_warning_levels = M.empty | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.