Skip to content

Commit 5d70645

Browse files
committed
Evaluate constant conditional expressions
Signed-off-by: Roberto Raggi <[email protected]>
1 parent 2f73083 commit 5d70645

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

src/parser/cxx/ast_interpreter.cc

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,18 @@ struct ASTInterpreter::NewPlacementResult {};
122122

123123
struct ASTInterpreter::NestedNamespaceSpecifierResult {};
124124

125+
struct ASTInterpreter::ToBool {
126+
ASTInterpreter& interp;
127+
128+
auto operator()(const StringLiteral*) const -> std::optional<bool> {
129+
return true;
130+
}
131+
132+
auto operator()(const auto& value) const -> std::optional<bool> {
133+
return bool(value);
134+
}
135+
};
136+
125137
struct ASTInterpreter::UnitVisitor {
126138
ASTInterpreter& accept;
127139

@@ -2193,10 +2205,17 @@ auto ASTInterpreter::ExpressionVisitor::operator()(BinaryExpressionAST* ast)
21932205
auto ASTInterpreter::ExpressionVisitor::operator()(
21942206
ConditionalExpressionAST* ast) -> ExpressionResult {
21952207
auto conditionResult = accept(ast->condition);
2196-
auto iftrueExpressionResult = accept(ast->iftrueExpression);
2197-
auto iffalseExpressionResult = accept(ast->iffalseExpression);
21982208

2199-
return ExpressionResult{std::nullopt};
2209+
if (!conditionResult.has_value()) return std::nullopt;
2210+
2211+
if (accept.toBool(conditionResult.value())) {
2212+
auto result = accept(ast->iftrueExpression);
2213+
return result;
2214+
}
2215+
2216+
auto result = accept(ast->iffalseExpression);
2217+
2218+
return result;
22002219
}
22012220

22022221
auto ASTInterpreter::ExpressionVisitor::operator()(YieldExpressionAST* ast)
@@ -3176,4 +3195,8 @@ auto ASTInterpreter::evaluate(ExpressionAST* ast) -> std::optional<ConstValue> {
31763195
return result;
31773196
}
31783197

3198+
auto ASTInterpreter::toBool(const ConstValue& value) -> std::optional<bool> {
3199+
return std::visit(ToBool{*this}, value);
3200+
}
3201+
31793202
} // namespace cxx

src/parser/cxx/ast_interpreter.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ class ASTInterpreter {
4343

4444
[[nodiscard]] auto evaluate(ExpressionAST* ast) -> std::optional<ConstValue>;
4545

46+
[[nodiscard]] auto toBool(const ConstValue& value) -> std::optional<bool>;
47+
4648
private:
4749
using ExpressionResult = std::optional<ConstValue>;
4850

@@ -116,6 +118,9 @@ class ASTInterpreter {
116118
struct AttributeSpecifierVisitor;
117119
struct AttributeTokenVisitor;
118120

121+
// ops
122+
struct ToBool;
123+
119124
// run on the base nodes
120125
[[nodiscard]] auto operator()(UnitAST* ast) -> UnitResult;
121126
[[nodiscard]] auto operator()(DeclarationAST* ast) -> DeclarationResult;

0 commit comments

Comments
 (0)