Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/.agents/skills/mojo-syntax/SKILL.md # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / .agents / skills / mojo-syntax / SKILL.md` 541 lines · 21679 bytes Raw Blame History Rendered 1 --- 2 name: mojo-syntax 3 description: 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 19 20 Mojo 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 24 compile.** 25 26 This skill specifically works on the latest Mojo, and stable versions may differ 27 slightly 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, 64 error soon: 65 66 ```mojo 67 def compute(x: Int) -> Int: # non-raising (compiler enforced) 68 return x * 2 69 70 def load(path: String) raises -> String: # explicitly raising 71 return open(path).read() 72 73 def main() raises: # main usually raises → def raises 74 ... 75 ``` 76 77 Note: existing stdlib code still uses `fn` during migration. New code should 78 always use `def`. 79 80 ## `comptime` replaces `alias` and `@parameter` 81 82 ```mojo 83 comptime N = 1024 # compile-time constant 84 comptime MyType = Int # type alias 85 comptime if condition: # compile-time branch 86 ... 87 comptime for i in range(10): # compile-time loop 88 ... 89 comptime 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 93 scope. Place them in `main()`, `__init__`, or the function that depends on the 94 invariant. 95 96 Inside structs, `comptime` defines associated constants and type aliases: 97 98 ```mojo 99 struct MyStruct: 100 comptime DefaultSize = 64 101 comptime ElementType = Float32 102 ``` 103 104 ## Argument conventions 105 106 Default is `read` (immutable borrow, never written explicitly). The others: 107 108 ```mojo 109 def __init__(out self, var value: String): # out = uninitialized output; var = owned 110 def modify(mut self): # mut = mutable reference 111 def consume(deinit self): # deinit = consuming/destroying 112 def view(ref self) -> ref[self] Self.T: # ref = reference with origin 113 def 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 117 as 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 126 def __init__(out self, x: Int): 127 self.x = x 128 129 # Copy constructor (keyword-only `copy` arg) 130 def __init__(out self, *, copy: Self): 131 self.data = copy.data 132 133 # Move constructor (keyword-only `deinit take` arg) 134 def __init__(out self, *, deinit take: Self): 135 self.data = take.data^ 136 137 # Destructor 138 def __del__(deinit self): 139 self.ptr.free() 140 ``` 141 142 To 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 149 struct Point(Copyable, Movable, Writable): 150 var x: Float64 151 var y: Float64 152 153 # Trait composition with & 154 comptime KeyElement = Copyable & Hashable & Equatable 155 struct Node[T: Copyable & Writable]: 156 var value: Self.T # Self-qualify struct parameters 157 158 # Parametric struct — // separates inferred from explicit params 159 struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]( 160 ImplicitlyCopyable, Sized, 161 ): 162 ... 163 164 # @implicit on constructors allows implicit conversion 165 @implicit 166 def __init__(out self, value: Int): 167 self.data = value 168 ``` 169 170 The 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 175 Inside a struct body, **always** use `Self.ParamName` — bare parameter names are 176 errors: 177 178 ```mojo 179 # WRONG — bare parameter access 180 struct 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 185 struct Container[T: Writable]: 186 var data: Self.T 187 def size(self) -> Self.T: 188 return self.data 189 ``` 190 191 This applies to all struct parameters (`T`, `N`, `mut`, `origin`, etc.) 192 everywhere inside the struct: field types, method signatures, method bodies, and 193 `comptime` declarations. 194 195 ### Explicit copy / transfer 196 197 Types not conforming to `ImplicitlyCopyable` (e.g., `Dict`, `List`, and user 198 structs that conform only to `Copyable, Movable`) require explicit `.copy()` or 199 ownership transfer `^` — `return my_struct` errors until you transfer with `^` 200 or add `ImplicitlyCopyable` conformance: 201 202 ```mojo 203 # WRONG — implicit copy of non-ImplicitlyCopyable type 204 var d = some_dict 205 var result = MyStruct(headers=d) # ERROR 206 207 # CORRECT — explicit copy or transfer 208 var result = MyStruct(headers=d.copy()) # or: headers=d^ 209 ``` 210 211 ## Imports use `std.` prefix 212 213 ```mojo 214 from std.testing import assert_equal, TestSuite 215 from std.algorithm import vectorize 216 from std.python import PythonObject 217 import std.random 218 ``` 219 220 Prelude 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 226 same in-memory representation. Useful when compile-time type expressions are 227 semantically 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 233 Inside 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 239 struct 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 256 Iterators use `raises StopIteration` (not `Optional`): 257 258 ```mojo 259 struct 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 271 For-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 284 fields. Use `MutExternalOrigin` for owned heap data (this is what stdlib 285 `ArcPointer` uses): 286 287 ```mojo 288 # Struct field — specify origin explicitly 289 var _ptr: UnsafePointer[Self.T, MutExternalOrigin] 290 291 # Allocate with alloc[] 292 def __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 302 Mojo tracks reference provenance with **origins**, not "lifetimes": 303 304 ```mojo 305 struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]: ... 306 ``` 307 308 Key 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 315 from std.testing import assert_equal, assert_true, assert_false, assert_raises, TestSuite 316 317 def test_my_feature() raises: 318 assert_equal(compute(2), 4) 319 with assert_raises(): 320 dangerous_operation() 321 322 def main() raises: 323 TestSuite.discover_tests[__functions_in_module()]().run() 324 ``` 325 326 The `mojo test` CLI subcommand was removed — run test files with `mojo run` 327 against a `TestSuite.discover_tests` runner like the one above. 328 329 ## Dict iteration 330 331 Dict entries are iterated directly — no `[]` deref: 332 333 ```mojo 334 for entry in my_dict.items(): 335 print(entry.key, entry.value) # direct field access, NOT entry[].key 336 337 for 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 347 var nums = List[Int](1, 2, 3) 348 349 # CORRECT — bracket literals 350 var nums = [1, 2, 3] # List[Int] 351 var nums: List[Float32] = [1.0, 2.0, 3.0] # explicit element type 352 var scores = {"alice": 95, "bob": 87} # Dict[String, Int] 353 ``` 354 355 `List[T]` rejects negative indices at compile time — use `lst[len(lst) - 1]`, 356 not `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 361 non-copyable arm, indexing the variant copies it — use the typed-arm subscript: 362 363 ```mojo 364 # WRONG — `values[i]` implicitly copies the Variant 365 var x = values[i].take[T]() # ERROR: cannot implicitly copy 366 367 # CORRECT — `values[i][T]` returns a ref to the inner value 368 var 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 386 No implicit conversions between numeric *variables*. Use explicit constructors: 387 388 ```mojo 389 var x = Float32(my_int) * scale # CORRECT: Int → Float32 390 var y = Int(my_uint) # CORRECT: UInt → Int 391 ``` 392 393 **Literals are polymorphic** — `FloatLiteral` and `IntLiteral` auto-adapt to 394 context: 395 396 ```mojo 397 var a: Float32 = 0.5 # literal becomes Float32 398 var b = Float32(x) * 0.003921 # literal adapts — no wrapping needed 399 var 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 406 var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0) 407 v[0] # read lane → Scalar[DType.float32] 408 v[0] = 5.0 # write lane 409 410 # Type cast 411 v.cast[DType.uint32]() # element-wise → SIMD[DType.uint32, 4] 412 413 # Clamp (method) 414 v.clamp(0.0, 1.0) # element-wise clamp to [lower, upper] 415 416 # min/max are FREE FUNCTIONS, not methods 417 from std.math import min, max 418 min(a, b) # element-wise min (same-type SIMD args) 419 max(a, b) # element-wise max 420 421 # Element-wise ternary via bool SIMD 422 var mask = (v > 0.0) # SIMD[DType.bool, 4] 423 mask.select(true_case, false_case) # picks per-lane 424 425 # Reductions 426 v.reduce_add() # horizontal sum → Scalar 427 v.reduce_max() # horizontal max → Scalar 428 v.reduce_min() # horizontal min → Scalar 429 ``` 430 431 ## Strings 432 433 **All explicit stdlib imports require the `std.` prefix.** The 434 removed-syntax table shows the most common corrections, but the rule 435 is universal. Prelude types (`Int`, `String`, `List`, etc.) are 436 auto-imported and need no import statement. 437 438 `len(s)` returns **byte length**, not codepoint count. Mojo strings are UTF-8. 439 Byte indexing requires keyword syntax: `s[byte=idx]` (not `s[idx]`). `len(s)` is 440 deprecated 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 444 materialize an owned `String`. 445 446 ### String indexing (common error) 447 448 ```mojo 449 # WRONG — compile error 450 var ch = s[0] 451 var sub = s[0:10] 452 453 # CORRECT — byte-level access 454 var ch = s[byte=0] # returns StringSlice 455 var ch_str = String(s[byte=0]) # if you need a String 456 457 # CORRECT — iterate codepoints for truncation 458 var result = String("") 459 var count = 0 460 for cp in s.codepoint_slices(): 461 if count >= 10: 462 break 463 result += String(cp) 464 count += 1 465 ``` 466 467 ```mojo 468 var s = "Hello" 469 len(s) # 5 (bytes) 470 s.byte_length() # 5 (same as len) 471 s.count_codepoints() # 5 (codepoint count — differs for non-ASCII) 472 473 # Iteration — `for c in s:` is deprecated; use codepoint_slices() 474 for cp_slice in s.codepoint_slices(): 475 print(cp_slice) 476 477 # Codepoint values 478 for cp in s.codepoints(): 479 print(Int(cp)) # Codepoint is a Unicode scalar value type 480 481 # StaticString = StringSlice with static origin (zero-allocation) 482 comptime GREETING: StaticString = "Hello, World" 483 484 # t-strings for interpolation (lazy, type-safe) 485 var msg = t"x={x}, y={y}" 486 487 # String.format() for runtime formatting 488 var s = "Hello, {}!".format("world") 489 ``` 490 491 ## Error handling 492 493 `raises` can specify a type. `try`/`except` works like Python: 494 495 ```mojo 496 def might_fail() raises -> Int: # raises Error (default) 497 raise Error("something went wrong") 498 499 def parse(s: String) raises Int -> Int: # raises specific type 500 raise 42 501 502 try: 503 var x = parse("bad") 504 except err: # err is Int 505 print("error code:", err) 506 ``` 507 508 No `match` statement. No `async`/`await` — use `Coroutine`/`Task` from 509 `std.runtime`. 510 511 ## Function types and closures 512 513 No lambda. Closures use bare `def` with a capture list in `{}` after the arg 514 list. `escaping` is removed; `capturing[_]` is still valid on parametric 515 closure-type params: 516 517 ```mojo 518 comptime MyFn = def(Int) -> None # unified value type 519 def runner[f: def(Int) capturing[_] -> None](): ... # parametric form 520 521 def closure(i: Int) {mut count, read ptr, var x}: # captures: mut/read/var 522 count += ptr[i] + x^ # `^` at use site, not in `{}` 523 524 vectorize[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 534 AnyType 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 ```