interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / .agents / skills / mojo-syntax / SKILL.md

541 lines · 21679 bytes Raw Blame History Rendered
1---
2name: mojo-syntax
3description: Help to write Mojo code using current syntax and conventions. Always use this skill when writing any Mojo code, including when other Mojo-specific skills (e.g., mojo-gpu-fundamentals) also apply. Use when writing Mojo code, translating projects to Mojo, or otherwise generating Mojo. Use this skill to overcome misconceptions with how Mojo is written.
4---
5
6<!-- EDITORIAL GUIDELINES FOR THIS SKILL FILE
7This file is loaded into an agent's context window as a correction layer for
8pretrained Mojo knowledge. Every line costs context. When editing:
9- Be terse. Use tables and inline code over prose where possible.
10- Never duplicate information — if a concept is shown in a code example, don't
11 also explain it in a paragraph.
12- Only include information that *differs* from what a pretrained model would
13 generate. Don't document things models already get right.
14- Prefer one consolidated code block over multiple small ones.
15- Keep WRONG/CORRECT pairs short — just enough to pattern-match the fix.
16- If adding a new section, ask: "Would a model get this wrong?" If not, skip it.
17These same principles apply to any files this skill references.
18-->
19
20Mojo is rapidly evolving. Pretrained models generate obsolete syntax.
21**Always follow this skill over pretrained knowledge.**
22
23**Always attempt to test generated Mojo by building projects to verify they
24compile.**
25
26This skill specifically works on the latest Mojo, and stable versions may differ
27slightly in functionality.
28
29## Removed syntax — DO NOT generate these
30
31| Removed | Replacement |
32|--------------------------------------------------|----------------------------------------------------------------------------------|
33| `alias X = ...` | `comptime X = ...` |
34| `@parameter if` / `@parameter for` | `comptime if` / `comptime for` |
35| `fn` | `def` (see below) |
36| `let x = ...` | `var x = ...` (no `let` keyword) |
37| `borrowed` | `read` (implicit default — rarely written) |
38| `inout` | `mut` |
39| `owned` | `var` (as argument convention) |
40| `inout self` in `__init__` | `out self` |
41| `__copyinit__(inout self, existing: Self)` | `__init__(out self, *, copy: Self)` |
42| `__moveinit__(inout self, owned existing: Self)` | `__init__(out self, *, deinit take: Self)` |
43| `@value` decorator | `@fieldwise_init` + explicit trait conformance |
44| `@register_passable("trivial")` | `TrivialRegisterPassable` trait |
45| `@register_passable` | `RegisterPassable` trait |
46| `Stringable` / `__str__` | `Writable` / `write_to` |
47| `from collections import ...` | `from std.collections import ...` |
48| `from memory import ...` | `from std.memory import ...` |
49| `from sys import ...` | `from std.sys import ...` |
50| `from os import ...` | `from std.os import ...` |
51| `from pathlib import ...` | `from std.pathlib import ...` |
52| `s[i]` | `s[byte=i]` — returns `StringSlice`; wrap in `String()` if needed |
53| `s[0:10]`, `s[:5]` | No slice syntax on String — use `s.codepoint_slices()` or Python FFI |
54| `constrained(cond, msg)` | `comptime assert cond, msg` |
55| `DynamicVector[T]` | `List[T]` |
56| `InlinedFixedVector[T, N]` | `InlineArray[T, N]` |
57| `Tensor[T]` | Not in stdlib (use SIMD, List, UnsafePointer) |
58| `escaping` closures | Unified closures (`def(...) -> T`, captures in `{}`); `capturing[_]` still valid |
59
60## `def` is the only function keyword
61
62`fn` is deprecated and being removed. `def` does **not** imply `raises`.
63**Always** add `raises` explicitly when needed — omitting it is a warning today,
64error soon:
65
66```mojo
67def compute(x: Int) -> Int: # non-raising (compiler enforced)
68 return x * 2
69
70def load(path: String) raises -> String: # explicitly raising
71 return open(path).read()
72
73def main() raises: # main usually raises → def raises
74 ...
75```
76
77Note: existing stdlib code still uses `fn` during migration. New code should
78always use `def`.
79
80## `comptime` replaces `alias` and `@parameter`
81
82```mojo
83comptime N = 1024 # compile-time constant
84comptime MyType = Int # type alias
85comptime if condition: # compile-time branch
86 ...
87comptime for i in range(10): # compile-time loop
88 ...
89comptime assert N > 0, "N must be positive" # compile-time assertion
90```
91
92**`comptime assert` must be inside a function body** — not at module/struct
93scope. Place them in `main()`, `__init__`, or the function that depends on the
94invariant.
95
96Inside structs, `comptime` defines associated constants and type aliases:
97
98```mojo
99struct MyStruct:
100 comptime DefaultSize = 64
101 comptime ElementType = Float32
102```
103
104## Argument conventions
105
106Default is `read` (immutable borrow, never written explicitly). The others:
107
108```mojo
109def __init__(out self, var value: String): # out = uninitialized output; var = owned
110def modify(mut self): # mut = mutable reference
111def consume(deinit self): # deinit = consuming/destroying
112def view(ref self) -> ref[self] Self.T: # ref = reference with origin
113def view2[origin: Origin, //](ref[origin] self) -> ...: # ref[origin] = explicit origin
114```
115
116`ref`, `mut`, `out`, `deinit`, `read`, `var` are reserved and **cannot be used
117as identifiers** — neither as parameter names (`def cmp(got: T, ref: T)` →
118`"error: expected argument name"`) nor as local `var` names
119(`var ref = ...` → `"unexpected token in expression"`). Rename
120(`expected`, `reference`, etc.).
121
122## Lifecycle methods
123
124```mojo
125# Constructor
126def __init__(out self, x: Int):
127 self.x = x
128
129# Copy constructor (keyword-only `copy` arg)
130def __init__(out self, *, copy: Self):
131 self.data = copy.data
132
133# Move constructor (keyword-only `deinit take` arg)
134def __init__(out self, *, deinit take: Self):
135 self.data = take.data^
136
137# Destructor
138def __del__(deinit self):
139 self.ptr.free()
140```
141
142To copy: `var b = a.copy()` (provided by `Copyable` trait).
143
144## Struct patterns
145
146```mojo
147# @fieldwise_init generates __init__ from fields; traits in parentheses
148@fieldwise_init
149struct Point(Copyable, Movable, Writable):
150 var x: Float64
151 var y: Float64
152
153# Trait composition with &
154comptime KeyElement = Copyable & Hashable & Equatable
155struct Node[T: Copyable & Writable]:
156 var value: Self.T # Self-qualify struct parameters
157
158# Parametric struct — // separates inferred from explicit params
159struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]](
160 ImplicitlyCopyable, Sized,
161):
162 ...
163
164# @implicit on constructors allows implicit conversion
165@implicit
166def __init__(out self, value: Int):
167 self.data = value
168```
169
170The compiler synthesizes copy/move constructors when a struct conforms to
171`Copyable`/`Movable` and all fields support it.
172
173### Self-qualify struct parameters
174
175Inside a struct body, **always** use `Self.ParamName` — bare parameter names are
176errors:
177
178```mojo
179# WRONG — bare parameter access
180struct Container[T: Writable]:
181 var data: T # ERROR: use Self.T
182 def size(self) -> T: # ERROR: use Self.T
183
184# CORRECT — Self-qualified
185struct Container[T: Writable]:
186 var data: Self.T
187 def size(self) -> Self.T:
188 return self.data
189```
190
191This applies to all struct parameters (`T`, `N`, `mut`, `origin`, etc.)
192everywhere inside the struct: field types, method signatures, method bodies, and
193`comptime` declarations.
194
195### Explicit copy / transfer
196
197Types not conforming to `ImplicitlyCopyable` (e.g., `Dict`, `List`, and user
198structs that conform only to `Copyable, Movable`) require explicit `.copy()` or
199ownership transfer `^` — `return my_struct` errors until you transfer with `^`
200or add `ImplicitlyCopyable` conformance:
201
202```mojo
203# WRONG — implicit copy of non-ImplicitlyCopyable type
204var d = some_dict
205var result = MyStruct(headers=d) # ERROR
206
207# CORRECT — explicit copy or transfer
208var result = MyStruct(headers=d.copy()) # or: headers=d^
209```
210
211## Imports use `std.` prefix
212
213```mojo
214from std.testing import assert_equal, TestSuite
215from std.algorithm import vectorize
216from std.python import PythonObject
217import std.random
218```
219
220Prelude auto-imports (no import needed): `Int`, `String`, `Bool`, `List`,
221`Dict`, `Optional`, `SIMD`, `Float32`, `Float64`, `UInt8`, `Pointer`,
222`UnsafePointer`, `Span`, `Error`, `DType`, `Writable`, `Writer`, `Copyable`,
223`Movable`, `Equatable`, `Hashable`, `rebind`, `print`, `range`, `len`, and more.
224
225`rebind[TargetType](value)` reinterprets a value as a different type with the
226same in-memory representation. Useful when compile-time type expressions are
227semantically equal but syntactically distinct (e.g., TileTensor element types
228— see GPU skill).
229
230`std` is reserved as a module-level identifier — you cannot `def std`,
231`import X as std`, or `from X import std`. Struct methods named `std` are fine.
232
233Inside a multi-module package, `pkg.X.Y(...)` from a submodule needs explicit
234`import pkg`; `import pkg.X as X` binds only `X`, not `pkg`.
235
236## `Writable` / `Writer` (replaces `Stringable`)
237
238```mojo
239struct MyType(Writable):
240 var x: Int
241
242 def write_to(self, mut writer: Some[Writer]): # for print() / String()
243 writer.write("MyType(", self.x, ")")
244
245 def write_repr_to(self, mut writer: Some[Writer]): # for repr()
246 t"MyType(x={self.x})".write_to(writer) # t-strings for interpolation
247```
248
249- `Some[Writer]` — builtin existential type (not `Writer` directly)
250- Both methods have **default implementations** via reflection if all fields are
251 `Writable` — simple structs need not implement them
252- Convert to `String` with `String.write(value)`, not `str(value)`
253
254## Iterator protocol
255
256Iterators use `raises StopIteration` (not `Optional`):
257
258```mojo
259struct MyCollection(Iterable):
260 comptime IteratorType[
261 iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]
262 ]: Iterator = MyIter[origin=iterable_origin]
263
264 def __iter__(ref self) -> Self.IteratorType[origin_of(self)]: ...
265
266# Iterator must define:
267# comptime Element: Movable
268# def __next__(mut self) raises StopIteration -> Self.Element
269```
270
271For-in: `for item in col:` (immutable) / `for ref item in col:` (mutable).
272
273## Memory and pointer types
274
275| Type | Use |
276|---------------------------------|------------------------------------------------------------------------|
277| `Pointer[T, mut=M, origin=O]` | Safe, non-nullable. Deref with `p[]`. |
278| `alloc[T](n)` / `UnsafePointer` | Free function `alloc[T](count)` → `UnsafePointer`. `.free()` required. |
279| `Span(list)` | Non-owning contiguous view. |
280| `OwnedPointer[T]` | Unique ownership (like Rust `Box`). |
281| `ArcPointer[T]` | Reference-counted shared ownership. |
282
283`UnsafePointer` has an `origin` parameter that must be specified for struct
284fields. Use `MutExternalOrigin` for owned heap data (this is what stdlib
285`ArcPointer` uses):
286
287```mojo
288# Struct field — specify origin explicitly
289var _ptr: UnsafePointer[Self.T, MutExternalOrigin]
290
291# Allocate with alloc[]
292def __init__(out self, size: Int):
293 self._ptr = alloc[Self.T](size)
294```
295
296`UnsafePointer` is **non-null by design** — null default constructor and
297`__bool__` are deprecated. For nullable storage, use
298`Optional[UnsafePointer[...]]` (same layout; `None` is the null niche).
299
300## Origin system (not "lifetime")
301
302Mojo tracks reference provenance with **origins**, not "lifetimes":
303
304```mojo
305struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]: ...
306```
307
308Key types: `Origin`, `MutOrigin`, `ImmutOrigin`, `MutAnyOrigin`,
309`ImmutAnyOrigin`, `MutExternalOrigin`, `ImmutExternalOrigin`,
310`StaticConstantOrigin`. Use `origin_of(value)` to get a value's origin.
311
312## Testing
313
314```mojo
315from std.testing import assert_equal, assert_true, assert_false, assert_raises, TestSuite
316
317def test_my_feature() raises:
318 assert_equal(compute(2), 4)
319 with assert_raises():
320 dangerous_operation()
321
322def main() raises:
323 TestSuite.discover_tests[__functions_in_module()]().run()
324```
325
326The `mojo test` CLI subcommand was removed — run test files with `mojo run`
327against a `TestSuite.discover_tests` runner like the one above.
328
329## Dict iteration
330
331Dict entries are iterated directly — no `[]` deref:
332
333```mojo
334for entry in my_dict.items():
335 print(entry.key, entry.value) # direct field access, NOT entry[].key
336
337for key in my_dict:
338 print(key, my_dict[key])
339```
340
341## Collection literals
342
343`List` has **no variadic positional constructor**. Use bracket literal syntax:
344
345```mojo
346# WRONG — no List[T](elem1, elem2, ...) constructor
347var nums = List[Int](1, 2, 3)
348
349# CORRECT — bracket literals
350var nums = [1, 2, 3] # List[Int]
351var nums: List[Float32] = [1.0, 2.0, 3.0] # explicit element type
352var scores = {"alice": 95, "bob": 87} # Dict[String, Int]
353```
354
355`List[T]` rejects negative indices at compile time — use `lst[len(lst) - 1]`,
356not `lst[-1]`. (Library types may still support it.)
357
358## Variant access
359
360`Variant[A, B]` is `ImplicitlyCopyable` only if *all* arms are. With a
361non-copyable arm, indexing the variant copies it — use the typed-arm subscript:
362
363```mojo
364# WRONG — `values[i]` implicitly copies the Variant
365var x = values[i].take[T]() # ERROR: cannot implicitly copy
366
367# CORRECT — `values[i][T]` returns a ref to the inner value
368var x = values[i][T].copy() # or `^` to transfer
369```
370
371## Common decorators
372
373| Decorator | Purpose |
374|------------------------------------------------|---------------------------------------|
375| `@fieldwise_init` | Generate fieldwise constructor |
376| `@implicit` | Allow implicit conversion |
377| `@always_inline` / `@always_inline("nodebug")` | Force inline |
378| `@no_inline` | Prevent inline |
379| `@staticmethod` | Static method |
380| `@deprecated("msg")` | Deprecation warning |
381| `@doc_hidden` | Hide from docs |
382| `@explicit_destroy` | Linear type (no implicit destruction) |
383
384## Numeric conversions — must be explicit
385
386No implicit conversions between numeric *variables*. Use explicit constructors:
387
388```mojo
389var x = Float32(my_int) * scale # CORRECT: Int → Float32
390var y = Int(my_uint) # CORRECT: UInt → Int
391```
392
393**Literals are polymorphic** — `FloatLiteral` and `IntLiteral` auto-adapt to
394context:
395
396```mojo
397var a: Float32 = 0.5 # literal becomes Float32
398var b = Float32(x) * 0.003921 # literal adapts — no wrapping needed
399var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0) # literals adapt
400```
401
402## SIMD operations
403
404```mojo
405# Construction and lane access
406var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)
407v[0] # read lane → Scalar[DType.float32]
408v[0] = 5.0 # write lane
409
410# Type cast
411v.cast[DType.uint32]() # element-wise → SIMD[DType.uint32, 4]
412
413# Clamp (method)
414v.clamp(0.0, 1.0) # element-wise clamp to [lower, upper]
415
416# min/max are FREE FUNCTIONS, not methods
417from std.math import min, max
418min(a, b) # element-wise min (same-type SIMD args)
419max(a, b) # element-wise max
420
421# Element-wise ternary via bool SIMD
422var mask = (v > 0.0) # SIMD[DType.bool, 4]
423mask.select(true_case, false_case) # picks per-lane
424
425# Reductions
426v.reduce_add() # horizontal sum → Scalar
427v.reduce_max() # horizontal max → Scalar
428v.reduce_min() # horizontal min → Scalar
429```
430
431## Strings
432
433**All explicit stdlib imports require the `std.` prefix.** The
434removed-syntax table shows the most common corrections, but the rule
435is universal. Prelude types (`Int`, `String`, `List`, etc.) are
436auto-imported and need no import statement.
437
438`len(s)` returns **byte length**, not codepoint count. Mojo strings are UTF-8.
439Byte indexing requires keyword syntax: `s[byte=idx]` (not `s[idx]`). `len(s)` is
440deprecated on `String` — use `s.byte_length()` or `s.count_codepoints()`.
441
442`split`, `removeprefix`, `removesuffix` return `StringSlice` (or
443`List[StringSlice]`) viewing the source — wrap with `String(...)` to
444materialize an owned `String`.
445
446### String indexing (common error)
447
448```mojo
449# WRONG — compile error
450var ch = s[0]
451var sub = s[0:10]
452
453# CORRECT — byte-level access
454var ch = s[byte=0] # returns StringSlice
455var ch_str = String(s[byte=0]) # if you need a String
456
457# CORRECT — iterate codepoints for truncation
458var result = String("")
459var count = 0
460for cp in s.codepoint_slices():
461 if count >= 10:
462 break
463 result += String(cp)
464 count += 1
465```
466
467```mojo
468var s = "Hello"
469len(s) # 5 (bytes)
470s.byte_length() # 5 (same as len)
471s.count_codepoints() # 5 (codepoint count — differs for non-ASCII)
472
473# Iteration — `for c in s:` is deprecated; use codepoint_slices()
474for cp_slice in s.codepoint_slices():
475 print(cp_slice)
476
477# Codepoint values
478for cp in s.codepoints():
479 print(Int(cp)) # Codepoint is a Unicode scalar value type
480
481# StaticString = StringSlice with static origin (zero-allocation)
482comptime GREETING: StaticString = "Hello, World"
483
484# t-strings for interpolation (lazy, type-safe)
485var msg = t"x={x}, y={y}"
486
487# String.format() for runtime formatting
488var s = "Hello, {}!".format("world")
489```
490
491## Error handling
492
493`raises` can specify a type. `try`/`except` works like Python:
494
495```mojo
496def might_fail() raises -> Int: # raises Error (default)
497 raise Error("something went wrong")
498
499def parse(s: String) raises Int -> Int: # raises specific type
500 raise 42
501
502try:
503 var x = parse("bad")
504except err: # err is Int
505 print("error code:", err)
506```
507
508No `match` statement. No `async`/`await` — use `Coroutine`/`Task` from
509`std.runtime`.
510
511## Function types and closures
512
513No lambda. Closures use bare `def` with a capture list in `{}` after the arg
514list. `escaping` is removed; `capturing[_]` is still valid on parametric
515closure-type params:
516
517```mojo
518comptime MyFn = def(Int) -> None # unified value type
519def runner[f: def(Int) capturing[_] -> None](): ... # parametric form
520
521def closure(i: Int) {mut count, read ptr, var x}: # captures: mut/read/var
522 count += ptr[i] + x^ # `^` at use site, not in `{}`
523
524vectorize[simd_width](size, closure) # runtime-arg overload
525```
526
527`read` is default. `var x` is owned — transfer with `x^` at the use site.
528`@parameter` on a nested closure is only needed when consumed as a
529*comptime* parameter (`f[my_closure]`); runtime-arg overloads use bare form.
530
531## Type hierarchy
532
533```text
534AnyType
535 ImplicitlyDestructible — auto __del__; most types
536 Movable — __init__(out self, *, deinit take: Self)
537 Copyable — __init__(out self, *, copy: Self)
538 ImplicitlyCopyable(Copyable, ImplicitlyDestructible)
539 RegisterPassable(Movable)
540 TrivialRegisterPassable(ImplicitlyCopyable, ImplicitlyDestructible, Movable, RegisterPassable)
541```