, , node, node, , (.. , if, ..).
if, . - ( -C):
enum AST_Node {
Node_if,
Node_and,
Node_or,
Node_not,
Node_equal,
Node_less,
};
struct AST {
struct AST *children[MAX_CHILDREN];
enum AST_Node node;
};
struct AST *parse_if_statement()
{
expect("if");
expect("(");
struct AST *condition = parse_expression();
expect(")");
struct AST *then_branch = parse_statement();
struct AST *else_branch = NULL;
if (accept("else")) {
else_branch = parse_statement();
}
struct AST *if_statement = new_AST_node(Node_if);
if_statement->children[0] = condition;
if_statement->children[1] = then_branch;
if_statement->children[2] = else_branch;
return if_statement;
}
, / ( "", ..), ( ) .
: - , . , node , /.
Value *interpret_if_statement(struct AST *ast)
{
assert(ast->node == Node_if);
struct AST *condition = ast->children[0];
struct AST *then_branch = ast->children[1];
struct AST *else_branch = ast->children[2];
Value *condval = interpret_expression(condition);
if (condval->bool_value == TRUE) {
return interpret_statement(then_branch);
} else if (else_branch != NULL) {
return interpret_statement(else_branch);
} else {
return NULL;
}
}
user529758