Skip to content

Support if expressions in value position #154

Description

@t-kalinowski

R’s if is an expression. When it has an else branch, it returns the value of the selected branch:

fn <- function(x) {
  declare(type(x = logical(1)))
  y <- if (x) 1 else 2
  y
}

quickr currently lowers if only as a Fortran control-flow statement and does not attach a value to the result. Assignment therefore rejects this example with:

cannot assign `if (x) 1 else 2`: expression does not produce a value

That diagnostic is clearer than the previous internal error, but it describes the current lowering limitation rather than the R expression.

I think if expressions in value position should:

  • infer a common mode, rank, and shape from the two branches;
  • assign the selected branch to the destination or a temporary;
  • evaluate the condition once and execute only the selected branch;
  • preserve branch-local hoisting and side effects;
  • report a clear error when the branch results are incompatible.

An if without else needs separate handling because R returns NULL when the condition is false.

Tests should exercise this through the public API and call the generated function for both branches. They should also cover incompatible branch modes or shapes and side effects confined to the selected branch.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions