modular / modular/modular

[Feature Request] [mojo-lang] Comptime if ternary at runtime

Open
#6,452 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug_feature_triaged enhancement mojo
Dominant language
Mojo
Stars
29.8k
Forks
3.2k
PR merge metrics
No merged PRs in 30d

Description

Review Mojo's priorities
What is your request?

Our current setup only allows us to do

var a: Int
comptime if condition:
  a = 1
else:
  a = 0

AFAIK if we do

var a = 1 if condition else 0

the bool gets materialized and the expression is evaluated at runtime, and for trivial cases like this LLVM should optimize it away.

Could we maybe get a way to express a ternary expression to be forcibly evaluated at compile time? It would avoid materialization for expressions that could be more tersely declared in a ternary than a full if-else:

comptime elems = [1, 2, 3]
var a = 3 comptime if len(elems) >= 3 else 0
What is your motivation for this change?

...

Any other details?

...

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the request's existing comptime if examples and compare them with the ternary expressions shown in the issue. Review how compile-time conditions and runtime expressions are currently distinguished in Mojo. Done means a documented, agreed-upon way to express a ternary that is forcibly evaluated at compile time, including the len(elems) example.

Written by the indexing model from the issue text.

Assessment

Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.