/// <summary> /// Make a loop: /// $initializers /// goto converterGeneratedName# /// while true: /// $iterators /// :converterGeneratedName# /// break $conditionType $condition /// $body /// </summary> ArrayList MakeManualLoop(INode node, List <Statement> initializers, B.StatementModifierType conditionType, Expression condition, List <Statement> iterators, Statement body) { // we use this "while true" form because "continue" must not skip the iterator. ArrayList list = ConvertStatements(initializers); B.LabelStatement labelStatement = MakeLabel(GenerateName()); B.GotoStatement gotoStatement = new B.GotoStatement(); gotoStatement.Label = new B.ReferenceExpression(labelStatement.Name); list.Add(gotoStatement); B.WhileStatement w = new B.WhileStatement(GetLexicalInfo(node)); w.Condition = new B.BoolLiteralExpression(true); list.Add(w); w.Block = ConvertBlock(iterators); B.BreakStatement breakStatement = new B.BreakStatement(); breakStatement.Modifier = new B.StatementModifier(conditionType, ConvertExpression(condition)); w.Block.Add(labelStatement); w.Block.Add(breakStatement); foreach (B.Statement st in ConvertBlock(body).Statements) { w.Block.Add(st); } return(list); }
public object VisitDoLoopStatement(DoLoopStatement doLoopStatement, object data) { bool frontCondition = doLoopStatement.ConditionPosition != ConditionPosition.End; bool negateCondition = doLoopStatement.ConditionType == ConditionType.Until; if (frontCondition && negateCondition) { // VB: Do Unless * : ** : Loop B.UnlessStatement u = new B.UnlessStatement(GetLexicalInfo(doLoopStatement)); u.Condition = ConvertExpression(doLoopStatement.Condition); u.Block = ConvertBlock(doLoopStatement.EmbeddedStatement); return(u); } // While and Do loop B.WhileStatement w = new B.WhileStatement(GetLexicalInfo(doLoopStatement)); if (frontCondition) { w.Condition = ConvertExpression(doLoopStatement.Condition); } else { w.Condition = new B.BoolLiteralExpression(true); } w.Block = ConvertBlock(doLoopStatement.EmbeddedStatement); if (!frontCondition) { B.BreakStatement breakStatement = new B.BreakStatement(); breakStatement.Modifier = new B.StatementModifier(negateCondition ? B.StatementModifierType.If : B.StatementModifierType.Unless, ConvertExpression(doLoopStatement.Condition)); w.Block.Add(breakStatement); } return(w); }
public static Statement MapStatementModifier(StatementModifier modifier, out Block block) { switch (modifier.Type) { case StatementModifierType.If: { IfStatement stmt = new IfStatement(modifier.LexicalInfo); stmt.Condition = modifier.Condition; stmt.TrueBlock = new Block(); block = stmt.TrueBlock; return stmt; } case StatementModifierType.Unless: { UnlessStatement stmt = new UnlessStatement(modifier.LexicalInfo); stmt.Condition = modifier.Condition; block = stmt.Block; return stmt; } case StatementModifierType.While: { WhileStatement stmt = new WhileStatement(modifier.LexicalInfo); stmt.Condition = modifier.Condition; block = stmt.Block; return stmt; } } throw CompilerErrorFactory.NotImplemented(modifier, string.Format("modifier {0} supported", modifier.Type)); }
public override void OnWhileStatement(WhileStatement node) { if (node.OrBlock == null) return; InternalLocal enteredLoop = CodeBuilder().DeclareTempLocal(_currentMethod, BoolType()); IfStatement orPart = new IfStatement( node.OrBlock.LexicalInfo, CodeBuilder().CreateNotExpression(CodeBuilder().CreateReference(enteredLoop)), node.OrBlock, null); node.OrBlock = orPart.ToBlock(); node.Block.Insert(0, CodeBuilder().CreateAssignment( CreateReference(enteredLoop), CreateTrueLiteral())); }
public override void OnWhileStatement(WhileStatement node) { Label endLabel = _il.DefineLabel(); Label bodyLabel = _il.DefineLabel(); Label thenLabel = _il.DefineLabel(); Label conditionLabel = _il.DefineLabel(); LocalBuilder enteredLoop = null; if(null != node.OrBlock) { enteredLoop = _il.DeclareLocal(typeof(bool)); _il.Emit(OpCodes.Ldc_I4_0); _il.Emit(OpCodes.Stloc, enteredLoop); } _il.Emit(OpCodes.Br, conditionLabel); _il.MarkLabel(bodyLabel); EnterLoop(endLabel, conditionLabel); if(null != node.OrBlock) { _il.Emit(OpCodes.Ldc_I4_1); _il.Emit(OpCodes.Stloc, enteredLoop); } node.Block.Accept(this); LeaveLoop(); _il.MarkLabel(conditionLabel); EmitDebugInfo(node); EmitBranchTrue(node.Condition, bodyLabel); if(null != node.OrBlock) { _il.Emit(OpCodes.Ldloc, enteredLoop); _il.Emit(OpCodes.Brtrue, thenLabel); EnterLoop(endLabel, thenLabel); node.OrBlock.Accept(this); LeaveLoop(); _il.MarkLabel(thenLabel); } if(null != node.ThenBlock) { node.ThenBlock.Accept(this); } _il.MarkLabel(endLabel); }
public void do_while_statement(Block container) { IToken token = null; IToken token2 = null; try { WhileStatement statement2; Block block; token = this.LT(1); this.match(10); if (base.inputState.guessing == 0) { WhileStatement statement; WhileStatement statement1 = statement = new WhileStatement(ToLexicalInfo(token)); statement.set_Condition(new BoolLiteralExpression(true)); statement2 = statement; block = statement2.get_Block(); container.Add(statement2); this.EnterLoop(statement2); } this.block(block); token2 = this.LT(1); this.match(0x2f); Expression expression = this.paren_expression(); this.eos(); if (base.inputState.guessing == 0) { BreakStatement statement3; BreakStatement statement4 = statement3 = new BreakStatement(ToLexicalInfo(token2)); statement3.set_Modifier(new StatementModifier(2, expression)); block.Add(statement3); this.LeaveLoop(statement2); } } catch (RecognitionException exception) { if (base.inputState.guessing != 0) { throw; } this.reportError(exception); this.recover(exception, tokenSet_15_); } }
public override void OnWhileStatement(WhileStatement node) { Label endLabel = _il.DefineLabel(); Label bodyLabel = _il.DefineLabel(); Label conditionLabel = _il.DefineLabel(); _il.Emit(OpCodes.Br, conditionLabel); _il.MarkLabel(bodyLabel); EnterLoop(endLabel, conditionLabel); node.Block.Accept(this); LeaveLoop(); _il.MarkLabel(conditionLabel); EmitDebugInfo(node); EmitBranchTrue(node.Condition, bodyLabel); Visit(node.OrBlock); Visit(node.ThenBlock); _il.MarkLabel(endLabel); }
public override void LeaveWhileStatement(WhileStatement node) { node.Condition = AssertBoolContext(node.Condition); }
public void while_statement(Block container) { IToken token = null; try { WhileStatement statement2; Block block; token = this.LT(1); this.match(0x2f); Expression expression = this.paren_expression(); if (base.inputState.guessing == 0) { WhileStatement statement; WhileStatement statement1 = statement = new WhileStatement(ToLexicalInfo(token)); statement.set_Condition(expression); statement2 = statement; block = statement2.get_Block(); container.Add(statement2); this.EnterLoop(statement2); } this.compound_or_single_stmt(block); if (base.inputState.guessing == 0) { this.LeaveLoop(statement2); } } catch (RecognitionException exception) { if (base.inputState.guessing != 0) { throw; } this.reportError(exception); this.recover(exception, tokenSet_15_); } }
public override void OnWhileStatement(WhileStatement node) { this.OnLoopBody(node.get_Block()); }
//throws RecognitionException, TokenStreamException protected WhileStatement while_stmt() { WhileStatement ws; IToken w = null; IToken or = null; IToken et = null; ws = null; Expression e = null; try { // for error handling w = LT(1); match(WHILE); e=expression(); if (0==inputState.guessing) { ws = new WhileStatement(ToLexicalInfo(w)); ws.Condition = e; } compound_stmt(ws.Block); { switch ( LA(1) ) { case OR: { or = LT(1); match(OR); if (0==inputState.guessing) { ws.OrBlock = new Block(ToLexicalInfo(or)); } compound_stmt(ws.OrBlock); break; } case EOF: case DEDENT: case ESEPARATOR: case BREAK: case CONTINUE: case CAST: case CHAR: case DEF: case FOR: case FALSE: case GOTO: case IF: case NULL: case RAISE: case RETURN: case SELF: case SUPER: case THEN: case TRY: case TRUE: case TYPEOF: case UNLESS: case WHILE: case YIELD: case ID: case TRIPLE_QUOTED_STRING: case DOUBLE_QUOTED_STRING: case SINGLE_QUOTED_STRING: case LBRACK: case LPAREN: case ASSEMBLY_ATTRIBUTE_BEGIN: case SPLICE_BEGIN: case DOT: case COLON: case MULTIPLY: case LBRACE: case QQ_BEGIN: case SUBTRACT: case LONG: case INCREMENT: case DECREMENT: case ONES_COMPLEMENT: case INT: case RE_LITERAL: case DOUBLE: case FLOAT: case TIMESPAN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1) ) { case THEN: { et = LT(1); match(THEN); if (0==inputState.guessing) { ws.ThenBlock = new Block(ToLexicalInfo(et)); } compound_stmt(ws.ThenBlock); break; } case EOF: case DEDENT: case ESEPARATOR: case BREAK: case CONTINUE: case CAST: case CHAR: case DEF: case FOR: case FALSE: case GOTO: case IF: case NULL: case RAISE: case RETURN: case SELF: case SUPER: case TRY: case TRUE: case TYPEOF: case UNLESS: case WHILE: case YIELD: case ID: case TRIPLE_QUOTED_STRING: case DOUBLE_QUOTED_STRING: case SINGLE_QUOTED_STRING: case LBRACK: case LPAREN: case ASSEMBLY_ATTRIBUTE_BEGIN: case SPLICE_BEGIN: case DOT: case COLON: case MULTIPLY: case LBRACE: case QQ_BEGIN: case SUBTRACT: case LONG: case INCREMENT: case DECREMENT: case ONES_COMPLEMENT: case INT: case RE_LITERAL: case DOUBLE: case FLOAT: case TIMESPAN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException ex) { if (0 == inputState.guessing) { reportError(ex); recover(ex,tokenSet_75_); } else { throw ex; } } return ws; }
override public void LeaveForStatement(ForStatement node) { _iteratorNode = node.Iterator; CurrentEnumeratorType = GetExpressionType(node.Iterator); if (null == CurrentBestEnumeratorType) return; //error DeclarationCollection declarations = node.Declarations; Block body = new Block(node.LexicalInfo); InternalLocal iterator = CodeBuilder.DeclareLocal(_current, Context.GetUniqueName("iterator"), CurrentBestEnumeratorType); if (CurrentBestEnumeratorType == CurrentEnumeratorType) { //$iterator = <node.Iterator> body.Add( CodeBuilder.CreateAssignment( node.LexicalInfo, CodeBuilder.CreateReference(iterator), node.Iterator)); } else { //$iterator = <node.Iterator>.GetEnumerator() body.Add( CodeBuilder.CreateAssignment( node.LexicalInfo, CodeBuilder.CreateReference(iterator), CodeBuilder.CreateMethodInvocation(node.Iterator, CurrentBestGetEnumerator))); } // while __iterator.MoveNext(): if (null == CurrentBestMoveNext) return; //error WhileStatement ws = new WhileStatement(node.LexicalInfo); ws.Condition = CodeBuilder.CreateMethodInvocation( CodeBuilder.CreateReference(iterator), CurrentBestMoveNext); if (null == CurrentBestGetCurrent) return; //error Expression current = CodeBuilder.CreateMethodInvocation( CodeBuilder.CreateReference(iterator), CurrentBestGetCurrent); if (1 == declarations.Count) { // item = __iterator.Current ws.Block.Add( CodeBuilder.CreateAssignment( node.LexicalInfo, CodeBuilder.CreateReference((InternalLocal)declarations[0].Entity), current)); } else { UnpackExpression(ws.Block, CodeBuilder.CreateCast( CurrentEnumeratorItemType, current), node.Declarations); } ws.Block.Add(node.Block); ws.OrBlock = node.OrBlock; ws.ThenBlock = node.ThenBlock; // try: // while... // ensure: // d = iterator as IDisposable // d.Dispose() unless d is null if (IsAssignableFrom(TypeSystemServices.IDisposableType, CurrentBestEnumeratorType)) { TryStatement tryStatement = new TryStatement(); tryStatement.ProtectedBlock.Add(ws); tryStatement.EnsureBlock = new Block(); CastExpression castExpression = new CastExpression(); castExpression.Type = CodeBuilder.CreateTypeReference(TypeSystemServices.IDisposableType); castExpression.Target = CodeBuilder.CreateReference(iterator); castExpression.ExpressionType = TypeSystemServices.IDisposableType; tryStatement.EnsureBlock.Add( CodeBuilder.CreateMethodInvocation(castExpression, IDisposable_Dispose)); body.Add(tryStatement); } else { body.Add(ws); } ReplaceCurrentNode(body); }
public override void OnWhileStatement(WhileStatement node) { WriteConditionalBlock("while", node.Condition, node.Block); if(node.OrBlock != null) { WriteIndented(); WriteKeyword("or:"); WriteLine(); WriteBlock(node.OrBlock); } if(node.ThenBlock != null) { WriteIndented(); WriteKeyword("then:"); WriteLine(); WriteBlock(node.ThenBlock); } }
public object VisitDoLoopStatement(DoLoopStatement doLoopStatement, object data) { bool frontCondition = doLoopStatement.ConditionPosition != ConditionPosition.End; bool negateCondition = doLoopStatement.ConditionType == ConditionType.Until; if (frontCondition && negateCondition) { // VB: Do Unless * : ** : Loop B.UnlessStatement u = new B.UnlessStatement(GetLexicalInfo(doLoopStatement)); u.Condition = ConvertExpression(doLoopStatement.Condition); u.Block = ConvertBlock(doLoopStatement.EmbeddedStatement); return u; } // While and Do loop B.WhileStatement w = new B.WhileStatement(GetLexicalInfo(doLoopStatement)); if (frontCondition) w.Condition = ConvertExpression(doLoopStatement.Condition); else w.Condition = new B.BoolLiteralExpression(true); w.Block = ConvertBlock(doLoopStatement.EmbeddedStatement); if (!frontCondition) { B.BreakStatement breakStatement = new B.BreakStatement(); breakStatement.Modifier = new B.StatementModifier(negateCondition ? B.StatementModifierType.If : B.StatementModifierType.Unless, ConvertExpression(doLoopStatement.Condition)); w.Block.Add(breakStatement); } return w; }
/// <summary> /// Make a loop: /// $initializers /// goto converterGeneratedName# /// while true: /// $iterators /// :converterGeneratedName# /// break $conditionType $condition /// $body /// </summary> ArrayList MakeManualLoop(INode node, List<Statement> initializers, B.StatementModifierType conditionType, Expression condition, List<Statement> iterators, Statement body) { // we use this "while true" form because "continue" must not skip the iterator. ArrayList list = ConvertStatements(initializers); B.LabelStatement labelStatement = MakeLabel(GenerateName()); B.GotoStatement gotoStatement = new B.GotoStatement(); gotoStatement.Label = new B.ReferenceExpression(labelStatement.Name); list.Add(gotoStatement); B.WhileStatement w = new B.WhileStatement(GetLexicalInfo(node)); w.Condition = new B.BoolLiteralExpression(true); list.Add(w); w.Block = ConvertBlock(iterators); B.BreakStatement breakStatement = new B.BreakStatement(); breakStatement.Modifier = new B.StatementModifier(conditionType, ConvertExpression(condition)); w.Block.Add(labelStatement); w.Block.Add(breakStatement); foreach (B.Statement st in ConvertBlock(body).Statements) { w.Block.Add(st); } return list; }
override public void OnWhileStatement(WhileStatement node) { VisitLoop(node.Block); Visit(node.OrBlock); Visit(node.ThenBlock); }
override public object Clone() { WhileStatement clone = new WhileStatement(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _modifier) { clone._modifier = _modifier.Clone() as StatementModifier; clone._modifier.InitializeParent(clone); } if (null != _condition) { clone._condition = _condition.Clone() as Expression; clone._condition.InitializeParent(clone); } if (null != _block) { clone._block = _block.Clone() as Block; clone._block.InitializeParent(clone); } if (null != _orBlock) { clone._orBlock = _orBlock.Clone() as Block; clone._orBlock.InitializeParent(clone); } if (null != _thenBlock) { clone._thenBlock = _thenBlock.Clone() as Block; clone._thenBlock.InitializeParent(clone); } return clone; }
public override void OnWhileStatement(WhileStatement node) { }
public override void OnWhileStatement(WhileStatement node) { VisitLoop(node.Block); }
void CreateMoveNext() { BooMethodBuilder method = _enumerator.AddVirtualMethod("MoveNext", TypeSystemServices.BoolType); Expression moveNext = CodeBuilder.CreateMethodInvocation( CodeBuilder.CreateReference((InternalField)_enumeratorField.Entity), TypeSystemServices.Map(Methods.InstanceFunctionOf<IEnumerator, bool>(e => e.MoveNext))); Expression current = CodeBuilder.CreateMethodInvocation( CodeBuilder.CreateReference((InternalField)_enumeratorField.Entity), ((IProperty)GetMember(_sourceEnumeratorType, "Current", EntityType.Property)).GetGetMethod()); Statement filter = null; Statement stmt = null; Block outerBlock = null; Block innerBlock = null; if (null == _generator.Filter) { IfStatement istmt = new IfStatement(moveNext, new Block(), null); outerBlock = innerBlock = istmt.TrueBlock; stmt = istmt; } else { WhileStatement wstmt = new WhileStatement(moveNext); outerBlock = wstmt.Block; if (StatementModifierType.If == _generator.Filter.Type) { IfStatement ifstmt = new IfStatement(_generator.Filter.Condition, new Block(), null); innerBlock = ifstmt.TrueBlock; filter = ifstmt; } else { UnlessStatement ustmt = new UnlessStatement(_generator.Filter.Condition); innerBlock = ustmt.Block; filter = ustmt; } stmt = wstmt; } DeclarationCollection declarations = _generator.Declarations; if (declarations.Count > 1) { NormalizeIterationStatements.UnpackExpression(CodeBuilder, method.Method, outerBlock, current, declarations); foreach (Declaration declaration in declarations) { method.Locals.Add(((InternalLocal)declaration.Entity).Local); } } else { InternalLocal local = (InternalLocal)declarations[0].Entity; method.Locals.Add(local.Local); outerBlock.Add(CodeBuilder.CreateAssignment( CodeBuilder.CreateReference(local), current)); } if (null != filter) { outerBlock.Add(filter); } innerBlock.Add(CodeBuilder.CreateAssignment( CodeBuilder.CreateReference((InternalField)_current.Entity), _generator.Expression)); innerBlock.Add(new ReturnStatement(new BoolLiteralExpression(true))); method.Body.Add(stmt); method.Body.Add(new ReturnStatement(new BoolLiteralExpression(false))); }
public Statement for_c(Block container) { Statement statement = null; try { Expression expression; Expression expression2; WhileStatement statement3; Block block; string str; switch (this.LA(1)) { case 0x2d: this.declaration_statement(container); if (base.inputState.guessing == 0) { statement = container.get_Statements().get_Item(-1) as DeclarationStatement; if (statement != null) { statement.Annotate("PrivateScope"); } } break; case 12: case 15: case 0x13: case 0x1b: case 0x1d: case 0x27: case 40: case 0x2a: case 0x2c: case 0x3b: case 60: case 0x3d: case 0x3f: case 0x44: case 0x4f: case 80: case 0x52: case 0x58: case 0x67: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: this.expression_statement(container); break; case 0x4d: break; default: throw new NoViableAltException(this.LT(1), this.getFilename()); } this.match(0x4d); switch (this.LA(1)) { case 12: case 15: case 0x13: case 0x1b: case 0x1d: case 0x27: case 40: case 0x2a: case 0x2c: case 0x3b: case 60: case 0x3d: case 0x3f: case 0x44: case 0x4f: case 80: case 0x52: case 0x58: case 0x67: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: expression = this.expression(); break; case 0x4d: break; default: throw new NoViableAltException(this.LT(1), this.getFilename()); } this.match(0x4d); switch (this.LA(1)) { case 12: case 15: case 0x13: case 0x1b: case 0x1d: case 0x27: case 40: case 0x2a: case 0x2c: case 0x3b: case 60: case 0x3d: case 0x3f: case 0x44: case 0x4f: case 80: case 0x52: case 0x58: case 0x67: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: expression2 = this.assignment_expression(); break; case 0x40: break; default: throw new NoViableAltException(this.LT(1), this.getFilename()); } if (base.inputState.guessing == 0) { WhileStatement statement2; WhileStatement statement1 = statement2 = new WhileStatement(); statement2.set_Condition(expression); statement3 = statement2; if (expression == null) { BoolLiteralExpression expression3; BoolLiteralExpression expression1 = expression3 = new BoolLiteralExpression(); expression3.set_Value(true); statement3.set_Condition(expression3); } block = statement3.get_Block(); statement = statement3; str = this.SetUpLoopLabel(statement3); container.Add(statement); this.EnterLoop(statement3); } this.match(0x40); this.compound_or_single_stmt(block); if (base.inputState.guessing != 0) { return statement; } this.LeaveLoop(statement3); if (this.IsLabelInUse(statement3)) { LabelStatement statement4; LabelStatement statement5 = statement4 = new LabelStatement(); statement4.set_Name(str); block.Add(statement4); } if (expression2 != null) { block.Add(expression2); } } catch (RecognitionException exception) { if (base.inputState.guessing != 0) { throw; } this.reportError(exception); this.recover(exception, tokenSet_15_); return statement; } return statement; }
public override void LeaveWhileStatement(WhileStatement node) { node.Condition = ExplicitBooleanContext(node.Condition); }
/// <summary> /// Optimize the <c>for item in array</c> construct /// </summary> /// <param name="node">the for statement to check</param> private void CheckForItemInArrayLoop(ForStatement node) { var enumeratorType = GetExpressionType(node.Iterator) as IArrayType; if (enumeratorType == null || enumeratorType.Rank > 1) return; IType elementType = enumeratorType.ElementType; if (elementType is InternalCallableType) return; Block body = new Block(node.LexicalInfo); InternalLocal indexVariable = DeclareTempLocal(TypeSystemServices.IntType); Expression indexReference = CodeBuilder.CreateReference(indexVariable); // __num = 0 body.Add( CodeBuilder.CreateAssignment( indexReference, CodeBuilder.CreateIntegerLiteral(0))); InternalLocal arrayVar = DeclareTempLocal(node.Iterator.ExpressionType); ReferenceExpression arrayRef = CodeBuilder.CreateReference(arrayVar); // __arr = <arr> body.Add( CodeBuilder.CreateAssignment( arrayRef, node.Iterator)); InternalLocal endVar = CodeBuilder.DeclareTempLocal( _currentMethod, TypeSystemServices.IntType); ReferenceExpression endRef = CodeBuilder.CreateReference(endVar); // __end = __arr.Length body.Add( CodeBuilder.CreateAssignment( node.Iterator.LexicalInfo, endRef, CodeBuilder.CreateMethodInvocation( arrayRef, Array_get_Length))); // while __num < __end: WhileStatement ws = new WhileStatement(node.LexicalInfo); ws.Condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.LessThan, indexReference, endRef); if (1 == node.Declarations.Count) { ILocalEntity loopVariable = (ILocalEntity) node.Declarations[0].Entity; node.Block.ReplaceNodes( new NodePredicate(new EntityPredicate(loopVariable).Matches), CreateRawArraySlicing(arrayRef, indexReference, elementType, loopVariable.Type)); } else { // alpha, bravo, charlie = arr[__num] UnpackExpression( ws.Block, CreateRawArraySlicing(arrayRef, indexReference, elementType), node.Declarations); } // <block> ws.Block.Add(node.Block); FixContinueStatements(node, ws); // __num += 1 BinaryExpression assignment = CodeBuilder.CreateAssignment( indexReference, CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.IntType, BinaryOperatorType.Addition, indexReference, CodeBuilder.CreateIntegerLiteral(1))); AstAnnotations.MarkUnchecked(assignment); ws.Block.Add(assignment); ws.OrBlock = node.OrBlock; ws.ThenBlock = node.ThenBlock; body.Add(ws); ReplaceCurrentNode(body); }
public override bool EnterWhileStatement(WhileStatement node) { return true; }
/// <summary> /// Optimize the <c>for item in range()</c> construct /// </summary> /// <param name="node">the for statement to check</param> private void CheckForItemInRangeLoop(ForStatement node) { MethodInvocationExpression mi = node.Iterator as MethodInvocationExpression; if (null == mi) return; if (!IsRangeInvocation(mi)) return; DeclarationCollection declarations = node.Declarations; if (declarations.Count != 1) return; ExpressionCollection args = mi.Arguments; Block body = new Block(node.LexicalInfo); Expression min; Expression max; Expression step; IntegerLiteralExpression mini; IntegerLiteralExpression maxi; IntegerLiteralExpression stepi; if (args.Count == 1) { mini = CodeBuilder.CreateIntegerLiteral(0); min = mini; max = args[0]; maxi = max as IntegerLiteralExpression; stepi = CodeBuilder.CreateIntegerLiteral(1); step = stepi; } else if (args.Count == 2) { min = args[0]; mini = min as IntegerLiteralExpression; max = args[1]; maxi = max as IntegerLiteralExpression; stepi = CodeBuilder.CreateIntegerLiteral(1); step = stepi; } else { min = args[0]; mini = min as IntegerLiteralExpression; max = args[1]; maxi = max as IntegerLiteralExpression; step = args[2]; stepi = step as IntegerLiteralExpression; } InternalLocal numVar = CodeBuilder.DeclareTempLocal( _currentMethod, TypeSystemServices.IntType); Expression numRef = CodeBuilder.CreateReference(numVar); // __num = <min> body.Add( CodeBuilder.CreateAssignment( numRef, min)); Expression endRef; if (null != maxi) { endRef = max; } else { InternalLocal endVar = CodeBuilder.DeclareTempLocal( _currentMethod, TypeSystemServices.IntType); endRef = CodeBuilder.CreateReference(endVar); // __end = <end> body.Add( CodeBuilder.CreateAssignment( endRef, max)); } if (args.Count == 1) { if (null != maxi) { if (maxi.Value < 0) { // raise ArgumentOutOfRangeException("max") (if <max> < 0) Statement statement = CodeBuilder.RaiseException( body.LexicalInfo, TypeSystemServices.Map(System_ArgumentOutOfRangeException_ctor), CodeBuilder.CreateStringLiteral("max")); body.Add(statement); } } else { IfStatement ifStatement = new IfStatement(body.LexicalInfo); ifStatement.TrueBlock = new Block(); // raise ArgumentOutOfRangeException("max") if __end < 0 Statement statement = CodeBuilder.RaiseException( body.LexicalInfo, TypeSystemServices.Map(System_ArgumentOutOfRangeException_ctor), CodeBuilder.CreateStringLiteral("max")); ifStatement.Condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.LessThan, endRef, CodeBuilder.CreateIntegerLiteral(0)); ifStatement.TrueBlock.Add(statement); body.Add(ifStatement); } } Expression stepRef; switch (args.Count) { case 1: stepRef = CodeBuilder.CreateIntegerLiteral(1); break; case 2: if (null != mini && null != maxi) { if (maxi.Value < mini.Value) // __step = -1 stepRef = CodeBuilder.CreateIntegerLiteral(-1); else // __step = 1 stepRef = CodeBuilder.CreateIntegerLiteral(1); } else { InternalLocal stepVar = CodeBuilder.DeclareTempLocal( _currentMethod, TypeSystemServices.IntType); stepRef = CodeBuilder.CreateReference(stepVar); // __step = 1 body.Add( CodeBuilder.CreateAssignment( stepRef, CodeBuilder.CreateIntegerLiteral(1))); // __step = -1 if __end < __num IfStatement ifStatement = new IfStatement(node.LexicalInfo); ifStatement.Condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.LessThan, endRef, numRef); ifStatement.TrueBlock = new Block(); ifStatement.TrueBlock.Add( CodeBuilder.CreateAssignment( stepRef, CodeBuilder.CreateIntegerLiteral(-1))); body.Add(ifStatement); } break; default: if (null != stepi) { stepRef = step; } else { InternalLocal stepVar = CodeBuilder.DeclareTempLocal( _currentMethod, TypeSystemServices.IntType); stepRef = CodeBuilder.CreateReference(stepVar); // __step = <step> body.Add( CodeBuilder.CreateAssignment( stepRef, step)); } break; } if (args.Count == 3) { Expression condition = null; bool run = false; if (null != stepi) { if (stepi.Value < 0) { if (null != maxi && null != mini) { run = maxi.Value > mini.Value; } else { condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.GreaterThan, endRef, numRef); } } else { if (null != maxi && null != mini) { run = maxi.Value < mini.Value; } else { condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.LessThan, endRef, numRef); } } } else { if (null != maxi && null != mini) { if (maxi.Value < mini.Value) { condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.GreaterThan, stepRef, CodeBuilder.CreateIntegerLiteral(0)); } else { condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.LessThan, stepRef, CodeBuilder.CreateIntegerLiteral(0)); } } else { condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.Or, CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.And, CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.LessThan, stepRef, CodeBuilder.CreateIntegerLiteral(0)), CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.GreaterThan, endRef, numRef)), CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.And, CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.GreaterThan, stepRef, CodeBuilder.CreateIntegerLiteral(0)), CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, BinaryOperatorType.LessThan, endRef, numRef))); } } // raise ArgumentOutOfRangeException("step") if (__step < 0 and __end > __begin) or (__step > 0 and __end < __begin) Statement statement = CodeBuilder.RaiseException( body.LexicalInfo, TypeSystemServices.Map(System_ArgumentOutOfRangeException_ctor), CodeBuilder.CreateStringLiteral("step")); if (condition != null) { IfStatement ifStatement = new IfStatement(body.LexicalInfo); ifStatement.TrueBlock = new Block(); ifStatement.Condition = condition; ifStatement.TrueBlock.Add(statement); body.Add(ifStatement); } else if (run) { body.Add(statement); } // __end = __num + __step * cast(int, Math.Ceiling((__end - __num)/cast(double, __step))) if (null != stepi && null != maxi && null != mini) { int stepVal = (int) stepi.Value; int maxVal = (int) maxi.Value; int minVal = (int) mini.Value; endRef = CodeBuilder.CreateIntegerLiteral( minVal + stepVal * (int)System.Math.Ceiling((maxVal - minVal) / ((double)stepVal))); } else { Expression endBak = endRef; if (null != maxi) { InternalLocal endVar = CodeBuilder.DeclareTempLocal( _currentMethod, TypeSystemServices.IntType); endRef = CodeBuilder.CreateReference(endVar); } body.Add( CodeBuilder.CreateAssignment( endRef, CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.IntType, BinaryOperatorType.Addition, numRef, CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.IntType, BinaryOperatorType.Multiply, stepRef, CodeBuilder.CreateCast( TypeSystemServices.IntType, CodeBuilder.CreateMethodInvocation( TypeSystemServices.Map(System_Math_Ceiling), CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.DoubleType, BinaryOperatorType.Division, CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.IntType, BinaryOperatorType.Subtraction, endBak, numRef), CodeBuilder.CreateCast( TypeSystemServices.DoubleType, stepRef)))))))); } } // while __num != __end: WhileStatement ws = new WhileStatement(node.LexicalInfo); BinaryOperatorType op = BinaryOperatorType.Inequality; if (stepRef.NodeType == NodeType.IntegerLiteralExpression) { if (((IntegerLiteralExpression)stepRef).Value > 0) { op = BinaryOperatorType.LessThan; } else { op = BinaryOperatorType.GreaterThan; } } ws.Condition = CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.BoolType, op, numRef, endRef); ws.Condition.LexicalInfo = node.LexicalInfo; // item = __num ws.Block.Add( CodeBuilder.CreateAssignment( CodeBuilder.CreateReference((InternalLocal)declarations[0].Entity), numRef)); Block rawBlock = new Block(); rawBlock["checked"] = false; // __num += __step rawBlock.Add( CodeBuilder.CreateAssignment( numRef, CodeBuilder.CreateBoundBinaryExpression( TypeSystemServices.IntType, BinaryOperatorType.Addition, numRef, stepRef))); ws.Block.Add(rawBlock as Statement); // <block> ws.Block.Add(node.Block); ws.OrBlock = node.OrBlock; ws.ThenBlock = node.ThenBlock; body.Add(ws); ReplaceCurrentNode(body); }
//throws RecognitionException, TokenStreamException protected WhileStatement while_stmt() { WhileStatement ws; IToken w = null; IToken or = null; IToken et = null; ws = null; Expression e = null; Block lastBlock = null; try { // for error handling w = LT(1); match(WHILE); e=expression(); if (0==inputState.guessing) { ws = new WhileStatement(SourceLocationFactory.ToLexicalInfo(w)); ws.Condition = e; lastBlock = ws.Block; } begin(); block(ws.Block.Statements); { switch ( LA(1) ) { case OR: { or = LT(1); match(OR); if (0==inputState.guessing) { lastBlock = ws.OrBlock = new Block(SourceLocationFactory.ToLexicalInfo(or)); } begin(); block(ws.OrBlock.Statements); break; } case END: case THEN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1) ) { case THEN: { et = LT(1); match(THEN); if (0==inputState.guessing) { lastBlock = ws.ThenBlock = new Block(SourceLocationFactory.ToLexicalInfo(et)); } begin(); block(ws.ThenBlock.Statements); break; } case END: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } end(lastBlock); } catch (RecognitionException ex) { if (0 == inputState.guessing) { reportError(ex); recover(ex,tokenSet_79_); } else { throw ex; } } return ws; }
private void FixContinueStatements(ForStatement node, WhileStatement ws) { // :update LabelStatement label = CreateUpdateLabel(node); GotoOnTopLevelContinue continueFixup = new GotoOnTopLevelContinue(label); node.Block.Accept(continueFixup); if (continueFixup.UsageCount > 0) ws.Block.Add(label); }
protected WhileStatement while_stmt() //throws RecognitionException, TokenStreamException { WhileStatement ws; IToken w = null; IToken or = null; IToken et = null; ws = null; Expression e = null; try { // for error handling w = LT(1); match(WHILE); e=expression(); if (0==inputState.guessing) { ws = new WhileStatement(ToLexicalInfo(w)); ws.Condition = e; } compound_stmt(ws.Block); { switch ( LA(1) ) { case OR: { or = LT(1); match(OR); if (0==inputState.guessing) { ws.OrBlock = new Block(ToLexicalInfo(or)); } compound_stmt(ws.OrBlock); break; } case EOF: case DEDENT: case ESEPARATOR: case ASSEMBLY_ATTRIBUTE_BEGIN: case MODULE_ATTRIBUTE_BEGIN: case ABSTRACT: case BREAK: case CONTINUE: case CALLABLE: case CAST: case CHAR: case CLASS: case CONSTRUCTOR: case DEF: case DESTRUCTOR: case ENUM: case EVENT: case FINAL: case FOR: case FALSE: case GOTO: case INTERFACE: case INTERNAL: case IF: case NEW: case NULL: case OVERRIDE: case PARTIAL: case PUBLIC: case PROTECTED: case PRIVATE: case RAISE: case RETURN: case SELF: case SUPER: case STATIC: case STRUCT: case THEN: case TRY: case TRANSIENT: case TRUE: case TYPEOF: case UNLESS: case VIRTUAL: case WHILE: case YIELD: case TRIPLE_QUOTED_STRING: case LPAREN: case DOUBLE_QUOTED_STRING: case SINGLE_QUOTED_STRING: case ID: case MULTIPLY: case LBRACK: case SPLICE_BEGIN: case DOT: case COLON: case LBRACE: case QQ_BEGIN: case SUBTRACT: case LONG: case INCREMENT: case DECREMENT: case ONES_COMPLEMENT: case INT: case BACKTICK_QUOTED_STRING: case RE_LITERAL: case DOUBLE: case FLOAT: case TIMESPAN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { if ((LA(1)==THEN) && (LA(2)==COLON)) { et = LT(1); match(THEN); if (0==inputState.guessing) { ws.ThenBlock = new Block(ToLexicalInfo(et)); } compound_stmt(ws.ThenBlock); } else if ((tokenSet_84_.member(LA(1))) && (tokenSet_51_.member(LA(2)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (0 == inputState.guessing) { reportError(ex, "while_stmt"); recover(ex,tokenSet_84_); } else { throw ex; } } return ws; }
public void TransformIteration(ForStatement node) { string[] textArray1 = new string[] { "iterator" }; InternalLocal iteratorVariable = this.get_CodeBuilder().DeclareLocal(this.get_CurrentMethod(), base._context.GetUniqueName(textArray1), this.get_TypeSystemServices().IEnumeratorType); iteratorVariable.set_IsUsed(true); Block block = new Block(node.get_LexicalInfo()); block.Add(this.get_CodeBuilder().CreateAssignment(node.get_LexicalInfo(), this.get_CodeBuilder().CreateReference(iteratorVariable), node.get_Iterator())); WhileStatement statement = new WhileStatement(node.get_LexicalInfo()); statement.set_Condition(this.get_CodeBuilder().CreateMethodInvocation(this.get_CodeBuilder().CreateReference(iteratorVariable), this.IEnumerator_MoveNext)); MethodInvocationExpression expression = this.get_CodeBuilder().CreateMethodInvocation(this.get_CodeBuilder().CreateReference(iteratorVariable), this.IEnumerator_get_Current); InternalLocal entity = TypeSystemServices.GetEntity(node.get_Declarations().get_Item(0)); statement.get_Block().Add(this.get_CodeBuilder().CreateAssignment(node.get_LexicalInfo(), this.get_CodeBuilder().CreateReference(entity), expression)); statement.get_Block().Add(node.get_Block()); new LoopVariableUpdater(this, base._context, iteratorVariable, entity).Visit(node); block.Add(statement); node.get_ParentNode().Replace(node, block); }