macro processor: add `defined` operator

issue#70
Houtan Bastani 2019-08-19 15:04:39 +02:00
parent 8ebd2a1735
commit b77f6ecd94
No known key found for this signature in database
GPG Key ID: 000094FB955BE169
5 changed files with 20 additions and 1 deletions

View File

@ -861,6 +861,8 @@ UnaryOp::eval()
return argbt->normpdf();
case codes::UnaryOp::normcdf:
return argbt->normcdf();
case codes::UnaryOp::defined:
return argbt->defined();
}
}
catch (StackTrace &ex)
@ -1203,6 +1205,8 @@ UnaryOp::to_string() const noexcept
return "normpdf(" + retval + ")";
case codes::UnaryOp::normcdf:
return "normcdf(" + retval + ")";
case codes::UnaryOp::defined:
return "defined(" + retval + ")";
}
// Suppress GCC warning
exit(EXIT_FAILURE);
@ -1463,6 +1467,9 @@ UnaryOp::print(ostream &output, bool matlab_output) const noexcept
case codes::UnaryOp::normcdf:
output << "normcdf(";
break;
case codes::UnaryOp::defined:
output << "defined(";
break;
}
arg->print(output, matlab_output);

View File

@ -191,6 +191,7 @@ namespace macro
virtual StringPtr cast_string() const { throw StackTrace("This type cannot be cast to a string"); }
virtual TuplePtr cast_tuple() const { throw StackTrace("This type cannot be cast to a tuple"); }
virtual ArrayPtr cast_array() const { throw StackTrace("This type cannot be cast to an array"); }
virtual BoolPtr defined() const { throw StackTrace("Operator `defined` does not exist for this type"); }
};
@ -358,6 +359,10 @@ namespace macro
{
return make_shared<Array>(vector<ExpressionPtr>{make_shared<String>(value, env)}, env);
}
inline BoolPtr defined() const override
{
return make_shared<Bool>(env.isSymbolDefined(value), env);
}
};

View File

@ -104,7 +104,8 @@ namespace macro
lgamma,
round,
normpdf,
normcdf
normcdf,
defined
};
enum class BinaryOp

View File

@ -70,6 +70,8 @@ using namespace macro;
%token BOOL REAL STRING TUPLE ARRAY
%token DEFINED
%left OR
%left AND
%left EQUAL_EQUAL NOT_EQUAL
@ -392,6 +394,8 @@ primary_expr : LPAREN expr RPAREN
{ $$ = make_shared<TrinaryOp>(codes::TrinaryOp::normpdf, $3, $5, $7, driver.env, @$); }
| NORMCDF LPAREN expr COMMA expr COMMA expr RPAREN
{ $$ = make_shared<TrinaryOp>(codes::TrinaryOp::normcdf, $3, $5, $7, driver.env, @$); }
| DEFINED LPAREN NAME RPAREN
{ $$ = make_shared<UnaryOp>(codes::UnaryOp::defined, make_shared<String>($3, driver.env, @3), driver.env, @$); }
;
oper_expr : primary_expr

View File

@ -156,6 +156,8 @@ CONT \\\\{SPC}*
<expr,eval>tuple { return token::TUPLE; }
<expr,eval>array { return token::ARRAY; }
<expr,eval>defined { return token::DEFINED; }
<expr,eval>((([0-9]*\.[0-9]+)|([0-9]+\.))([ed][-+]?[0-9]+)?)|([0-9]+([ed][-+]?[0-9]+)?)|nan|inf {
yylval->build<string>(yytext);
return token::NUMBER;