mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

mjdi Technical Investigation Report

Target compiler: Mojo 1.2.0 (2016d0cd), installed from PyPI (mojo==1.2.0,

Source: mjdi/docs/technical-investigation.md

Target compiler: Mojo 1.2.0 (2016d0cd), installed from PyPI (mojo==1.2.0, mojo-compiler==1.2.0, Modular Inc). Standard library: std 1.2.0 (source reviewed at tag mojo/v1.2.0 of github.com/modular/modular).

Every conclusion below is backed by a compiler-run experiment in experiments/ (all experiments in this repository compile and run with mojo run experiments/<file> unless the experiment documents a limitation).

Feature verification matrix

#FeatureStatusEvidence
1Trait with provided (default) method implementationsVerifiedexp1_traits.mojo
2Struct overriding a provided trait methodVerifiedexp1_traits.mojo
3@staticmethod on trait methods (required for self-free methods)Verifiedexp1_traits.mojo — a trait method without self must be @staticmethod, otherwise "self argument must be present"
4Trait method returning Self with default implVerified (constrained)exp1_traits.mojo — works when the trait inherits Defaultable; Self() requires Defaultable evidence
5Generic trait method ([R: Trait] parameter) with default impl calling through the genericVerifiedexp1_traits.mojo — instance and static forms both compile
6Trait-constrained generic static dispatch (R.has[T]() on generic type parameter)Verifiedexp3_registry.mojo
7Trait instance-method dispatch through a generic-typed field (self.rest.get_has[T]())Verifiedexp3_registry.mojo
8Recursive parameterized structs (type-level linked lists, e.g. Registry[H, Rest])Verifiedexp3_registry.mojo — the tail type must satisfy Defaultable & Movable & Deinitable and both ends declare conformance to the shared trait
9Comptime type equality (U == Self.T) inside generic static methodsVerifiedexp3_registry.mojo
10reflect[T] field enumeration (field_count, field_names, field_types)Verifiedexp2_reflection.mojo
11Detecting Inject[T] fields via reflect[FT].base_name() == "Inject"Verifiedexp2_reflection.mojo
12Generic-argument extraction reflect[FT].field_at[0].TVerified (limited)exp2_reflection.mojo — works when the first field's type is the parameter; for wrappers storing Optional[T] the chain descends through stdlib internals, so mjdi avoids it (see design note 1)
13reflect[T].field_ref[i] read/mutation of struct fieldsVerifiedexp2_reflection.mojo, exp4_construction.mojo
14Writing a concretely-typed value through a generic field refVerified (constrained)requires rebind[Concrete](field_ref(...)) on the destination ref; rebind[A, B](/docs/0.10.0/value) on the rvalue fails because the two-parameter overload expects the source type to be inferrable
15Comptime iteration in generic context (comptime for + comptime if)Verifiedexp2_reflection.mojo — a runtime if over a comptime condition instantiates both branches and crashes on non-struct field types; comptime if is mandatory
16comptime assert cond, "message" for compile-time diagnosticsVerifiedexp3_registry.mojo (duplicate registration)
17Tuple.concat runtime tuple concatenationVerifiedstdlib source tuple.mojo:485; used by construction experiments
18Splatting a Tuple into a variadic-typed calleeVerified (compiler-documented)Pair(*t) fails for fixed-arity callees; the compiler error documents the dispatcher/shim pattern
19Generic Tuple[*Ts] parameter from an unbound TypeList paramUnsupportedexp4_construction.mojo — "value passed to 'Ts' cannot be converted ... depends on an unresolved parameter" for Tuple[*Ts] and Tuple[*Ts.values]
20Extending a pack at a call site (f(*acc, v) / Tuple(a, *tail))Unsupported"concatenating unpacked positional arguments is not supported"
21Passing T.__init__ (generated fieldwise ctor) as a function-value parameterUnsupportedexp4_construction.mojo — "unexpected parameter"; constructors are not first-class function values
22field_ref on an uninitialized out parameterUnsupported"use of uninitialized value" — the stdlib builds tuples with mark_initialized + Pointer.unsafe_write instead, which mjdi rejects as unsafe memory manipulation (PRD rule)
23@property computed membersUnsupported"use of unknown declaration 'property'"
24fn keywordRemoved in 1.2.0 (use def)compiler error
25Direct trait-member access (Trait.method())Unsupported"Direct access of trait members is not supported" — always call through the concrete/generic type
26Enum as comptime struct parameterVerifiedprovider.mojo compiles with scope: ProviderScope parameters
27Function-value parameters (callee: def() raises -> T)Verifiedfactory providers invoke comptime-registered functions at runtime
28Fieldless structsVerified (constrained)fieldless structs have no synthesized zero-arg __init__; they need an explicit def __init__(out self): pass
29mut parameter annotationsUnsupported (non-self args)by-value parameters use var; mut is for self and locals
30Linear types (Deinitable where (False, msg), Movable where False)Verifiedexp7_annotations.mojo — a struct can opt out of both traits, carry the linear opt-outs alongside other trait conformances, and require an explicit destroy(deinit self)
31@__annotation(<comptime value>) struct decoratorVerifiedexp7_annotations.mojo — accepts a comptime value and coexists with trait conformance lists; the decorator is spelled @__annotation (singular) and is only supported on structs and struct fields
32Reading annotations back: reflect[T].annotations() (comptime tuple)Verifiedexp7_annotations.mojo — len(...) gives the arity and [i] indexes the elements. On a generic T the element is a compile-time-dependent value: __eq__, __str__, and StaticString conversion are all rejected, so mjdi recognizes the marker via conforms_to(type_of(ann), LinearAnnotation), which the compiler proves for dependent values
33Explicit destruction of a linear value (lease^.destroy() on a trait-required deinit self method)Verifiedexp7_annotations.mojo — in-place init, borrow reads, and transfer-into-destroy compile with no copy/move; the value is consumed exactly once

Design notes (deviations forced by the compiler)

  1. Inject stores Optional[T], not T. Two-phase construction needs the service to be default-constructible (T()), so every field — including Inject fields — needs a default. Storing the dependency directly would require T: Defaultable for every dependency, which conflicts with constructor-taking services like Database(url). An Optional-backed Inject is always defaultable. The dependency type is never extracted by unwrapping Optional/Variant internals (fragile); instead Inject conforms to an mjdi-owned marker trait whose static methods know the dependency type through Self.T (finding 6/7), so dependency discovery and validation are fully version-stable.

  2. Construction is two-phase. resolve_dependencies[T] default-constructs T and then writes each Inject field through reflect[T].field_ref[i] (finding 13/14). This is safe: every field is initialized by T() before the resolver overwrites it. Arbitrary-argument reflective construction (findings 19–22) is not expressible in safe Mojo 1.2.0.

  3. Registries are type-level linked lists (Registry[Head, Rest]), because comptime pack/tuple concatenation is not available (finding 20). Lookup, duplicate detection, and graph walks recurse through trait-polymorphic static methods (findings 6/7/8).

  4. Singleton instances are handed out as copies (provider type must be Copyable). Mojo's value semantics forbid handing out two references to the same owned instance safely; the container caches one canonical construction and each resolution returns a copy of it. Documented in docs/known-limitations.md.

  5. No @property (finding 23): the dependency accessor is spelled self.dep.value() rather than the PRD's conceptual self.dep.value.

Findings from the implementation phase (supplementary)

The following were discovered while building the library itself; each is exercised by the test suite or a compile-fail fixture.

#FeatureStatusEvidence / consequence
30comptime if conditions referencing the enclosing generic struct's Self (e.g. Self.provides[T]()) can mis-evaluateBrokenduplicate-registration checks were inert inside register methods; routed through free-function helpers with explicit chain parameters, and moved into the container-construction validation walk
31Type equality (comptime if U == Concrete) is unreliable in functions with more than one type parameterBrokenverified: the branch is skipped while reflect[U].name() reports the compared type; mjdi avoids type equality in all dispatch paths
32Evidence does not flow from equality branches; rebind_var[Dest](/docs/0.10.0/value) performs the conversion in return position, rebind_var[Optional[T]](Optional[U](v^)) in assignment positionVerifiedslot_fill/slot_copy/supply_as conversions
33Runtime trait-instance dispatch is reliable even where comptime dispatch is notVerifiedProviderContext.accepts_scoped is an instance method answered at runtime
34Recursive struct definitions (a struct whose field type eventually contains itself) are rejected by the compiler ("attempt to resolve a recursive reference")Compiler-levelstruct-level dependency cycles cannot be declared at all; the compiler is the detector
35Enums are declared with __enum/case (the enum keyword is gone), have no __eq__, and their parameters materialize via materialize[...]()Verifiedprovider_scope/provider_kind; discriminant comparisons
36Function-type parameters must use the thin convention (def() raises thin -> T) and are invoked via Self.factory()Verifiedfactory providers
37A trait method requirement re-declared in an inheriting trait is a "conflicting default implementations" errorVerifiedProviderChain inherits kind_of from ProviderQueryable instead of re-declaring it
38Passing a generic struct's Self as a generic argument from an instance method works for calls, but comptime assertions inside the callee that re-dispatch through that argument can still mis-evaluatePartially brokenvalidation therefore runs in the container-construction walk with concrete descriptor-side Self.T references
39mojo test does not exist in 1.2.0; tests are standalone programsVerifiedscripts/run_tests.sh drives unit, compile-fail, crash-expected, and example runs
40mojo package is deprecated in favor of mojo precompile ... -o pkg.mojocVerifiedbuild instructions

Consequences for the validation architecture

Because findings 30/31/38 make registration-time comptime checks inert in the comptime reg = Registry()... evaluation pattern, all structural validation runs at container construction (Container[registry].__init__ elaboration), which is verified to evaluate correctly and still fails before any application code executes. Registration-time guards remain as defense in depth; the authoritative checks live in dependency_graph.mojo and in the descriptor-side check_unique_against/validate_with implementations that reference their own concrete parameters.