Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .sources/VERSIONS
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ chain-fusion-signer v0.3.0
papi v0.1.1 168bc9d
ic-pub-key v1.0.1 f89fa55
icp-cli v0.2.3 caeac37
motoko v1.7.0 1e65e26
motoko v1.8.0 75c4123
motoko-core v2.4.0 cd37dbf
cdk-rs ic-cdk v0.20.1 / ic-cdk-timers v1.0.0 / ic-cdk-executor v2.0.0 317f55c
candid 2025-12-18 # candid v0.10.20, didc v0.5.4 2e4a2cf
Expand Down
2 changes: 1 addition & 1 deletion .sources/motoko
Submodule motoko updated 288 files
2 changes: 1 addition & 1 deletion docs/languages/motoko/fundamentals/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ type Result<Ok, Err> = { #ok : Ok; #err : Err }
Unlike option types, the Result type includes a second type parameter `Err` which allows you to specify exactly what kind of error occurred. This makes error handling more informative and flexible.

```motoko

public type TodoError = { #notFound; #alreadyDone : Time };
```

The previous example can be revised to use `Result` types:
Expand Down
70 changes: 58 additions & 12 deletions docs/languages/motoko/fundamentals/implicit-parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,25 @@ description: "Motoko language documentation"
## 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
Expand Down Expand Up @@ -58,7 +58,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,
Expand All @@ -69,7 +69,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
Expand All @@ -84,7 +84,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");
```

Expand Down Expand Up @@ -150,7 +150,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);
Expand All @@ -161,7 +161,7 @@ if (scores.containsKey("Alice")) {
};

// Get size
let playerCount = scores.size()
let playerCount = scores.size();
```

## How inference works
Expand All @@ -170,13 +170,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.

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:
Expand Down Expand Up @@ -278,7 +322,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

Expand Down
3 changes: 2 additions & 1 deletion docs/languages/motoko/fundamentals/pattern-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Motoko supports several types of patterns:
| Named | Introduces identifiers into a new scope. | `age`, `x` |
| Tuple | Must have at least two components. | `( component0, component1, …​ )` |
| Alternative (`or`-pattern) | Match multiple patterns. | `0 or 1` |
| Conjunctive (`and`-pattern) | Match both patterns; bindings combine. | `?x and s` |

## Concepts

Expand All @@ -29,7 +30,7 @@ Unlike traditional `enum` types in other languages, which define fixed sets of v

### Irrefutable and refutable patterns

Patterns are either refutable** or irrefutable. A refutable pattern can fail to match (like literal patterns or specific variant tags). An irrefutable pattern always matches any value of its type. Examples include the wildcard `_`, simple variable names, or structured patterns (like records or tuples) made only from irrefutable parts.
Patterns are either **refutable** or **irrefutable**. A refutable pattern can fail to match (like literal patterns or specific variant tags). An irrefutable pattern always matches any value of its type. Examples include the wildcard `_`, simple variable names, or structured patterns (like records or tuples) made only from irrefutable parts.

### Singleton types

Expand Down
10 changes: 10 additions & 0 deletions docs/languages/motoko/reference/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ $(dfx cache show)/moc --version

# Motoko compiler changelog

## 1.8.0 (2026-05-15)

* motoko (`moc`)

* feat: Implicit argument derivation — the compiler can derive implicit arguments from functions that themselves have implicit parameters (e.g., `compare` for `[Nat]` from `Array.compare<Nat>` + `Nat.compare`). Works transitively and is depth-limited via `--implicit-derivation-depth` (#5966).

* feat: `and`-patterns — `p1 and p2` matches when both legs match, binding from both (#6049).

* bugfix: M0236 dot-notation auto-fix on unparenthesized single-argument calls (e.g. `List.reverse b`) no longer rewrites them into a bare function reference (`b.reverse`), which silently turned a call into a no-op; the suggestion now produces `b.reverse()` (#6096).

## 1.7.0 (2026-04-29)

* motoko (`moc`)
Expand Down
1 change: 1 addition & 0 deletions docs/languages/motoko/reference/motoko-grammar.md
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ This section describes the concrete syntax, or grammar, of Motoko. The specifica
<pat_bin> ::=
<pat_un>
<pat_bin> 'or' <pat_bin>
<pat_bin> 'and' <pat_bin>
<pat_bin> ':' <typ>

<pat> ::=
Expand Down
Loading