Editions Ideas
jmh530
john.michael.hall at gmail.com
Thu Dec 18 15:20:03 UTC 2025
On Thursday, 18 December 2025 at 05:57:35 UTC, Walter Bright
wrote:
> On 12/16/2025 1:12 PM, jmh530 wrote:
>> The idea is that functions include "a pointer to the current
>> context as an implicit additional argument.". It looks to be
>> helpful with managing allocators.
>
> That sounds like member functions?
The implicit aspect of it is similar, but not exactly the same
since the context depends on the scope and can be overridden.
It's described in more detail here [1], which I reproduce below
and then it follows with a discussion of how it applies to
allocators [2] (which I'm going not going to include)
---
In each scope, there is an implicit value named context. This
context variable is local to each scope and is implicitly passed
by pointer to any procedure call in that scope (if the procedure
has the Odin calling convention).
The main purpose of the implicit context system is for the
ability to intercept third-party code and libraries and modify
their functionality. One such case is modifying how a library
allocates something or logs something. In C, this was usually
achieved with the library defining macros which could be
overridden so that the user could define what they wanted.
However, not many libraries supported this in many languages by
default which meant intercepting third-party code to see what it
does and to change how it does it was not possible.
```
main :: proc() {
c := context // copy the current scope's context
context.user_index = 456
{
context.allocator = my_custom_allocator()
context.user_index = 123
supertramp() // the `context` for this scope is implicitly
passed to `supertramp`
}
// `context` value is local to the scope it is in
assert(context.user_index == 456)
}
supertramp :: proc() {
c := context // this `context` is the same as the parent
procedure that it was called from
// From this example, context.user_index == 123
// A context.allocator is assigned to the return value of
`my_custom_allocator()`
// The memory management procedure uses the `context.allocator`
by default unless explicitly specified otherwise
ptr := new(int)
free(ptr)
}
```
By default, the context value has default values for its
parameters which is decided in the package runtime. These
defaults are compiler specific.
To see what the implicit context value contains, please see the
definition of the Context struct in package runtime.
[1] https://odin-lang.org/docs/overview/#implicit-context-system
[2] https://odin-lang.org/docs/overview/#allocators
More information about the Digitalmars-d
mailing list