[flang-commits] [flang] [flang] Implement conditional expressions parser/semantics (F2023) (PR #186489)

Peter Klausler via flang-commits flang-commits at lists.llvm.org
Fri Mar 20 12:47:29 PDT 2026


================
@@ -390,6 +390,36 @@ struct LogicalOperation
   LogicalOperator logicalOperator;
 };
 
+// Fortran 2023 conditional expression: (cond ? val : cond ? val : ... : else)
+// All branches have the same type and rank (verified during semantic analysis).
+template <typename T> class ConditionalExpr {
+public:
+  using Result = T;
+  CLASS_BOILERPLATE(ConditionalExpr)
+  ConditionalExpr(
+      std::vector<Expr<SomeLogical>> &&conds, std::vector<Expr<Result>> &&vals)
+      : conditions_{std::move(conds)}, values_{std::move(vals)} {
+    CHECK(values_.size() == conditions_.size() + 1);
+  }
+  bool operator==(const ConditionalExpr &) const;
+  const std::vector<Expr<SomeLogical>> &conditions() const {
+    return conditions_;
+  }
+  std::vector<Expr<SomeLogical>> &conditions() { return conditions_; }
+  const std::vector<Expr<Result>> &values() const { return values_; }
+  std::vector<Expr<Result>> &values() { return values_; }
+  int Rank() const { return values_.empty() ? 0 : values_.front().Rank(); }
+  std::optional<DynamicType> GetType() const {
+    return values_.empty() ? std::nullopt : values_.front().GetType();
+  }
+  static constexpr int Corank() { return 0; }
+  llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
+
+private:
+  std::vector<Expr<SomeLogical>> conditions_; // size N
----------------
klausler wrote:

The final "else" expression of a conditional expression can be an arbitrary `expr` (R1002) so recursion is unavoidable.  I think that you're trying to tell me that you think it's simpler to represent `(l1 ? x1 : l2 ? x2 : (l3 ? x3 : l4 ? x4 : x5))` as a two-level tree rather than a four-level one.  But this means that code operating over your representation has to use both iteration *and* recursion for everything, rather than just recursion.  The recursion is ineluctable; the iteration is optional and unnecessary.

If that doesn't make sense, I don't think that I can help you further.

https://github.com/llvm/llvm-project/pull/186489


More information about the flang-commits mailing list