Beispiel #1
0
		public override void VisitWhileStatement(WhileStatement whileStatement)
		{
            var token = CreateBlock(string.Format("while ({0})", whileStatement.Condition.GetText()), SDNodeRole.WhileLoop);
            _tokenList.Add(token);

            VisitChildren(token.Statements, whileStatement.EmbeddedStatement);
		}
		void ApplyAction(Script script, WhileStatement statement) {
			var doWhile = new DoWhileStatement {
				Condition = statement.Condition.Clone(),
				EmbeddedStatement = statement.EmbeddedStatement.Clone()
			};

			script.Replace(statement, doWhile);
		}
 public override object VisitWhileStatement(WhileStatement whileStatement, object data)
 {
     var condition = whileStatement.Condition as PrimitiveExpression;
     if (condition != null && condition.LiteralValue == "true")
     {
         UnlockWith(whileStatement);
     }
     return base.VisitWhileStatement(whileStatement, data);
 }
        public void WhileStatementProducesEmptyWhile()
        {
            var statement = new WhileStatement();
            statement.Condition = true;
            statement.Statement = JS.Empty();

            Assert.AreEqual("true;", statement.Condition.ToString());
            Assert.AreEqual(";", statement.Statement.ToString());
            Assert.AreEqual("while(true);", statement.ToString());
        }
 public override object VisitWhileStatement(WhileStatement whileStatement, object data)
 {
     if(whileStatement.EmbeddedStatement is BlockStatement)
     {
         foreach (Statement innerstatement in (BlockStatement)whileStatement.EmbeddedStatement)
         {
             if(innerstatement is WhileStatement || innerstatement is DoWhileStatement)
                 UnlockWith(whileStatement);
         }
     }
     return base.VisitWhileStatement(whileStatement, data);
 }
        public void WhileStatementRequiresConditionAndStatement()
        {
            var statement = new WhileStatement();

            Expect.Throw<InvalidOperationException>(() => statement.ToString());

            statement.Condition = true;

            Expect.Throw<InvalidOperationException>(() => statement.ToString());

            statement.Statement = JS.Empty();

            Assert.AreEqual("while(true);", statement.ToString());
        }
Beispiel #7
0
 public override object Walk(WhileStatement node)
 {
     object result = null;
     while (InterpreterHelper.IsTrue(node.Condition.Accept(this)))
     {
         try
         {
             result = node.Body.Accept(this);
         }
         catch (Break)
         {
             break;
         }
         catch (Next)
         {
             continue;
         }
     }
     return result;
 }
        private string buildChunkedDelete(DeleteSpecification delete)
        {

            var counter = new DeclareVariableStatement();
            var counterVariable = new DeclareVariableElement();
            counterVariable.DataType = new SqlDataTypeReference() {SqlDataTypeOption = SqlDataTypeOption.Int};
            counterVariable.VariableName = new Identifier() {Value = "@rowcount"};
            counterVariable.Value = new IntegerLiteral() {Value = "10000"};
            counter.Declarations.Add(counterVariable);
            
            delete.TopRowFilter = new TopRowFilter();
            delete.TopRowFilter.Expression = new ParenthesisExpression() {Expression = new IntegerLiteral() {Value = "10000"} };

            var setCounter = new SetVariableStatement();
            setCounter.Variable = new VariableReference() {Name = "@rowcount"};
            setCounter.Expression = new GlobalVariableExpression() {Name = "@@rowcount"};
            setCounter.AssignmentKind = AssignmentKind.Equals;

            var deleteStatement = new DeleteStatement();
            deleteStatement.DeleteSpecification = delete;

            var beginEnd = new BeginEndBlockStatement();
            beginEnd.StatementList = new StatementList();
            beginEnd.StatementList.Statements.Add(deleteStatement);
            beginEnd.StatementList.Statements.Add(setCounter);

            var whilePredicate = new BooleanComparisonExpression();
            whilePredicate.ComparisonType = BooleanComparisonType.GreaterThan;
            whilePredicate.FirstExpression = new VariableReference() {Name = "@rowcount"};
            whilePredicate.SecondExpression = new IntegerLiteral() {Value = "0"};

            var whileStatement = new WhileStatement();
            whileStatement.Predicate = whilePredicate;
            whileStatement.Statement = beginEnd;
            
            var text = ScriptDom.GenerateTSql(counter) + "\r\n" + ScriptDom.GenerateTSql(whileStatement);

            return text;
        }
Beispiel #9
0
 public override void PostWalk(WhileStatement node)
 {
     PostWalkWorker(node);
 }
 // WhileStatement
 public override bool Walk(WhileStatement node)
 {
     return(Location >= node.StartIndex && Location <= node.EndIndex);
 }
 // WhileStatement
 public override bool Walk(WhileStatement node)
 {
     return(false);
 }
Beispiel #12
0
        internal static PythonNode Create(NodeInfo info, List <PythonNode> Children)
        {
            if (Children == null)
            {
                Children = new List <PythonNode>();
            }
            var rewriter = new Rewriter(new List <Edit>());

            switch (info.NodeType)
            {
            case "CallExpressionNode":
                var target = (Expression)Children[0].InnerNode;
                var args   = new List <Arg>();
                if (Children.Count > 1)
                {
                    for (var i = 1; i < Children.Count; i++)
                    {
                        args.Add(rewriter.VisitArg((Arg)Children[i].InnerNode));
                    }
                }
                var inner = new CallExpression(rewriter.VisitExpression(target), args.ToArray());
                return(new CallExpressionNode(inner)
                {
                    Children = Children
                });

            case "ArgNode":
                var expression = (Expression)Children[0].InnerNode;
                var innerArg   = (info.NodeValue == null) ? new Arg(rewriter.VisitExpression(expression)) :
                                 new Arg(info.NodeType, expression);
                return(new ArgNode(innerArg)
                {
                    Children = Children, Value = innerArg.Name
                });

            case "BinaryExpressionNode":
                var            left             = (Expression)Children[0].InnerNode;
                var            right            = (Expression)Children[1].InnerNode;
                PythonOperator op               = info.NodeValue;
                var            binaryExpression = new BinaryExpression(op, rewriter.VisitExpression(left), rewriter.VisitExpression(right));
                return(new BinaryExpressionNode(binaryExpression)
                {
                    Children = Children, Value = binaryExpression.Operator
                });

            case "AugmentedAssignStatementNode":
                var            left1  = (Expression)Children[0].InnerNode;
                var            right1 = (Expression)Children[1].InnerNode;
                PythonOperator op1    = info.NodeValue;
                var            augmentedAssignStatement = new AugmentedAssignStatement(op1, rewriter.VisitExpression(left1), rewriter.VisitExpression(right1));
                return(new AugmentedAssignStatementNode(augmentedAssignStatement)
                {
                    Children = Children, Value = augmentedAssignStatement.Operator
                });

            case "SuiteStatementNode":
                var statements     = Children.Select(e => rewriter.VisitStatement((Statement)e.InnerNode));
                var suiteStatement = new SuiteStatement(statements.ToArray());
                return(new SuiteStatementNode(suiteStatement)
                {
                    Children = Children
                });

            case "WhileStatementNode":
                var       test           = (Expression)Children[0].InnerNode;
                var       body           = (Statement)Children[1].InnerNode;
                Statement else_          = (Children.Count == 3) ? rewriter.VisitStatement((Statement)Children[2].InnerNode) : null;
                var       whileStatement = new WhileStatement(rewriter.VisitExpression(test), rewriter.VisitStatement(body), else_);
                return(new WhileStatementNode(whileStatement)
                {
                    Children = Children
                });

            case "ReturnStatementNode":
                var returnStatement = new ReturnStatement(rewriter.VisitExpression((Expression)Children[0].InnerNode));
                return(new ReturnStatementNode(returnStatement)
                {
                    Children = Children
                });

            case "ParameterNode":
                var parameter = new Parameter(info.NodeValue);
                if (Children.Any())
                {
                    parameter.DefaultValue = rewriter.VisitExpression((Expression)Children[0].InnerNode);
                }
                return(new ParameterNode(parameter)
                {
                    Children = Children, Value = parameter.Name
                });

            case "ExpressionStatementNode":
                var expressionStatement = new ExpressionStatement(rewriter.VisitExpression((Expression)Children[0].InnerNode));
                return(new ExpressionStatementNode(expressionStatement)
                {
                    Children = Children
                });

            case "ParenthesisExpressionNode":
                var parenthesisExpression = new ParenthesisExpression(rewriter.VisitExpression((Expression)Children[0].InnerNode));
                return(new ParenthesisExpressionNode(parenthesisExpression)
                {
                    Children = Children
                });

            case "IfStatementNode":
                if (Children.Last().InnerNode is IfStatementTest)
                {
                    var ifStatement = new IfStatement(Children.Select(e => (IfStatementTest)e.InnerNode).ToArray(), null);
                    return(new IfStatementNode(ifStatement)
                    {
                        Children = Children
                    });
                }
                var tests     = Children.GetRange(0, Children.Count - 1).Select(e => (IfStatementTest)e.InnerNode);
                var elseStmt  = Children.Last().InnerNode;
                var statement = new IfStatement(tests.ToArray(), rewriter.VisitStatement((Statement)elseStmt));
                return(new IfStatementNode(statement)
                {
                    Children = Children
                });

            case "IfStatementTestNode":
                var ifStatementTest = new IfStatementTest(rewriter.VisitExpression((Expression)Children[0].InnerNode), rewriter.VisitStatement((Statement)Children[1].InnerNode));
                return(new IfStatementTestNode(ifStatementTest)
                {
                    Children = Children
                });

            case "AssignmentStatementNode":
                IEnumerable <Expression> leftAssign = Children.GetRange(0, Children.Count - 1).Select(e => rewriter.VisitExpression((Expression)e.InnerNode));
                var assignmentStatement             = new AssignmentStatement(leftAssign.ToArray(), rewriter.VisitExpression((Expression)Children.Last().InnerNode));
                return(new AssignmentStatementNode(assignmentStatement)
                {
                    Children = Children
                });

            case "TupleExpressionNode":
                IEnumerable <Expression> expressions = Children.Select(e => rewriter.VisitExpression((Expression)e.InnerNode));
                var tupleExpression = new TupleExpression(info.NodeValue, expressions.ToArray());
                return(new TupleExpressionNode(tupleExpression)
                {
                    Children = Children
                });

            case "ConditionalExpressionNode":
                var condExpression = new ConditionalExpression(rewriter.VisitExpression((Expression)Children[0].InnerNode), rewriter.VisitExpression((Expression)Children[1].InnerNode),
                                                               rewriter.VisitExpression((Expression)Children[2].InnerNode));
                return(new ConditionalExpressionNode(condExpression)
                {
                    Children = Children
                });

            //case "FunctionDefinitionNode":
            //    var funDef = new FunctionDefinition(info.NodeValue, ,rewriter.VisitExpression((Expression)Children[0].InnerNode));
            //    return new FunctionDefinitionNode(funDef) { Children = Children };
            default:
                throw new NotImplementedException(info.NodeType);
            }
        }
 public virtual void PostWalk(WhileStatement node)
 {
 }
 public virtual void PostWalk(WhileStatement node) { }
		public virtual void VisitWhileStatement (WhileStatement whileStatement)
		{
			VisitChildren (whileStatement);
		}
Beispiel #16
0
 public virtual bool Visit(WhileStatement node)
 {
     return(CommonVisit(node));
 }
Beispiel #17
0
 public virtual void EndVisit(WhileStatement node)
 {
     CommonEndVisit(node);
 }
 public void Visit(WhileStatement unit)
 {
     unit.Condition.Accept(this);
     unit.Statement.Accept(this);
 }
Beispiel #19
0
 public override IEnumerable <Expression> VisitWhileStatement(WhileStatement whileStatement)
 {
     yield return(whileStatement.Condition);
 }
Beispiel #20
0
        void CreateMoveNext()
        {
            BooMethodBuilder method = _enumerator.AddVirtualMethod("MoveNext", TypeSystemServices.BoolType);

            Expression moveNext = CodeBuilder.CreateMethodInvocation(
                CodeBuilder.CreateReference((InternalField)_enumeratorField.Entity),
                TypeSystemServices.Map(Types.IEnumerator.GetMethod("MoveNext")));

            Expression current = CodeBuilder.CreateMethodInvocation(
                CodeBuilder.CreateReference((InternalField)_enumeratorField.Entity),
                TypeSystemServices.Map(Types.IEnumerator.GetProperty("Current").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)));
        }
Beispiel #21
0
 public override void OnWhileStatement(WhileStatement node)
 {
 }
Beispiel #22
0
 public virtual void VisitWhileStatement(WhileStatement node)
 {
     Visit(node.Condition);
     Visit(node.Body);
 }
Beispiel #23
0
 public override void Exit(WhileStatement node)
 {
     level--;
 }
Beispiel #24
0
 public override DefiniteAssignmentStatus VisitWhileStatement(WhileStatement whileStatement, DefiniteAssignmentStatus data)
 {
     return(data);                // condition is handled by special condition CFG node
 }
Beispiel #25
0
		IEnumerable<Statement> TransformNode(ILNode node)
		{
			if (node is ILLabel) {
				yield return new Ast.LabelStatement { Label = ((ILLabel)node).Name };
			} else if (node is ILExpression) {
				List<ILRange> ilRanges = ILRange.OrderAndJoint(node.GetSelfAndChildrenRecursive<ILExpression>().SelectMany(e => e.ILRanges));
				AstNode codeExpr = TransformExpression((ILExpression)node);
				if (codeExpr != null) {
					codeExpr = codeExpr.WithAnnotation(ilRanges);
					if (codeExpr is Ast.Expression) {
						yield return new Ast.ExpressionStatement { Expression = (Ast.Expression)codeExpr };
					} else if (codeExpr is Ast.Statement) {
						yield return (Ast.Statement)codeExpr;
					} else {
						throw new Exception();
					}
				}
			} else if (node is ILWhileLoop) {
				ILWhileLoop ilLoop = (ILWhileLoop)node;
				WhileStatement whileStmt = new WhileStatement() {
					Condition = ilLoop.Condition != null ? (Expression)TransformExpression(ilLoop.Condition) : new PrimitiveExpression(true),
					EmbeddedStatement = TransformBlock(ilLoop.BodyBlock)
				};
				yield return whileStmt;
			} else if (node is ILCondition) {
				ILCondition conditionalNode = (ILCondition)node;
				bool hasFalseBlock = conditionalNode.FalseBlock.EntryGoto != null || conditionalNode.FalseBlock.Body.Count > 0;
				yield return new Ast.IfElseStatement {
					Condition = (Expression)TransformExpression(conditionalNode.Condition),
					TrueStatement = TransformBlock(conditionalNode.TrueBlock),
					FalseStatement = hasFalseBlock ? TransformBlock(conditionalNode.FalseBlock) : null
				};
			} else if (node is ILSwitch) {
				ILSwitch ilSwitch = (ILSwitch)node;
				SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) };
				foreach (var caseBlock in ilSwitch.CaseBlocks) {
					SwitchSection section = new SwitchSection();
					if (caseBlock.Values != null) {
						section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, ilSwitch.Condition.InferredType) }));
					} else {
						section.CaseLabels.Add(new CaseLabel());
					}
					section.Statements.Add(TransformBlock(caseBlock));
					switchStmt.SwitchSections.Add(section);
				}
				yield return switchStmt;
			} else if (node is ILTryCatchBlock) {
				ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node);
				var tryCatchStmt = new Ast.TryCatchStatement();
				tryCatchStmt.TryBlock = TransformBlock(tryCatchNode.TryBlock);
				foreach (var catchClause in tryCatchNode.CatchBlocks) {
					if (catchClause.ExceptionVariable == null
					    && (catchClause.ExceptionType == null || catchClause.ExceptionType.MetadataType == MetadataType.Object))
					{
						tryCatchStmt.CatchClauses.Add(new Ast.CatchClause { Body = TransformBlock(catchClause) });
					} else {
						tryCatchStmt.CatchClauses.Add(
							new Ast.CatchClause {
								Type = AstBuilder.ConvertType(catchClause.ExceptionType),
								VariableName = catchClause.ExceptionVariable == null ? null : catchClause.ExceptionVariable.Name,
								Body = TransformBlock(catchClause)
							});
					}
				}
				if (tryCatchNode.FinallyBlock != null)
					tryCatchStmt.FinallyBlock = TransformBlock(tryCatchNode.FinallyBlock);
				if (tryCatchNode.FaultBlock != null) {
					CatchClause cc = new CatchClause();
					cc.Body = TransformBlock(tryCatchNode.FaultBlock);
					cc.Body.Add(new ThrowStatement()); // rethrow
					tryCatchStmt.CatchClauses.Add(cc);
				}
				yield return tryCatchStmt;
			} else if (node is ILFixedStatement) {
				ILFixedStatement fixedNode = (ILFixedStatement)node;
				FixedStatement fixedStatement = new FixedStatement();
				foreach (ILExpression initializer in fixedNode.Initializers) {
					Debug.Assert(initializer.Code == ILCode.Stloc);
					ILVariable v = (ILVariable)initializer.Operand;
					fixedStatement.Variables.Add(
						new VariableInitializer {
							Name = v.Name,
							Initializer = (Expression)TransformExpression(initializer.Arguments[0])
						}.WithAnnotation(v));
				}
				fixedStatement.Type = AstBuilder.ConvertType(((ILVariable)fixedNode.Initializers[0].Operand).Type);
				fixedStatement.EmbeddedStatement = TransformBlock(fixedNode.BodyBlock);
				yield return fixedStatement;
			} else if (node is ILBlock) {
				yield return TransformBlock((ILBlock)node);
			} else {
				throw new Exception("Unknown node type");
			}
		}
Beispiel #26
0
 /// <summary>
 /// Visit operation called for while statements.
 ///
 /// <param name="stmt">an while statement</param>
 /// </summary>
 public virtual void visit_while_statement(WhileStatement stmt)
 {
 }
 public override void PostWalk(WhileStatement node) { }
        /// <summary>
        ///     Generates the code for a WhileStatement node.
        /// </summary>
        /// <param name="ws">The WhileStatement node.</param>
        /// <returns>String containing C# code for WhileStatement ws.</returns>
        private string GenerateWhileStatement(WhileStatement ws)
        {
            StringBuilder retVal = new StringBuilder();
            StringBuilder tmpVal = new StringBuilder();

            bool marc = FuncCallsMarc();

            tmpVal.Append(GenerateIndented("while (", ws));
            tmpVal.Append(GenerateNode((SYMBOL) ws.kids.Pop()));
            tmpVal.Append(GenerateLine(")"));

            //Forces all functions to use MoveNext() instead of .Current, as it never changes otherwise, and the loop runs infinitely
            m_isInEnumeratedDeclaration = true;
            retVal.Append(DumpFunc(marc));
            retVal.Append(tmpVal.ToString());
            m_isInEnumeratedDeclaration = false; //End above

            if (IsParentEnumerable)
            {
                retVal.Append(GenerateLine("{")); // SLAM! No 'while(true) doThis(); ' statements for you!
                retVal.Append(GenerateLine("if (CheckSlice()) yield return null;"));
            }

            // CompoundStatement handles indentation itself but we need to do it
            // otherwise.
            bool indentHere = ws.kids.Top is Statement;
            if (indentHere) m_braceCount++;
            retVal.Append(GenerateNode((SYMBOL) ws.kids.Pop()));
            if (indentHere) m_braceCount--;

            if (IsParentEnumerable)
                retVal.Append(GenerateLine("}"));

            return retVal.ToString() + DumpAfterFunc(marc);
        }
Beispiel #29
0
			public override object Visit (While whileStatement)
			{
				var result = new WhileStatement (WhilePosition.Begin);
				var location = LocationsBag.GetLocations (whileStatement);
				result.AddChild (new CSharpTokenNode (Convert (whileStatement.loc), "while".Length), WhileStatement.WhileKeywordRole);
				
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), WhileStatement.Roles.LPar);
				result.AddChild ((INode)whileStatement.expr.Accept (this), WhileStatement.Roles.Condition);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), WhileStatement.Roles.RPar);
				result.AddChild ((INode)whileStatement.Statement.Accept (this), WhileStatement.Roles.EmbeddedStatement);
				
				return result;
			}
		public override void VisitWhileStatement(WhileStatement whileStatement) {
			bool oldIsInsideLoop = _isInsideLoop;
			try {
				_isInsideLoop = true;
				base.VisitWhileStatement(whileStatement);
			}
			finally {
				_isInsideLoop = oldIsInsideLoop;
			}
		}
Beispiel #31
0
 public override bool Walk(WhileStatement node)
 {
     UpdateChildRanges(node);
     return(base.Walk(node));
 }
Beispiel #32
0
 public void VisitWhile(WhileStatement w)
 {
     if (w.Else != null)
     {
         gen.If(
             w.Test.Accept(xlat),
             () => gen.DoWhile(
                 () => w.Body.Accept(this),
                 w.Test.Accept(xlat)),
             () => w.Else.Accept(this));
     }
     else
     {
         gen.While(
             w.Test.Accept(xlat),
             () => w.Body.Accept(this));
     }
 }
 // WhileStatement
 public virtual bool Walk(WhileStatement node)
 {
     return(true);
 }
 public virtual void Exit(WhileStatement node)
 {
 }
 public override void PostWalk(WhileStatement node)
 {
 }
		public override void VisitWhileStatement(WhileStatement whileStatement) {
			// Condition
			JsExpression condition;
			List<JsStatement> preBody = null;
			var compiledCondition = CompileExpression(whileStatement.Condition, CompileExpressionFlags.ReturnValueIsImportant);
			if (compiledCondition.AdditionalStatements.Count == 0) {
				condition = compiledCondition.Expression;
			}
			else {
				// The condition requires additional statements. Transform "while ((SomeProperty = 1) < 0) { ... }" to "while (true) { this.set_SomeProperty(1); if (!(i < 1)) { break; } ... }
				preBody = new List<JsStatement>();
				preBody.AddRange(compiledCondition.AdditionalStatements);
				preBody.Add(JsStatement.If(JsExpression.LogicalNot(compiledCondition.Expression), JsStatement.Break(), null));
				condition = JsExpression.True;
			}

			var body = CreateInnerCompiler().Compile(whileStatement.EmbeddedStatement);
			if (preBody != null)
				body = JsStatement.Block(preBody.Concat(body.Statements));

			_result.Add(JsStatement.While(condition, body));
		}
Beispiel #37
0
 public void Visit(WhileStatement statement)
 {
     statement.Statement.Accept(this);
     statement.Condition.Accept(this);
 }
Beispiel #38
0
 // WhileStatement
 public override bool Walk(WhileStatement node)
 {
     return(ShouldWalkWorker(node));
 }
		public void WhileTrue()
		{
			WhileStatement loop = new WhileStatement {
				Condition = new PrimitiveExpression(true),
				EmbeddedStatement = new BlockStatement {
					new AssignmentExpression(new IdentifierExpression("i"), new PrimitiveExpression(0)),
					new BreakStatement()
				}
			};
			DefiniteAssignmentAnalysis da = CreateDefiniteAssignmentAnalysis(loop);
			da.Analyze("i");
			Assert.AreEqual(0, da.UnassignedVariableUses.Count);
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(loop));
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(loop.EmbeddedStatement));
			Assert.AreEqual(DefiniteAssignmentStatus.CodeUnreachable, da.GetStatusAfter(loop.EmbeddedStatement));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusAfter(loop));
		}
Beispiel #40
0
 public override bool Walk(WhileStatement node)
 {
     CanComplete     = IsActualExpression(node.Test);
     CommitByDefault = true;
     return(base.Walk(node));
 }
        /*
            go from:

            insert into dbo.table(columns...)
            select top X from dbo.another_table(columns...)

            to:

            while (select count(*) from dbo.table) > 0
            begin
                with to_delete(
                    select top X from dbo.another_table(columns...)
                )
                delete to_delete.* into dbo.table(columns...)
            end

        */
        private WhileStatement BuildWhileStatement(InsertSpecification originalInsert)
        {
            var whyle = new WhileStatement();
            whyle.Predicate =
                BuildWhilePredicate(
                    BuildSelectSubQuery((originalInsert.InsertSource as SelectInsertSource).Select as QuerySpecification));
            whyle.Statement = BuildBeginEndWrappedBody(originalInsert);
            return whyle;
        }
 public virtual void VisitWhileStatement(WhileStatement whileStatement)
 {
     VisitExpression(whileStatement.Test);
     VisitStatement(whileStatement.Body);
 }
 public virtual bool Enter(WhileStatement node)
 {
     return true;
 }
Beispiel #44
0
 public WhileBlock(IEmitter emitter, WhileStatement whileStatement)
     : base(emitter, whileStatement)
 {
     Emitter        = emitter;
     WhileStatement = whileStatement;
 }
Beispiel #45
0
        public override StringBuilder VisitWhileStatement(WhileStatement whileStatement, int data)
        {
            var result = new StringBuilder("while (").Append(whileStatement.Condition.AcceptVisitor(this, data)).Append(")");

            var stmt = whileStatement.EmbeddedStatement;
            result.Append(Indent(stmt, stmt.AcceptVisitor(this, data)));

            return result;
        }
Beispiel #46
0
 public SymbolTable VisitWhile(WhileStatement w)
 {
     throw new NotImplementedException();
 }
Beispiel #47
0
 public override bool Enter(WhileStatement node)
 {
     Print("WhileStatement");
     level++;
     return true;
 }
Beispiel #48
0
            public override object VisitWhileStatement(WhileStatement whileStatement, object data)
            {
                UnlockWith(whileStatement);

                return(base.VisitWhileStatement(whileStatement, data));
            }
		public virtual void Visit(WhileStatement s)
		{
			VisitChildren(s);

			if (s.Condition != null)
				s.Condition.Accept(this);
		}
Beispiel #50
0
 private List <Inferred> InferWhileStatement(WhileStatement node, Scope scope)
 {
     Debug.Print("Not implemented: InferWhileStatementIn");
     return(null);
 }
 // WhileStatement
 public virtual bool Walk(WhileStatement node) { return true; }
 public WhileExpressionInterpreter(ExpressionInterpreterHandler expressionInterpreterHandler, WhileStatement whileStatement, LabelTarget brk, LabelTarget cont)
 {
     this.expressionInterpreterHandler = expressionInterpreterHandler;
     this.whileStatement = whileStatement;
     this.brk            = brk;
     this.cont           = cont;
 }
 // WhileStatement
 public override bool Walk(WhileStatement node) { return false; }
Beispiel #54
0
        private ExpressionValue ExecuteStatement(Statement statement, Environment env)
        {
            switch (statement.kind)
            {
            case StatementType.ASSIGN:
            {
                AssignmentStatement asg = statement as AssignmentStatement;
                this.Assign(asg.assignment);
                return(null);
            }

            case StatementType.IF:
            {
                IfStatement     st    = statement as IfStatement;
                ExpressionValue value = this.evaluator.Evaluate(st.condition.Expression, this.env);
                if (value.Bool == true)
                {
                    return(this.ExecuteStatements(st.body));
                }
                return(null);
            }

            case StatementType.IF_ELSE:
            {
                IfElseStatement st    = statement as IfElseStatement;
                ExpressionValue value = this.evaluator.Evaluate(st.condition.Expression, this.env);
                if (value.Bool == true)
                {
                    return(this.ExecuteStatements(st.ifBody));
                }
                else
                {
                    return(this.ExecuteStatements(st.elseBody));
                }
            }

            case StatementType.WHILE:
            {
                WhileStatement  st    = statement as WhileStatement;
                ExpressionValue value = this.evaluator.Evaluate(st.condition.Expression, this.env);
                if (value.Bool == true)
                {
                    Statements ss = new Statements();
                    ss.AddStatement(st.body);
                    ss.AddStatement(st);
                    return(this.ExecuteStatements(ss));
                }

                return(null);
            }

            case StatementType.FUNC_DECL:
            {
                FunctionStatement st = statement as FunctionStatement;
                this.DeclareFunction(st.function);
                return(null);
            }

            case StatementType.FUNCTION:
            {
                FunctionStatement st = statement as FunctionStatement;
                return(this.ExecuteFunction(st.val));
            }

            case StatementType.RETURN:
            {
                FunctionStatement st = statement as FunctionStatement;
                return(this.evaluator.Evaluate(st.val, this.Environment));
            }
            }

            return(null);
        }
Beispiel #55
0
			public override object Visit(While whileStatement)
			{
				var result = new WhileStatement();
				var location = LocationsBag.GetLocations(whileStatement);
				result.AddChild(new CSharpTokenNode(Convert(whileStatement.loc), WhileStatement.WhileKeywordRole), WhileStatement.WhileKeywordRole);
				
				if (location != null)
					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
				if (whileStatement.expr != null)
					result.AddChild((Expression)whileStatement.expr.Accept(this), Roles.Condition);
				if (location != null && location.Count > 1)
					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
				if (whileStatement.Statement != null)
					result.AddChild((Statement)whileStatement.Statement.Accept(this), Roles.EmbeddedStatement);
				return result;
			}
Beispiel #56
0
 public void Visit(WhileStatement node)
 {
     ReportError(node);
 }
        public void VisitWhileStatement(WhileStatement whileStmt)
        {
            int tmp_counter = scope_counter;
            DecendScope();
            scope_counter = 0;

            whileStmt.Condition.AcceptWalker(this);
            whileStmt.Body.AcceptWalker(this);

            AscendScope();
            scope_counter = tmp_counter + 1;
        }
Beispiel #58
0
        Statement ParseStatement(Scope scope)
        {
            int       startP    = reader.p;
            int       startLine = reader.Peek().Line;
            Statement stat      = null;

            // print(tok.Peek().Print())
            if (reader.ConsumeKeyword("if"))
            {
                //setup
                IfStmt _if = new IfStmt();

                //clauses
                do
                {
                    int        sP       = reader.p;
                    Expression nodeCond = ParseExpr(scope);

                    if (!reader.ConsumeKeyword("then"))
                    {
                        error("'then' expected");
                    }

                    List <Statement> nodeBody = ParseStatementList(scope);

                    List <Token> range = new List <Token>();
                    range.Add(reader.tokens[sP - 1]);
                    range.AddRange(reader.Range(sP, reader.p));

                    _if.Clauses.Add(new ElseIfStmt(scope)
                    {
                        Condition     = nodeCond,
                        Body          = nodeBody,
                        ScannedTokens = range
                    });
                }while (reader.ConsumeKeyword("elseif"));

                // else clause
                if (reader.ConsumeKeyword("else"))
                {
                    int sP = reader.p;
                    List <Statement> nodeBody = ParseStatementList(scope);
                    List <Token>     range    = new List <Token>();
                    range.Add(reader.tokens[sP - 1]);
                    range.AddRange(reader.Range(sP, reader.p));

                    _if.Clauses.Add(new ElseStmt(scope)
                    {
                        Body          = nodeBody,
                        ScannedTokens = range
                    });
                }

                // end
                if (!reader.ConsumeKeyword("end"))
                {
                    error("'end' expected");
                }

                stat = _if;
            }
            else if (reader.ConsumeKeyword("while"))
            {
                WhileStatement w = new WhileStatement(scope);

                // condition
                Expression nodeCond = ParseExpr(scope);

                // do
                if (!reader.ConsumeKeyword("do"))
                {
                    error("'do' expected");
                }

                // body
                List <Statement> body = ParseStatementList(scope);

                //end
                if (!reader.ConsumeKeyword("end"))
                {
                    error("'end' expected");
                }


                // return
                w.Condition = nodeCond;
                w.Body      = body;
                stat        = w;
            }
            else if (reader.ConsumeKeyword("do"))
            {
                // do block
                List <Statement> b = ParseStatementList(scope);

                if (!reader.ConsumeKeyword("end"))
                {
                    error("'end' expected");
                }

                stat = new DoStatement(scope)
                {
                    Body = b
                };
            }
            else if (reader.ConsumeKeyword("for"))
            {
                //for block
                if (!reader.Is(TokenType.Ident))
                {
                    error("<ident> expected");
                }

                Token baseVarName = reader.Get();
                if (reader.ConsumeSymbol('='))
                {
                    //numeric for
                    NumericForStatement forL   = new NumericForStatement(scope);
                    Variable            forVar = new Variable()
                    {
                        Name = baseVarName.Data
                    };
                    forL.Scope.AddLocal(forVar);

                    Expression startEx = ParseExpr(scope);

                    if (!reader.ConsumeSymbol(','))
                    {
                        error("',' expected");
                    }

                    Expression endEx = ParseExpr(scope);

                    Expression stepEx = null;
                    if (reader.ConsumeSymbol(','))
                    {
                        stepEx = ParseExpr(scope);
                    }
                    if (!reader.ConsumeKeyword("do"))
                    {
                        error("'do' expected");
                    }


                    List <Statement> body = ParseStatementList(forL.Scope);

                    if (!reader.ConsumeKeyword("end"))
                    {
                        error("'end' expected");
                    }


                    forL.Variable = forVar;
                    forL.Start    = startEx;
                    forL.End      = endEx;
                    forL.Step     = stepEx;
                    forL.Body     = body;
                    stat          = forL;
                }
                else
                {
                    // generic for
                    GenericForStatement forL = new GenericForStatement(scope);

                    List <Variable> varList = new List <Variable> {
                        forL.Scope.CreateLocal(baseVarName.Data)
                    };
                    while (reader.ConsumeSymbol(','))
                    {
                        if (!reader.Is(TokenType.Ident))
                        {
                            error("for variable expected");
                        }

                        varList.Add(forL.Scope.CreateLocal(reader.Get().Data));
                    }
                    if (!reader.ConsumeKeyword("in"))
                    {
                        error("'in' expected");
                    }

                    List <Expression> generators = new List <Expression>();
                    Expression        first      = ParseExpr(scope);

                    generators.Add(first);
                    while (reader.ConsumeSymbol(','))
                    {
                        Expression gen = ParseExpr(scope);
                        generators.Add(gen);
                    }
                    if (!reader.ConsumeKeyword("do"))
                    {
                        error("'do' expected");
                    }

                    List <Statement> body = ParseStatementList(forL.Scope);

                    if (!reader.ConsumeKeyword("end"))
                    {
                        error("'end' expected");
                    }

                    forL.VariableList = varList;
                    forL.Generators   = generators;
                    forL.Body         = body;
                    stat = forL;
                }
            }
            else if (reader.ConsumeKeyword("repeat"))
            {
                List <Statement> body = ParseStatementList(scope);

                if (!reader.ConsumeKeyword("until"))
                {
                    error("'until' expected");
                }

                Expression cond = ParseExpr(scope);

                RepeatStatement r = new RepeatStatement(scope);
                r.Condition = cond;
                r.Body      = body;
                stat        = r;
            }
            else if (reader.ConsumeKeyword("function"))
            {
                if (!reader.Is(TokenType.Ident))
                {
                    error("function name expected");
                }

                Expression name = ParseSuffixedExpr(scope, true);
                // true: only dots and colons

                FunctionStatement func = ParseFunctionArgsAndBody(scope);

                func.IsLocal = false;
                func.Name    = name;
                stat         = func;
            }
            else if (reader.ConsumeKeyword("local"))
            {
                if (reader.Is(TokenType.Ident))
                {
                    List <string> varList = new List <string> {
                        reader.Get().Data
                    };
                    while (reader.ConsumeSymbol(','))
                    {
                        if (!reader.Is(TokenType.Ident))
                        {
                            error("local variable name expected");
                        }
                        varList.Add(reader.Get().Data);
                    }

                    List <Expression> initList = new List <Expression>();
                    if (reader.ConsumeSymbol('='))
                    {
                        do
                        {
                            Expression ex = ParseExpr(scope);
                            initList.Add(ex);
                        } while (reader.ConsumeSymbol(','));
                    }

                    //now patch var list
                    //we can't do this before getting the init list, because the init list does not
                    //have the locals themselves in scope.
                    List <Expression> newVarList = new List <Expression>();
                    for (int i = 0; i < varList.Count; i++)
                    {
                        Variable x = scope.CreateLocal(varList[i]);
                        newVarList.Add(new VariableExpression {
                            Var = x
                        });
                    }

                    AssignmentStatement l = new AssignmentStatement();
                    l.Lhs     = newVarList;
                    l.Rhs     = initList;
                    l.IsLocal = true;
                    stat      = l;
                }
                else if (reader.ConsumeKeyword("function"))
                {
                    if (!reader.Is(TokenType.Ident))
                    {
                        error("Function name expected");
                    }
                    string   name     = reader.Get().Data;
                    Variable localVar = scope.CreateLocal(name);

                    FunctionStatement func = ParseFunctionArgsAndBody(scope);

                    func.Name = new VariableExpression {
                        Var = localVar
                    };
                    func.IsLocal = true;
                    stat         = func;
                }
                else
                {
                    error("local variable or function definition expected");
                }
            }
#if !VANILLA_LUA
            else if (reader.ConsumeSymbol("::"))
            {
                if (!reader.Is(TokenType.Ident))
                {
                    error("label name expected");
                }

                string label = reader.Get().Data;
                if (!reader.ConsumeSymbol("::"))
                {
                    error("'::' expected");
                }

                LabelStatement l = new LabelStatement();
                l.Label = label;
                stat    = l;
            }
#endif
            else if (reader.ConsumeKeyword("return"))
            {
                List <Expression> exprList = new List <Expression>();
                if (!reader.IsKeyword("end") && !reader.IsEof())
                {
                    Expression firstEx = ParseExpr(scope);
                    exprList.Add(firstEx);
                    while (reader.ConsumeSymbol(','))
                    {
                        Expression ex = ParseExpr(scope);
                        exprList.Add(ex);
                    }
                }
                ReturnStatement r = new ReturnStatement();
                r.Arguments = exprList;
                stat        = r;
            }
            else if (reader.ConsumeKeyword("break"))
            {
                stat = new BreakStatement();
            }
            else if (reader.ConsumeKeyword("continue"))
            {
                stat = new ContinueStatement();
            }
#if !VANILLA_LUA
            else if (reader.ConsumeKeyword("goto"))
            {
                if (!reader.Is(TokenType.Ident))
                {
                    error("label expected");
                }

                string        label = reader.Get().Data;
                GotoStatement g     = new GotoStatement();
                g.Label = label;
                stat    = g;
            }
            else if (reader.ConsumeKeyword("using"))
            {
                // using <a, b = 1, x()> do <statements> end
                UsingStatement us = new UsingStatement(scope);
                us.Scope = new Scope(scope);

                List <Expression> lhs = new List <Expression> {
                    ParseExpr(us.Scope)
                };
                while (reader.ConsumeSymbol(','))
                {
                    lhs.Add(ParseSuffixedExpr(us.Scope, true));
                }

                // equals
                if (!reader.ConsumeSymbol('='))
                {
                    error("'=' expected");
                }

                //rhs
                List <Expression> rhs = new List <Expression>();
                rhs.Add(ParseExpr(us.Scope));
                while (reader.ConsumeSymbol(','))
                {
                    rhs.Add(ParseExpr(scope));
                }

                AssignmentStatement a = new AssignmentStatement();
                a.Lhs     = lhs;
                a.Rhs     = rhs;
                a.IsLocal = true;

                if (!reader.ConsumeKeyword("do"))
                {
                    error("'do' expected");
                }

                List <Statement> block = ParseStatementList(us.Scope);

                if (!reader.ConsumeKeyword("end"))
                {
                    error("'end' expected");
                }

                us.Vars = a;
                us.Body = block;
                stat    = us;
            }
#endif
            else
            {
                // statementParseExpr
                Expression suffixed = ParseSuffixedExpr(scope);
                // assignment or call?
                if (reader.IsSymbol(',') || reader.IsSymbol('='))
                {
                    // check that it was not parenthesized, making it not an lvalue
                    if (suffixed.ParenCount > 0)
                    {
                        error("Can not assign to parenthesized expression, it is not an lvalue");
                    }

                    // more processing needed
                    List <Expression> lhs = new List <Expression> {
                        suffixed
                    };
                    while (reader.ConsumeSymbol(','))
                    {
                        lhs.Add(ParseSuffixedExpr(scope));
                    }

                    // equals
                    if (!reader.ConsumeSymbol('='))
                    {
                        error("'=' expected");
                    }

                    //rhs
                    List <Expression> rhs = new List <Expression>();
                    rhs.Add(ParseExpr(scope));
                    while (reader.ConsumeSymbol(','))
                    {
                        rhs.Add(ParseExpr(scope));
                    }

                    AssignmentStatement a = new AssignmentStatement();
                    a.Lhs = lhs;
                    a.Rhs = rhs;
                    stat  = a;
                }
#if !VANILLA_LUA
                else if (isAugmentedAssignment(reader.Peek()))
                {
                    AugmentedAssignmentStatement aas = new AugmentedAssignmentStatement();
                    Expression left        = suffixed;
                    Expression right       = null;
                    string     augmentedOp = reader.Get().Data;
                    right = ParseExpr(scope);
                    BinOpExpr nRight = new BinOpExpr();
                    nRight.Lhs = left;
                    nRight.Op  = augmentedOp.Substring(0, augmentedOp.Length - 1); // strip the '='
                    nRight.Rhs = right;

                    aas.Lhs = new List <Expression> {
                        left
                    };
                    aas.Rhs = new List <Expression> {
                        nRight
                    };
                    stat = aas;
                }
#endif
                else if (suffixed is CallExpr ||
                         suffixed is TableCallExpr ||
                         suffixed is StringCallExpr)
                {
                    //it's a call statement
                    CallStatement c = new CallStatement();
                    c.Expression = suffixed;
                    stat         = c;
                }
                else
                {
                    error("assignment statement expected");
                }
            }

            stat.ScannedTokens = reader.Range(startP, reader.p);
            if (reader.Peek().Data == ";" && reader.Peek().Type == TokenType.Symbol)
            {
                stat.HasSemicolon   = true;
                stat.SemicolonToken = reader.Get();
            }
            if (stat.Scope == null)
            {
                stat.Scope = scope;
            }
            stat.LineNumber = startLine;
            return(stat);
        }
Beispiel #59
0
		public void VisitWhileStatement(WhileStatement whileStatement)
		{
			StartNode(whileStatement);
			WriteKeyword(WhileStatement.WhileKeywordRole);
			Space(policy.SpaceBeforeWhileParentheses);
			LPar();
			Space(policy.SpacesWithinWhileParentheses);
			whileStatement.Condition.AcceptVisitor(this);
			Space(policy.SpacesWithinWhileParentheses);
			RPar();
			WriteEmbeddedStatement(whileStatement.EmbeddedStatement);
			EndNode(whileStatement);
		}
Beispiel #60
0
 public override void VisitWhileStatement(WhileStatement whileStatement)
 {
     new WhileBlock(this, whileStatement).Emit();
 }