while
This commit is contained in:
parent
16378e5d48
commit
5f560f079b
5 changed files with 30 additions and 5 deletions
|
|
@ -191,3 +191,25 @@ struct Module : Node
|
|||
return oss.str();
|
||||
}
|
||||
};
|
||||
|
||||
struct While : Stmt
|
||||
{
|
||||
ptr<Expr> condition;
|
||||
std::vector<ptr<Stmt>> body;
|
||||
|
||||
While(ptr<Expr> cond, std::vector<ptr<Stmt>> b)
|
||||
: condition(std::move(cond)), body(std::move(b)) {}
|
||||
|
||||
std::string dump(int indent = 0) const override
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << indent_str(indent) << "While\n";
|
||||
oss << condition->dump(indent + 1);
|
||||
for (const auto &stmt : body)
|
||||
{
|
||||
oss << "\n"
|
||||
<< stmt->dump(indent + 1);
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
};
|
||||
|
|
@ -49,6 +49,7 @@ pass { return yy::parser::token::TOK_KW_PASS; }
|
|||
else { return yy::parser::token::TOK_KW_ELSE; }
|
||||
elif { return yy::parser::token::TOK_KW_ELIF; }
|
||||
class { return yy::parser::token::TOK_KW_CLASS; }
|
||||
while { return yy::parser::token::TOK_KW_WHILE; }
|
||||
|
||||
\=\= { return yy::parser::token::TOK_EQ; }
|
||||
\!\= { return yy::parser::token::TOK_NE; }
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@
|
|||
%left KW_OR
|
||||
%left KW_AND
|
||||
%right KW_NOT // unary logical NOT
|
||||
%token KW_DEF KW_IF KW_RETURN KW_FOR KW_IN KW_PASS KW_ELSE KW_ELIF KW_CLASS
|
||||
%token KW_DEF KW_IF KW_RETURN KW_FOR KW_IN KW_PASS KW_ELSE KW_ELIF KW_CLASS KW_WHILE
|
||||
|
||||
%token L_PAREN R_PAREN L_BRACKET R_BRACKET L_BRACE R_BRACE
|
||||
%token DOT COLON SEMICOLON COMMA
|
||||
|
|
@ -94,6 +94,9 @@ stmt:
|
|||
| KW_RETURN expr NEWLINE {
|
||||
$$ = std::make_unique<Return>(std::move($2));
|
||||
}
|
||||
| KW_WHILE expr COLON NEWLINE INDENT stmt_list DEDENT {
|
||||
$$ = std::make_unique<While>(std::move($2), std::move($6));
|
||||
}
|
||||
;
|
||||
|
||||
expr:
|
||||
|
|
@ -102,6 +105,7 @@ expr:
|
|||
| STRING { $$ = std::make_unique<String>($1); }
|
||||
| expr PLUS expr { $$ = std::make_unique<BinOp>( BinaryOperator(BinaryOperator::ADD), std::move($1), std::move($3)); }
|
||||
| expr MULTIPLY expr { $$ = std::make_unique<BinOp>( BinaryOperator(BinaryOperator::MUL), std::move($1), std::move($3)); }
|
||||
| expr MINUS expr { $$ = std::make_unique<BinOp>( BinaryOperator(BinaryOperator::SUB), std::move($1), std::move($3)); }
|
||||
| expr LT expr { $$ = std::make_unique<BinOp>( BinaryOperator(BinaryOperator::LT) , std::move($1), std::move($3)); }
|
||||
| expr KW_AND expr { $$ = std::make_unique<BinOp>( BinaryOperator(BinaryOperator::AND) , std::move($1), std::move($3)); }
|
||||
| expr KW_OR expr { $$ = std::make_unique<BinOp>( BinaryOperator(BinaryOperator::OR) , std::move($1), std::move($3)); }
|
||||
|
|
|
|||
|
|
@ -1,3 +1,2 @@
|
|||
while x:
|
||||
x = x - 1
|
||||
|
||||
|
|
|
|||
|
|
@ -6,4 +6,3 @@ Module
|
|||
BinOp(-)
|
||||
Identifier(x)
|
||||
Number(1)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue