Math Integer Foundations
Math integer foundations: Min, Max, Abs, Clamp, Sign, and their boundary semantics.
VOID Language roadmap
Array and collection expression foundations are complete. The next phase fills in the numeric and timing utilities ordinary programs depend on, with deterministic seeded randomness, portable entropy at a narrow native boundary, and elapsed-time measurement built on VOID's existing monotonic clock.
Current phase
This phase keeps common numeric helpers in ordinary library/runtime paths instead of creating special compiler behavior. It starts with integer and floating-point Math semantics, builds deterministic Random around explicit state and unbiased sampling, adds portable automatic seeding through a small entropy boundary, and reuses the monotonic clock for Stopwatch.
Math integer foundations: Min, Max, Abs, Clamp, Sign, and their boundary semantics.
Math and MathF floating-point functions: Sqrt, Pow, Sin, Cos, Atan2, and related operations.
Rounding, Floor, Ceiling, Truncate, and defined floating-point edge behavior.
Build the Random foundation around deterministic seeded behavior with explicit internal state.
Add unbiased random integer ranges and upper bounds with overflow-safe sampling.
Add random floating-point values and byte-buffer generation on the same explicit-state foundation.
Add portable automatic random seeding through a small native entropy boundary.
Add Stopwatch and elapsed-time measurement by reusing the existing monotonic clock.
Integrate and stabilize numeric, random, and timing behavior across their normal library, runtime, and platform boundaries.
Run the independent Work integration audit across the complete block and cumulative suite before locking the phase.
Completed foundations
Each completed phase keeps its full public history, but starts collapsed. Open only the section you want to inspect; the active phase above remains expanded.
int[] a = {1, 2, 3}; use contextual element typing and the existing conversion rules.int[] a = [1, 2, 3]; work as a general expression form rather than an array-only special case.[], element conversions, and overload resolution participate in ordinary target-typed semantic selection.[1, ..other, 5] preserve element order, conversion rules, and the target collection contract.Span<T> and ReadOnlySpan<T> through the existing contiguous-memory model.this in instance contexts while preserving overload resolution, inheritance, virtual dispatch, generics, lambdas, iterators, async methods, method groups, and static-context rules.using Alias = Target; resolves through the ordinary namespace/type system with accessibility, generics, qualification, tooling, ambiguity, and diagnostics.-std=c11 -Wall -Wextra -Wpedantic -Werror -O2 without hiding warnings through suppression.out variables: Add declarations such as out int age as ordinary locals integrated with overload resolution, generics, definite assignment, diagnostics, and tooling.out var inference: Infer inline out-variable types from resolved out parameters through the existing overload and generic-inference systems.out _ discards.Container<int>.Member.void built-in type a general route to source-owned StandardLibrary static members without per-member compiler switches.Index.Start, Index.End, Range.All, and readonly-struct static-property behavior.Parse/TryParse contracts with shared format and overflow handling instead of primitive-specific lowering.EqualityComparer<T>.Default rather than hidden compiler branches.in-parameter mutation without speculative spelling fixes.Console.ReadLine() with newline and EOF handling.Console.Read() over the same input buffer so character and line reads compose without losing input.TextReader/TextWriter foundations and route Console.In, Out, Error, Write, and WriteLine through them.SetIn, SetOut, SetError, and redirected-stream state through ordinary library composition.Stream foundation and OpenStandardInput/Output/Error instead of Console-only transport types.ReadKey with echo/intercept behavior over narrow host-terminal primitives.Length, ByteLength, IsEmpty, and string.Empty while keeping null distinct from the empty string.Index & Enumeration: Make indexing, from-end positions, bounds checks, and allocation-free foreach (char ...) operate on Unicode scalar positions instead of raw UTF-8 bytes.Substring, returning ordinary immutable managed strings rather than introducing borrowed string views.+= with once-sized UTF-8 allocation, overflow checks, and embedded-NUL correctness.Insert, Remove, and Replace through the shared UTF-8/scalar machinery while preserving immutable string semantics.StringBuilder / Efficient Text Construction Foundation: Add reusable mutable construction storage whose result is always a normal managed string.const char * storage with GC-managed VcString * carrying an explicit byte length. Literals use their compiled length so embedded NUL survives. Existing NUL-terminated extern calls keep working temporarily through a call-scoped borrow bridge without defining the permanent native string ABI.string as the source-language type while native declarations carry metadata describing its ABI representation: borrowed NUL-terminated, pointer + length, borrowed/static return, owned return, or retained lifetime. Invalid combinations are diagnosed through VOID's existing native/attribute machinery.string without exposing the internal VcString layout as the C ABI. Marshal inbound text into managed strings and outbound text into stable ABI representations with explicit lifetime and ownership rules.string == const char * or inventing a second ordinary text type.Task.Delay yet. The timer service should be shared by every later feature in this block.Task.Delay Foundation: Add Task.Delay(int millisecondsDelay). Zero completes immediately, finite delays use the shared timer queue, and Timeout.Infinite represents a Task that does not complete by time. Invalid values below -1 fail deterministically. Absolutely no Thread.Sleep, worker blocking, or thread-per-delay implementation.Task.Delay Cancellation & Race Completion: Add Task.Delay(int millisecondsDelay, CancellationToken cancellationToken). Pre-cancellation, cancellation while pending, timer-vs-cancel races, originating token propagation, registration cleanup, GC rooting, and exactly-one terminal transition. A losing timer/cancellation callback must become harmless.CancellationTokenSource Disposal & Registration Lifetime Completion: Make CancellationTokenSource properly disposable and give it deterministic ownership of external registrations/timer registrations. This is an architectural prerequisite for linked sources and delayed cancellation so they do not leave parent registrations or timer state rooted forever. Existing cancellation semantics stay intact.CancellationTokenSource.CancelAfter Completion: Add delayed cancellation using the same timer queue: source.CancelAfter(millisecondsDelay); Support finite delay, zero, Timeout.Infinite disabling, repeated deadline replacement, ordinary Cancel() racing with the timer, disposal, forced GC, and concurrent reset/cancel races. Do not implement this as Task.Delay(...).ContinueWith(...).CancellationTokenSource Completion: Add linked-token composition, one/two-token and/or params forms as fits VOID's existing API conventions. Parent cancellation should cancel the linked source through ordinary cancellation registrations; no polling thread and no compiler support. Disposing the linked source must unregister from every parent deterministically.Task.WaitAsync Cancellation Completion: Add nonblocking Task.WaitAsync(CancellationToken token) and Task<T>.WaitAsync(CancellationToken token). Cancellation applies to waiting for the Task, not to the original Task itself. If the wait is canceled, the antecedent keeps running and may complete later. Result/fault/cancellation from the antecedent propagate normally when it wins. Use Task continuations + cancellation registrations, not a blocked worker.Task.WaitAsync Timeout & Combined Cancellation Completion: Add timeout forms, including the combined timeout/token form. A timeout should fault the proxy with a proper TimeoutException; cancellation should produce normal cancellation; antecedent completion should propagate its own state. Task-vs-timeout-vs-cancellation races must have exactly one winner and clean up both timer and token registration afterward. Again, the antecedent Task remains untouched if the wait times out or is canceled.Task.Delay, CancelAfter, linked sources and WaitAsync with async lambdas, ValueTask/custom awaiters, await using, WhenAll/WhenAny, async iterators, exceptions/finally, forced GC, ThreadPool contention, static-library/native boundaries, and timer/cancellation races. High-iteration race stress stays opt-in outside make test.make test.async () => ..., async x => ..., and block-bodied async lambdas. Target Task/Task<T>/ValueTask/ValueTask<T>-returning delegates and reuse the existing async return/await semantic rules. I would deliberately not add async void yet; completion/faults should remain observable unless we later design a proper fire-and-forget error policy.this, managed references, structs, generic values, nested lambdas, forced GC, and lambda/state-machine lifetime. This is important because an async lambda potentially has both a closure object and a suspension state machine.await using Syntax & Structural Async-Dispose Semantics: Add statement/declaration forms such as await using (...) and await using var .... Resolve DisposeAsync() structurally and run its result through the existing generalized awaiter binder, requiring GetResult(): void. The locked Task-returning IAsyncDisposable interface stays unchanged; Task, ValueTask, and custom valid awaitables should all work.await using State-Machine & Structured Cleanup Completion: Complete asynchronous disposal through normal exit, return, break, continue, faults, catch/finally, nested resources, mixed synchronous/async using, LIFO cleanup, disposal suspension, disposal faults, and managed-resource GC lifetime. No separate cleanup state machine.Task.Run Unwrapping: Add the missing composition primitives such as CompletedTask, FromResult<T>, faulted/canceled task construction, and proper Task.Run(Func<Task>) / Task.Run<T>(Func<Task<T>>) behavior. An async delegate passed to Task.Run must produce one Task, not Task<Task>, and unwrapping must be continuation-driven rather than blocking a worker with Wait().Task.WhenAll Completion: Add nonblocking Task and Task<T> aggregation, generic result arrays in original input order, empty-input behavior, GC rooting, cancellation/fault propagation, and races. I would fit this to VOID's existing singular Task exception model rather than bolt on a half-designed .NET AggregateException subsystem just for this milestone.Task.WhenAny Completion: Add race-safe first-completion composition for Task and Task<T>. The outer Task completes successfully with the winning Task regardless of whether that winner completed, faulted, or canceled. Cover simultaneous completion, GC, async lambdas, await using, ValueTask/custom awaits, and worker-thread races.await using, Task.Run unwrapping, WhenAll/WhenAny, exceptions, cancellation, async iterators, GC, threads, native/library boundaries, and diagnostics. This is the milestone where I run the mandatory complete cumulative make test.GetAwaiter(), IsCompleted, OnCompleted(Action), and GetResult(). No .NET interface dependency; VOID owns the contract. GetResult() determines whether the await expression is void or produces a value.OnCompleted, and GetResult() executed after resumption. This should extend the current async machinery, not create a second lowering pipeline.TaskAwaiter & Task Await De-Specialization: Add TaskAwaiter / TaskAwaiter<T> and Task.GetAwaiter(). Then move ordinary await Task onto the same generalized protocol as custom awaitables. After Task de-specialization, Task should no longer need a private compiler-only await path. I would also let the awaiter use Task's internal continuation registration directly instead of allocating an extra continuation Task.GetAwaiter. Ref-like values that cannot legally survive suspension must be diagnosed rather than boxed or silently copied somewhere unsafe.Task.Yield / Allocation-Free Yield Awaitable: Introduce a small YieldAwaitable/awaiter value type. IsCompleted is false, continuation registration queues through the existing ThreadPool, and GetResult() is empty. This gives VOID a real custom awaitable in its own standard library and proves generalized await works without manufacturing a Task object.ValueTask Foundation: Add non-generic ValueTask as a true value-type awaitable. A synchronously completed value should require no Task allocation; an incomplete/faulted/canceled asynchronous operation may use an existing Task as backing. Do not add pooling or an IValueTaskSource-style subsystem yet.ValueTask<T> Result & GC Completion: Add typed inline results plus Task-backed asynchronous results. Managed-reference T must remain correct across GC. Completion, faults, and cancellation must follow the same observable semantics as Task without turning ValueTask into a hidden managed object.ValueTask Return Integration: Allow async ValueTask and async ValueTask<T> methods. I would prioritize correctness and reuse the existing state-machine/completion machinery; I would not introduce clever pooling or a second async builder system just to advertise zero allocations. Completed/manual ValueTasks are already useful; deeper allocation optimization can come in a later performance block once the semantics are locked.try/catch/finally, library boundaries, nested Task/ValueTask awaits, and async iterators. Awaiter state and managed references must survive suspension correctly and cleanup must remain deterministic.YieldAwaitable, ValueTask/ValueTask<T>, async ValueTask methods, GC/lifetime, exceptions/cancellation, generated C, diagnostics, and the complete cumulative make test.NativeMemory Allocation Surface: Expose explicit unsafe allocation/free APIs through the standard library. Raw native allocations remain manually owned; no hidden GC ownership or fake safety.where T : unmanaged proof: checked count * sizeof(T), typed pointers, unmanaged structs, generic callers, zero-length behavior, and overflow diagnostics/runtime checks. No second unmanaged classifier.where T : unmanaged, pointers, stackalloc, native heap allocation, structs, arrays/tables, Span views, and native function-table patterns without special-case generic lowering.make test.where T : unmanaged with one authoritative recursive unmanaged-type classification. Primitive/native value types, enums, pointers, and structs composed entirely of unmanaged fields qualify; managed references and structs containing them do not. Integrate it with generic types, methods, inference, specialization, diagnostics, and existing constraint handling. I think this belongs first because otherwise later generic native-buffer APIs would need type-name hacks or compiler exceptions.unmanaged to use T*, pointer arithmetic where valid, sizeof(T), and stackalloc T[count]. Reuse the existing pointer/stackalloc implementation rather than building a generic-only path. This gives us a clean foundation for native Span<T> construction.fixed Statement & Scoped Pointer Semantics: Add fixed syntax and lowering through the existing scope/control-flow cleanup machinery. Pin acquisition/release must survive normal exit, return, break, continue, and exceptions. The fixed pointer is scoped and cannot be captured or returned as though its managed backing were permanently pinned. Existing explicitly unsafe raw-pointer behavior remains available; fixed becomes the correct lifetime-aware managed/native bridge.fixed structural rather than teaching the compiler a growing list of special types. A receiver exposing the proper pinnable-reference contract can participate, with receiver evaluation exactly once. This is the same architectural idea that worked well for the earlier Index/Range consumers and ref foreach.Span<T>, ReadOnlySpan<T>, Memory<T>, and ReadOnlyMemory<T> into that one pinning model. Writable sources expose writable pointers where legal; readonly views remain readonly. Range/slice-produced views must retain the correct owner and offset. GC, null/empty cases, nested slices, and evaluation-once behavior all get focused coverage.Span<T> / ReadOnlySpan<T> Construction: Add unsafe pointer+length construction for unmanaged storage. Once created, native-backed spans should use the same indexing, Range, slicing, ref foreach, CopyTo, Fill, and Clear machinery as managed/stack spans. No parallel “NativeSpan” type. Crucially, I would not make Memory<T> pointer-backed here: Memory<T> is heap-storable and therefore needs an ownership model for arbitrary native memory. Keeping Memory managed-array-backed remains the cleaner contract.fixed → pointer + length → existing unsafe extern calls, plus unmanaged Span views around externally owned buffers. Cover ref/out/in, callbacks, library output/import, generic unmanaged helpers, slices, and evaluation-once semantics. I would keep native APIs explicit as pointer+length here rather than inventing a magical direct Span ABI.make test, consistent with the existing harness policy.unmanaged constraints → generic stackalloc → pointers → fixed/pinning → arrays/Memory → Span/Range/ref → native calls/callbacks → GC/threads/exceptions. This gets the mandatory focused audit and full cumulative make test, exactly like the previous integration audit.ref T local aliases over locals, parameters, fields, and array elements. The compiler tracks lvalue provenance, definite assignment, and the managed owner that must stay rooted when a ref points inside an object or array.target = ref source, chained aliases, mutation through aliases, struct-field refs, readonly checks, and control-flow lifetime while reusing VOID's existing write-target and by-reference argument machinery.ref T method returns, return ref, and ref-returning calls as writable targets while rejecting references to dead locals, temporaries, and stack storage that cannot outlive the call.ref readonly & escape scopes: Add readonly references plus formal escape-scope analysis for stack storage, parameters, managed interior references, and longer-lived storage. Introduce an explicit scoped surface only if the language needs it to express those rules clearly.ref struct values that may contain byrefs without silently escaping into the managed heap. Fields, constructors, methods, properties, and ordinary stack locals follow the same lifetime model.await, and yield. Unsafe capture or suspension paths are rejected unless the compiler can prove the lifetime is valid.Span<T> & ReadOnlySpan<T>: Build spans as ordinary standard-library ref structs over the by-reference foundation, with length, indexed access, writable versus readonly behavior, and deliberate rules for native and managed element storage.stackalloc, valid unsafe pointer-backed views, slicing, managed-owner lifetime, and ref/ref readonly foreach so safe byrefs and the existing native-memory model meet cleanly.foreach bodies can suspend while preserving enumerator state and deterministic disposal across completion, early exit, faults, and cancellationIAsyncDisposable contract and explicit asynchronous disposal integrated with the existing async cleanup and finally control-flow modelIAsyncEnumerable<T> / IAsyncEnumerator<T> contracts and contextual await foreach semantics built on ordinary Tasksawait foreach consumer lowering preserves the enumerator across suspension and asynchronously disposes it on every structured exityield return and await through shared iterator/async state-machine machinery instead of a third independent lowering systemasync methods and await expressions with built-in Task / Task<T> awaitable semantics and focused diagnosticsasync Task<T>, typed await results, managed-result lifetime, and correct fault/cancellation propagation through the existing Task modelfinally, using, and structured cleanup preserved across suspension with deliberate diagnostics for invalid regions such as await inside lockCancellationToken and OperationCanceledException rules before and after suspensionTask completion state with synchronized pending, running, completed, faulted, and canceled outcomes plus exactly-once completionTask<T> typed results with managed-result rooting, fault storage, generic specialization, and shared Task state machineryTask.Run scheduling for delegates, closures, generic work, nested tasks, and worker-to-worker schedulingTaskCompletionSource completion, fault, and cancellation paths with managed lifetime supportThread.Sleep(int millisecondsTimeout) and a shared timeout contract including Timeout.InfiniteMonitor.Wait(object, int millisecondsTimeout) with timeout result and exact recursive monitor-depth restorationManualResetEvent and AutoResetEvent with indefinite/timed waits and race-safe signal behaviorSemaphore waits/releases on the existing managed synchronization foundationCancellationToken and CancellationTokenSource with thread-safe, idempotent cooperative cancellationOperationCanceledException outcomesMonitor.Wait intentionally remains cancellation-free while event/semaphore waits integrate cancellationtry/finally, using, closures/delegates/generics, native boundaries, and signal-vs-cancel/timeout racesforeach, enumerators, and yieldref/out/in, bindings, aliases, libraries, and callbackssizeof, memory copy/clear, and stackallocswitchconst/readonly, casts, is/asparamsdefault(T), typeof, type metadata, and conversionsdefaultvoidc checkin callsref/out/in capture and struct thisforeach, switch, nested control flow, and base-member accessreturn; with chaining/initializer and definite-assignment correctnessyieldref/out/in parameters through the existing C ABI"output": "library" static archives, [Export] symbols, reachability, static initialization, and VOID/C consumersvoid*, and ref/out/in pointer formsdo/while control flow across normal code, generics, lambdas, iterators, break/continue, and GC rootsadd/remove accessors across instance/static/interface/virtual formsnew[,]-style rectangular initializer inferencewhere constraints across class/struct/base/interface/multiple-interface/new() formsException hierarchy, messages, derived exceptions, and throw expression;finally on normal and exceptional completionreturn, break, and continue through one or more finally regionsthrow; rethrow, and exceptions raised from catch/finallyIDisposable foundation and deterministic compiler-generated iterator disposalforeach disposal on normal completion, early exit, and exceptionsusing (...) statements and scope-bound using declarationsnull patterns through the shared pattern matcherand, or, and not composition with binding/flow ruleswhen guards, deterministic first-match ordering, and focused invalid/unreachable diagnosticsyieldwhen-guard locals preserved across suspension with exact scopingfinally, and teardownforeach, using/disposal, exceptions, generics, and switch formsyieldVoid.Threading.Thread with new Thread(Action), Start(), and Join()Monitor.Enter / Monitor.Exitlock lowering with single evaluation and release through return/break/continue/exception cleanupThread.Join() after worker retirementparams, conditionals, and switch expressions routed through the shared conversion engineyield, GC, exceptions, finally, and disposalMonitor.Wait(object) with ownership checks, full recursive release, and exact recursion-depth reacquisitionMonitor.Pulse / PulseAll condition notification with correct ownership and waiter-vs-entry-waiter behaviorVoid.Threading.Interlocked integer increment/decrement/add/exchange/compare-exchange operations as real atomicsVoid.Threading.Volatile.Read / Write acquire/release access for supported primitive and managed-reference valuestry/finally, using, nested lock, native callbacks, GC, and thread shutdownBlock-wide invariant
Math, MathF, and deterministic seeded Random should behave as ordinary library/runtime surfaces with defined boundary rules rather than compiler-specific shortcuts.
Automatic random seeding should cross only a small portable entropy boundary, while Stopwatch should reuse the existing monotonic clock instead of introducing a second timing system.