Mojo Compile-Time Code
In Mojo Constants you used comptime to name a fixed value like comptime MAX_PLAYERS = 4. That was only the start. The compiler can run your own functions while it builds the program, and hand the finished results to the program. This page shows how that works, what it’s good for, and where the limits are. It’s also the starting point for the rest of this section: parameters, generics and compile-time loops all build on the same idea.
Two moments: compile time and run time
Section titled “Two moments: compile time and run time”Every Mojo program lives through two moments:
- Compile time:
mojo runormojo buildreads your code and turns it into a program. Nothing has run yet. - Run time: the program starts at
mainand does its work.
A var gets its value at run time. A comptime value gets its value at compile time, so by the time main starts, it’s already a finished number (or string, or list) baked into the program.
In Python there’s only one moment: the code runs top to bottom when you start it. A Python “constant” at the top of a file is computed again every time the program starts. Mojo can do that work once, while it builds.
Running your own function at compile time
Section titled “Running your own function at compile time”Here’s a normal function that works out the n-th Fibonacci number with a loop:
def fib(n: Int) -> Int: var a = 0 var b = 1 for _ in range(n): var next = a + b a = b b = next return a
comptime FIB_30 = fib(30)
def main(): print(FIB_30)Output:
832040fib is an ordinary function. Nothing about it says “compile time”. What makes it run early is the place where you call it: the right side of a comptime line. The compiler sees comptime FIB_30 = fib(30), runs fib(30) itself, and stores 832040. The finished program just prints a number; it never runs the loop.
Here’s that idea in one program:
def fib(n: Int) -> Int: var a = 0 var b = 1 for _ in range(n): var next = a + b a = b b = next return a
def main(): comptime early = fib(20) var how_many = 25 var late = fib(how_many) print("worked out while building:", early) print("worked out while running:", late)Output:
worked out while building: 6765worked out while running: 75025early is computed by the compiler. late depends on the variable how_many, so it has to wait until the program runs. You can’t put fib(how_many) on the right of comptime: the compiler stops with “cannot use a dynamic value in comptime initializer”, because it doesn’t know what’s in a var before the program runs.
A one-off compile-time value: comptime (...)
Section titled “A one-off compile-time value: comptime (...)”Sometimes you need a compile-time result only once, in the middle of an expression. Instead of naming it, wrap it in comptime (...):
def fib(n: Int) -> Int: var a = 0 var b = 1 for _ in range(n): var next = a + b a = b b = next return a
def main(): var bonus = 3 print(bonus * comptime (fib(10)))Output:
165comptime (fib(10)) is worked out while building (it’s 55), and only the multiplication by bonus happens at run time. It means exactly the same as writing comptime F10 = fib(10) on its own line first, just shorter.
Compile-time lists
Section titled “Compile-time lists”The compiler can build more than numbers. It can fill a whole List for you:
def squares(n: Int) -> List[Int]: var out = List[Int]() for i in range(n): out.append(i * i) return out^
comptime SQUARES = squares(6)
def main(): print(comptime (len(SQUARES))) print(comptime (SQUARES[4])) var table = materialize[SQUARES]() table.append(99) print(table)Output:
616[0, 1, 4, 9, 16, 25, 99]Three things happen here:
comptime (len(SQUARES))andcomptime (SQUARES[4])ask questions about the list at compile time. Only the answers (6and16) end up in the program.materialize[SQUARES]()makes a real run-time copy of the list, which you can change like any other list.- Writing
print(SQUARES[4])withoutcomptime (...)ormaterializedoesn’t compile.
That last point surprises people, so here’s the error:
comptime SQUARES: List[Int] = [0, 1, 4, 9, 16]
def main(): var i = 2 print(SQUARES[i])hello.mojo:5:11: error: cannot materialize comptime value of type 'List[Int]' to runtime because it is not 'ImplicitlyCopyable' print(SQUARES[i]) ^~~~~~~hello.mojo:5:11: note: use 'materialize' to explicitly materialize the value print(SQUARES[i]) ^ materialize[ ]()mojo: error: failed to parse the provided Mojo source moduleTurning a compile-time value into a run-time one is called materializing it. For small things like Int it happens on its own. For a List, which needs memory, Mojo wants you to say so. Mojo Materialization explains when and how.
What can’t run at compile time
Section titled “What can’t run at compile time”Most code can run inside the compiler, but not all of it. The Mojo manual’s page on compile-time evaluation lists what’s left out: anything that depends on the machine the program runs on. That means:
- reading or writing files,
- calling C libraries or other outside code,
- functions that can raise errors.
Here’s the last one in action:
def parse(text: String) raises -> Int: return Int(text)
comptime ANSWER = parse("42")
def main(): print(ANSWER)hello.mojo:4:24: error: cannot call raising function in comptime initializercomptime ANSWER = parse("42") ~~~~~^~~~~~mojo: error: failed to parse the provided Mojo source moduleA function marked raises might fail, and the compiler has no way to “catch” that failure while building. Write the value as a plain literal (comptime ANSWER = 42) or do the parsing at run time inside main.
Types are compile-time values too
Section titled “Types are compile-time values too”A type like Int or List[String] is also something the compiler knows before the program runs. So you can give a type a new name with comptime. This is called a type alias:
comptime Score = UInt8comptime Grid = List[List[Int]]
def main(): var best: Score = 200 var board: Grid = [[1, 2], [3, 4]] print(best) print(board)Output:
200[[1, 2], [3, 4]]Score is just another name for UInt8, and Grid another name for List[List[Int]]. Aliases make long types easier to read, and they let you change a type in one place: if scores ever need more room, you change comptime Score = UInt16 and every Score in the program follows. The standard library does the same thing: Float64 is itself an alias for a more general type you’ll meet in Mojo SIMD.
Checking compile-time results: comptime assert
Section titled “Checking compile-time results: comptime assert”When the compiler works out a value for you, you can also ask it to check that value. A comptime assert stops the build if its condition is false:
def fib(n: Int) -> Int: var a = 0 var b = 1 for _ in range(n): var next = a + b a = b b = next return a
comptime STEPS = 12comptime RESULT = fib(STEPS)
def main(): comptime assert RESULT < 1000, "RESULT is too big for the display" print("fib of", STEPS, "is", RESULT)Output:
fib of 12 is 144Change STEPS to 20 and the program won’t build: fib(20) is 6765, so the assert fails with “constraint failed: RESULT is too big for the display”. The mistake is caught before anyone runs the program. One rule to know: a comptime assert has to be inside a function. At the top of the file it’s an error (“‘comptime assert’ must be inside a function”), even though comptime values are fine there. You’ll see much more of comptime assert in Mojo Constraints.
The comptime family
Section titled “The comptime family”The keyword shows up in a few places. Here’s the whole family, so you know what’s coming in this section:
| You write | What it does | Where you learn it |
|---|---|---|
comptime NAME = expr |
Names a value worked out while building | This page, Constants |
comptime (expr) |
A one-off compile-time value inside an expression | This page |
comptime Alias = SomeType |
A new name for a type | This page |
comptime assert cond, "msg" |
Stops the build if cond is false |
This page, Constraints |
def f[n: Int]() |
A compile-time input to a function or struct | Parameters |
comptime if / comptime for |
Choose or repeat code while building | Compile-Time If & Loops |
Practice
Section titled “Practice”1. A table worked out early
Section titled “1. A table worked out early”Write a function triangle(n: Int) -> Int that adds up 1 + 2 + ... + n with a loop. Use it to make a compile-time value T100 = triangle(100) and print it from main.
Hint: the comptime line can go outside main, just like a constant.
Show solution
def triangle(n: Int) -> Int: var total = 0 for i in range(1, n + 1): total += i return total
comptime T100 = triangle(100)
def main(): print(T100)Output:
5050The loop runs inside the compiler. The program that runs only contains the number 5050.
2. Fix the program
Section titled “2. Fix the program”This program doesn’t compile. Make it print Third square: 4 without changing the comptime line.
comptime SQUARES: List[Int] = [0, 1, 4, 9]
def main(): print("Third square:", SQUARES[2])Hint: either ask the question at compile time, or make a run-time copy first.
Show solution
comptime SQUARES: List[Int] = [0, 1, 4, 9]
def main(): print("Third square:", comptime (SQUARES[2]))Output:
Third square: 4comptime (SQUARES[2]) reads the item while building, so only the Int reaches the program. var copy = materialize[SQUARES]() followed by copy[2] works too, but makes a whole run-time list just to read one number.
- The compiler can run your own functions while it builds: put the call on the right of
comptime NAME = .... - The same function runs at compile time or run time depending on where you call it.
comptime (expr)gives you a one-off compile-time value inside an expression.- Code that touches files, C libraries, or raises errors can’t run at compile time.
- Compile-time
Lists needmaterialize[...]()(orcomptime (...)) before run-time code can use them. comptime Alias = SomeTypegives a type a new name.comptime assertchecks compile-time results and stops the build when they’re wrong.
Next up: parameters, the square brackets in List[Int] and how to give your own functions compile-time inputs.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Compile-time evaluation: the official page on
comptimevalues, scope, and how the compiler runs your code. - Intro to metaprogramming: a short overview of compile-time code, parameters and traits.
- Materializing compile-time values: why compile-time lists need
materialize, and thecomptime (...)trick. - Keywords reference: where
comptimeappears in the language.