1 /* valawhilestatement.vala
3 * Copyright (C) 2006-2009 Jürg Billeter
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 * Jürg Billeter <j@bitron.ch>
26 * Represents a while iteration statement in the source code.
28 public class Vala
.WhileStatement
: CodeNode
, Statement
{
30 * Specifies the loop condition.
32 public Expression condition
{
38 _condition
.parent_node
= this
;
43 * Specifies the loop body.
51 _body
.parent_node
= this
;
55 private Expression _condition
;
59 * Creates a new while statement.
61 * @param cond loop condition
62 * @param body loop body
63 * @param source reference to source code
64 * @return newly created while statement
66 public WhileStatement (Expression condition
, Block body
, SourceReference? source_reference
= null) {
68 this
.source_reference
= source_reference
;
69 this
.condition
= condition
;
72 public override void accept (CodeVisitor visitor
) {
73 visitor
.visit_while_statement (this
);
76 public override void accept_children (CodeVisitor visitor
) {
77 condition
.accept (visitor
);
79 visitor
.visit_end_full_expression (condition
);
81 body
.accept (visitor
);
84 bool always_true (Expression condition
) {
85 var literal
= condition as BooleanLiteral
;
86 return (literal
!= null && literal
.value
);
89 public override bool check (SemanticAnalyzer analyzer
) {
90 // convert to simple loop
92 // do not generate if block if condition is always true
93 if (!always_true (condition
)) {
94 var if_condition
= new
UnaryExpression (UnaryOperator
.LOGICAL_NEGATION
, condition
, condition
.source_reference
);
95 var true_block
= new
Block (condition
.source_reference
);
96 true_block
.add_statement (new
BreakStatement (condition
.source_reference
));
97 var if_stmt
= new
IfStatement (if_condition
, true_block
, null, condition
.source_reference
);
98 body
.insert_statement (0, if_stmt
);
101 var loop
= new
Loop (body
, source_reference
);
103 var parent_block
= (Block
) parent_node
;
104 parent_block
.replace_statement (this
, loop
);
106 return loop
.check (analyzer
);