xo-expression: + if-expressions

This commit is contained in:
Roland Conybeare 2024-06-17 12:26:24 -04:00
commit 012597b112
4 changed files with 91 additions and 1 deletions

View file

@ -0,0 +1,67 @@
/** @file IfExpr.hpp
*
* Author: Roland Conybeare
**/
#pragma once
#include "Expression.hpp"
#include <vector>
#include <string>
//#include <cstdint>
namespace xo {
namespace ast {
/** @class IfExpr
* @brief abstract syntax tree for a function definition
*
**/
class IfExpr : public Expression {
public:
/** @p test test-expression; always execute
* @p when_true then-branch; executes only when test succeeds
* @p when_false else-branch; executes only when test fails
**/
IfExpr(const ref::rp<Expression> & test,
const ref::rp<Expression> & when_true,
const ref::rp<Expression> & when_false)
: Expression(exprtype::if_expr),
test_{test},
when_true_{when_true},
when_false_{when_false} {}
/** downcast from Expression **/
static ref::brw<IfExpr> from(ref::brw<Expression> x) {
return ref::brw<IfExpr>::from(x);
}
const ref::rp<Expression> & test() const { return test_; }
const ref::rp<Expression> & when_true() const { return when_true_; }
const ref::rp<Expression> & when_false() const { return when_false_; }
// ----- Expression -----
virtual void display(std::ostream & os) const override;
private:
/** if:
* (if x y z)
*
* executes x; if true execute y; otherwise execute z
**/
ref::rp<Expression> test_;
ref::rp<Expression> when_true_;
ref::rp<Expression> when_false_;
}; /*IfExpr*/
inline ref::rp<IfExpr>
make_if_expr(const ref::rp<Expression> & test,
const ref::rp<Expression> & when_true,
const ref::rp<Expression> & when_false)
{
return new IfExpr(test, when_true, when_false);
}
} /*namespace ast*/
} /*namespace xo*/
/** end IfExpr.hpp **/

View file

@ -28,6 +28,8 @@ namespace xo {
lambda,
/** variable reference **/
variable,
/** if-then-else **/
if_expr,
/** not an expression. comes last, counts entries **/
n_expr
@ -43,6 +45,7 @@ namespace xo {
case exprtype::apply: return "apply";
case exprtype::lambda: return "lambda";
case exprtype::variable: return "variable";
case exprtype::if_expr: return "if_expr";
default: break;
}

View file

@ -6,7 +6,7 @@ set(SELF_SRCS
Apply.cpp
Lambda.cpp
Variable.cpp
#init_reflect.cpp
IfExpr.cpp
)
xo_add_shared_library4(${SELF_LIB} ${PROJECT_NAME}Targets ${PROJECT_VERSION} 1 ${SELF_SRCS})

20
src/expression/IfExpr.cpp Normal file
View file

@ -0,0 +1,20 @@
/* @file IfExpr.cpp */
#include "IfExpr.hpp"
#include "xo/indentlog/print/vector.hpp"
namespace xo {
namespace ast {
void
IfExpr::display(std::ostream & os) const {
os << "<IfExpr"
<< xtag("test", test_)
<< xtag("when_true", when_true_)
<< xtag("when_false", when_false_)
<< ">";
} /*display*/
} /*namespace ast*/
} /*namespace xo*/
/* end IfExpr.cpp */