public override void OnForStatement(ForStatement node)
		{
			if (node.LexicalInfo.Line <= resolver.CaretLine && GetEndSourceLocation(node).Line >= resolver.CaretLine - 1) {
				foreach (Declaration decl in node.Declarations) {
					IterationDeclarationFound(decl.Name, decl.Type, node.Iterator, node.LexicalInfo);
				}
			}
			base.OnForStatement(node);
		}
Esempio n. 2
0
 public object VisitForeachStatement(ForeachStatement foreachStatement, object data)
 {
     B.ForStatement fs = new B.ForStatement(GetLexicalInfo(foreachStatement));
     fs.EndSourceLocation = GetLocation(foreachStatement.EndLocation);
     fs.Iterator          = ConvertExpression(foreachStatement.Expression);
     fs.Declarations.Add(new B.Declaration(foreachStatement.VariableName, ConvertTypeReference(foreachStatement.TypeReference)));
     fs.Block = ConvertBlock(foreachStatement.EmbeddedStatement);
     return(fs);
 }
        public override void LeaveForStatement(ForStatement node)
        {
            //do not optimize local-reusing loops (BOO-1111)
            //TODO: optimize anyway (modify end value to match generator model vs optimized model)
            if (node.Declarations.Count == 1
                && null != AstUtil.GetLocalByName(_currentMethod, node.Declarations[0].Name))
                return;

            CheckForItemInRangeLoop(node);
            CheckForItemInArrayLoop(node);
        }
Esempio n. 4
0
        public object VisitForNextStatement(ForNextStatement forNextStatement, object data)
        {
            if (forNextStatement.TypeReference.IsNull)
            {
                return(MakeManualLoop(forNextStatement));
            }
            B.ForStatement fs = new B.ForStatement(GetLexicalInfo(forNextStatement));
            fs.Block = ConvertBlock(forNextStatement.EmbeddedStatement);
            fs.Declarations.Add(new B.Declaration(forNextStatement.VariableName, null));
            B.Expression start = ConvertExpression(forNextStatement.Start);
            Expression   end   = forNextStatement.End;

            if (forNextStatement.Step == null || forNextStatement.Step.IsNull)
            {
                // range only goes to end - 1, so increment end
                end         = Expression.AddInteger(end, 1);
                fs.Iterator = MakeMethodCall("range", start, ConvertExpression(end));
            }
            else
            {
                PrimitiveExpression stepPE = forNextStatement.Step as PrimitiveExpression;
                if (stepPE == null || !(stepPE.Value is int))
                {
                    AddError(forNextStatement, "Step must be an integer literal");
                }
                else
                {
                    if ((int)stepPE.Value < 0)
                    {
                        end = Expression.AddInteger(end, -1);
                    }
                    else
                    {
                        end = Expression.AddInteger(end, 1);
                    }
                }
                fs.Iterator = MakeMethodCall("range", start, ConvertExpression(end), ConvertExpression(forNextStatement.Step));
            }
            return(fs);
        }
 public Statement for_in(Block container)
 {
     Statement stmt = null;
     try
     {
         Declaration declaration2;
         Block block;
         int num = this.LA(1);
         switch (num)
         {
             case 12:
             case 0x10:
             case 0x21:
             case 0x3b:
             {
                 IToken token = this.identifier();
                 if (base.inputState.guessing == 0)
                 {
                     Declaration declaration;
                     Declaration declaration1 = declaration = new Declaration(ToLexicalInfo(token));
                     declaration.set_Name(token.getText());
                     declaration2 = declaration;
                 }
                 break;
             }
             default:
                 if (num != 0x2d)
                 {
                     throw new NoViableAltException(this.LT(1), this.getFilename());
                 }
                 declaration2 = this.declaration();
                 if (base.inputState.guessing == 0)
                 {
                     DeclarationAnnotations.ForceNewVariable(declaration2);
                 }
                 break;
         }
         this.match(0x18);
         Expression expression = this.expression();
         if (base.inputState.guessing == 0)
         {
             ForStatement statement2;
             ForStatement statement1 = statement2 = new ForStatement();
             statement2.set_Iterator(expression);
             ForStatement statement3 = statement2;
             statement3.get_Declarations().Add(declaration2);
             block = statement3.get_Block();
             stmt = statement3;
             container.Add(stmt);
             this.EnterLoop(stmt);
         }
         this.match(0x40);
         this.compound_or_single_stmt(block);
         if (base.inputState.guessing == 0)
         {
             this.LeaveLoop(stmt);
         }
     }
     catch (RecognitionException exception)
     {
         if (base.inputState.guessing != 0)
         {
             throw;
         }
         this.reportError(exception);
         this.recover(exception, tokenSet_15_);
         return stmt;
     }
     return stmt;
 }
		public object VisitForNextStatement(ForNextStatement forNextStatement, object data)
		{
			if (forNextStatement.TypeReference.IsNull)
				return MakeManualLoop(forNextStatement);
			B.ForStatement fs = new B.ForStatement(GetLexicalInfo(forNextStatement));
			fs.Block = ConvertBlock(forNextStatement.EmbeddedStatement);
			fs.Declarations.Add(new B.Declaration(forNextStatement.VariableName, null));
			B.Expression start = ConvertExpression(forNextStatement.Start);
			Expression end = forNextStatement.End;
			if (forNextStatement.Step == null || forNextStatement.Step.IsNull) {
				// range only goes to end - 1, so increment end
				end = Expression.AddInteger(end, 1);
				fs.Iterator = MakeMethodCall("range", start, ConvertExpression(end));
			} else {
				PrimitiveExpression stepPE = forNextStatement.Step as PrimitiveExpression;
				if (stepPE == null || !(stepPE.Value is int)) {
					AddError(forNextStatement, "Step must be an integer literal");
				} else {
					if ((int)stepPE.Value < 0)
						end = Expression.AddInteger(end, -1);
					else
						end = Expression.AddInteger(end, 1);
				}
				fs.Iterator = MakeMethodCall("range", start, ConvertExpression(end), ConvertExpression(forNextStatement.Step));
			}
			return fs;
		}
Esempio n. 7
0
 public override void OnForStatement(ForStatement node)
 {
     base.OnForStatement(node);
 }
Esempio n. 8
0
        public override void OnExtendedGeneratorExpression(ExtendedGeneratorExpression node)
        {
            BlockExpression block = new BlockExpression(node.LexicalInfo);

            Block body = block.Body;
            Expression e = node.Items[0].Expression;
            foreach (GeneratorExpression ge in node.Items)
            {
                ForStatement fs = new ForStatement(ge.LexicalInfo);
                fs.Iterator = ge.Iterator;
                fs.Declarations = ge.Declarations;

                body.Add(fs);

                if (null == ge.Filter)
                {
                    body = fs.Block;
                }
                else
                {
                    fs.Block.Add(
                        NormalizeStatementModifiers.MapStatementModifier(ge.Filter, out body));
                }

            }
            body.Add(new YieldStatement(e.LexicalInfo, e));

            MethodInvocationExpression mie = new MethodInvocationExpression(node.LexicalInfo);
            mie.Target = block;

            Node parentNode = node.ParentNode;
            bool isGenerator = AstUtil.IsListMultiGenerator(parentNode);
            parentNode.Replace(node, mie);
            mie.Accept(this);

            if (isGenerator)
            {
                parentNode.ParentNode.Replace(
                    parentNode,
                    CodeBuilder.CreateConstructorInvocation(
                        TypeSystemServices.Map(ProcessGenerators.List_IEnumerableConstructor),
                        mie));
            }
        }
 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);
 }
Esempio n. 10
0
 public override void OnForStatement(ForStatement fs)
 {
     WriteIndented();
     WriteKeyword("for ");
     for (int i=0; i<fs.Declarations.Count; ++i)
     {
         if (i > 0) { Write(", "); }
         Visit(fs.Declarations[i]);
     }
     WriteKeyword(" in ");
     Visit(fs.Iterator);
     WriteLine(":");
     WriteBlock(fs.Block);
     if(fs.OrBlock != null)
     {
         WriteIndented();
         WriteKeyword("or:");
         WriteLine();
         WriteBlock(fs.OrBlock);
     }
     if(fs.ThenBlock != null)
     {
         WriteIndented();
         WriteKeyword("then:");
         WriteLine();
         WriteBlock(fs.ThenBlock);
     }
 }
Esempio n. 11
0
 protected void VisitForStatementBlock(ForStatement node)
 {
     EnterForNamespace(node);
     Visit(node.Block);
     Visit(node.OrBlock);
     Visit(node.ThenBlock);
     LeaveNamespace();
 }
Esempio n. 12
0
		override public object Clone()
		{
		
			ForStatement clone = new ForStatement();
			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 != _declarations)
			{
				clone._declarations = _declarations.Clone() as DeclarationCollection;
				clone._declarations.InitializeParent(clone);
			}
			if (null != _iterator)
			{
				clone._iterator = _iterator.Clone() as Expression;
				clone._iterator.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;


		}
Esempio n. 13
0
 public override void OnForStatement(ForStatement node)
 {
     VisitLoop(node.Block);
 }
 private LabelStatement CreateUpdateLabel(ForStatement node)
 {
     return new LabelStatement(LexicalInfo.Empty, "$label$" + _context.AllocIndex());
 }
 public override void LeaveForStatement(ForStatement node)
 {
     CheckForItemInRangeLoop(node);
     CheckForItemInArrayLoop(node);
 }
Esempio n. 16
0
		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);
		}
Esempio n. 17
0
        protected override Statement ExpandImpl(MacroStatement macro){
            if (macro.Arguments.Count == 0){
                throw new Exception("need at least one IEnumerable parameter");
            }

            var result = new Block();
            Expression src = macro.Arguments[0];

            var idx = new ReferenceExpression("_idx");
            Expression item = new ReferenceExpression("i");
            var col = new ReferenceExpression("current_collection");
            if (src is BinaryExpression){
                item = ((BinaryExpression) src).Left;
                src = ((BinaryExpression) src).Right;
            }

            if (macro.Arguments.Count > 1){
                idx = (ReferenceExpression) macro.Arguments[1];
            }

            string prefix = macro.get<string>("_prefix") ?? "";
            string suffix = macro.get<string>("_suffix") ?? "";


            Func<string, MacroStatement> findmacro = s =>{
                                                         var r = macro.get<Node>(s);
                                                         if (null == r){
                                                             return null;
                                                         }
                                                         if (!(r is MacroStatement)){
                                                             var m = new MacroStatement("stub");
                                                             m.Body = new Block().add(r);
                                                             r = m;
                                                         }

                                                         return (MacroStatement) r;
                                                     };
            Func<MacroStatement, Block> extract = m =>{
                                                      if (null == m){
                                                          return null;
                                                      }
                                                      if (m.Body != null && !m.Body.IsEmpty){
                                                          if (m.Body.Statements.Count == 1){
                                                              if (m.Body.Statements[0] is ExpressionStatement){
                                                                  Expression _ex =
                                                                      ((ExpressionStatement) m.Body.Statements[0]).
                                                                          Expression;
                                                                  if (_ex is LiteralExpression ||
                                                                      !_ex.ToCodeString().ToLower().StartsWith("out")){
                                                                      return new Block().add(_ex.writeOut());
                                                                  }
                                                              }
                                                          }
                                                          return m.Body;
                                                      }
                                                      if (m.Arguments.Count == 0){
                                                          return null;
                                                      }
                                                      var r = new Block();
                                                      if (!(m.Arguments[0] is MethodInvocationExpression)){
                                                          r.Add(BrailBuildingHelper.WriteOut(m.Arguments[0]));
                                                      }
                                                      else{
                                                          r.Add(m.Arguments[0]);
                                                      }

                                                      return r;
                                                  };

            MacroStatement beforeall_macro = findmacro("beforeall");
            MacroStatement onitem_macro = findmacro("onitem") ?? macro;
            MacroStatement onerror_macro = findmacro("onerror");
            ;
            MacroStatement between_macro = findmacro("between");
            ;
            MacroStatement afterall_macro = findmacro("afterall");
            ;
            MacroStatement onempty_macro = findmacro("onempty");
            ;
            MacroStatement beforeeach_macro = findmacro("beforeeach");
            ;
            MacroStatement aftereach_macro = findmacro("aftereach");

            MacroStatement prepare_macro = findmacro("prepare");
            ;

            Block beforeall = extract(beforeall_macro);
            Block onitem = extractMainItemBlock(macro, extract, onitem_macro, item, prefix, suffix);
            Block onerror = extract(onerror_macro);
            Block between = extract(between_macro);
            Block afterall = extract(afterall_macro);
            Block onempty = null;

            bool proceed_on_empty = false;
            if (onempty_macro != null && onempty_macro.Arguments.Count != 0 &&
                onempty_macro.Arguments[0].ToCodeString() == "proceed"){
                proceed_on_empty = true;
            }
            else{
                onempty = extract(onempty_macro);
            }
            Block beforeeach = extract(beforeeach_macro);
            Block aftereach = extract(aftereach_macro);


//          _idx = 0

            Statement betweener = getBetweener(idx, between);
            result.Add(col.assign(new MethodInvocationExpression(new ReferenceExpression("_wrapcollection"), src)));
            result.Add(new ReferenceExpression("___proceed").assign(new BoolLiteralExpression(proceed_on_empty)));
            var mainblock = new Block();
            mainblock.Add(idx.assign(0));
            mainblock.Add(new IfStatement(
                              new BinaryExpression(BinaryOperatorType.Equality, new NullLiteralExpression(), col),
                              new Block().add(new BinaryExpression(BinaryOperatorType.Assign, col,
                                                                   new MethodInvocationExpression(
                                                                       new ReferenceExpression("_wrapcollection"),
                                                                       new ArrayLiteralExpression()))),
                              null
                              ));
            if (beforeall != null){
                mainblock.Add(beforeall);
            }
            var maincycle = new ForStatement();
            maincycle.Iterator = col;
            string declname = item.ToCodeString();
            TypeReference decltype = null;
            if (item is TryCastExpression){
                declname = ((TryCastExpression) item).Target.ToCodeString();
                decltype = ((TryCastExpression) item).Type;
            }
            maincycle.Declarations.Add(new Declaration(maincycle.LexicalInfo, declname, decltype));
            maincycle.Block = new Block();
            maincycle.ThenBlock = afterall;

            if (betweener != null){
                maincycle.Block.Add(betweener);
            }
            if (null != prepare_macro){
                maincycle.Block.Add(prepare_macro.Body);
            }
            if (null != beforeeach){
                maincycle.Block.Add(beforeeach);
            }
            if (onerror == null){
                maincycle.Block.Add(onitem);
            }
            else{
                var trycatch = new TryStatement();
                var exchandler = new ExceptionHandler();
                exchandler.Block = onerror;
                exchandler.Declaration = new Declaration("_ex", new SimpleTypeReference("System.Exception"));
                trycatch.ProtectedBlock = onitem;
                trycatch.ExceptionHandlers.Add(exchandler);
                maincycle.Block.Add(trycatch);
            }
            if (null != aftereach){
                maincycle.Block.Add(aftereach);
            }
            maincycle.Block.Add(new UnaryExpression(UnaryOperatorType.Increment, idx));

            mainblock.Add(maincycle);

            result.Add(
                new IfStatement(
                    getMainCondition(col),
                    mainblock,
                    onempty
                    )
                );

//          if null!=items and (items as IEnumerable).Cast[of System.Object]().Count() != 0:

            return result;
        }
Esempio n. 18
0
        //throws RecognitionException, TokenStreamException
        protected ForStatement for_stmt()
        {
            ForStatement fs;

            IToken  f = null;
            IToken  or = null;
            IToken  et = null;

                fs = null;
                Expression iterator = null;
                DeclarationCollection declarations = null;
                Block body = null;

            try {      // for error handling
            f = LT(1);
            match(FOR);
            if (0==inputState.guessing)
            {

                        fs = new ForStatement(ToLexicalInfo(f));
                        declarations = fs.Declarations;
                        body = fs.Block;

            }
            declaration_list(declarations);
            match(IN);
            iterator=array_or_expression();
            if (0==inputState.guessing)
            {
                fs.Iterator = iterator;
            }
            compound_stmt(body);
            {
                switch ( LA(1) )
                {
                case OR:
                {
                    or = LT(1);
                    match(OR);
                    if (0==inputState.guessing)
                    {
                        fs.OrBlock = new Block(ToLexicalInfo(or));
                    }
                    compound_stmt(fs.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)
                    {
                        fs.ThenBlock = new Block(ToLexicalInfo(et));
                    }
                    compound_stmt(fs.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 fs;
        }
Esempio n. 19
0
		override public void OnForStatement(ForStatement node)
		{
			VisitLoop(node.Block);
			Visit(node.OrBlock);
			Visit(node.ThenBlock);
		}
Esempio n. 20
0
 public override void OnForStatement(ForStatement node)
 {
     NotImplemented("ForStatement");
 }
Esempio n. 21
0
 public override void OnForStatement(ForStatement node)
 {
 }
		public object VisitForeachStatement(ForeachStatement foreachStatement, object data)
		{
			B.ForStatement fs = new B.ForStatement(GetLexicalInfo(foreachStatement));
			fs.EndSourceLocation = GetLocation(foreachStatement.EndLocation);
			fs.Iterator = ConvertExpression(foreachStatement.Expression);
			fs.Declarations.Add(new B.Declaration(foreachStatement.VariableName, ConvertTypeReference(foreachStatement.TypeReference)));
			fs.Block = ConvertBlock(foreachStatement.EmbeddedStatement);
			return fs;
		}
 public override void OnForStatement(ForStatement node)
 {
     this.OnLoopBody(node.get_Block());
 }
        /// <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);
        }
Esempio n. 25
0
        //throws RecognitionException, TokenStreamException
        protected ForStatement for_stmt()
        {
            ForStatement fs;

            IToken  f = null;
            IToken  or = null;
            IToken  et = null;

                fs = null;
                Expression iterator = null;
                DeclarationCollection declarations = null;
                Block body = null;
                Block lastBlock = null;

            try {      // for error handling
            f = LT(1);
            match(FOR);
            if (0==inputState.guessing)
            {

                        fs = new ForStatement(SourceLocationFactory.ToLexicalInfo(f));
                        declarations = fs.Declarations;
                        lastBlock = body = fs.Block;

            }
            declaration_list(declarations);
            match(IN);
            iterator=array_or_expression();
            if (0==inputState.guessing)
            {
                fs.Iterator = iterator;
            }
            begin();
            block(body.Statements);
            {
                switch ( LA(1) )
                {
                case OR:
                {
                    or = LT(1);
                    match(OR);
                    if (0==inputState.guessing)
                    {
                        lastBlock = fs.OrBlock = new Block(SourceLocationFactory.ToLexicalInfo(or));
                    }
                    begin();
                    block(fs.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 = fs.ThenBlock = new Block(SourceLocationFactory.ToLexicalInfo(et));
                    }
                    begin();
                    block(fs.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 fs;
        }
        /// <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);
        }
Esempio n. 27
0
	protected ForStatement  for_stmt() //throws RecognitionException, TokenStreamException
{
		ForStatement fs;
		
		IToken  f = null;
		IToken  or = null;
		IToken  et = null;
		
				fs = null;
				Expression iterator = null;
				DeclarationCollection declarations = null;
				Block body = null;
			
		
		try {      // for error handling
			f = LT(1);
			match(FOR);
			if (0==inputState.guessing)
			{
				
						fs = new ForStatement(ToLexicalInfo(f));
						declarations = fs.Declarations;
						body = fs.Block;
					
			}
			declaration_list(declarations);
			match(IN);
			iterator=array_or_expression();
			if (0==inputState.guessing)
			{
				fs.Iterator = iterator;
			}
			compound_stmt(body);
			{
				switch ( LA(1) )
				{
				case OR:
				{
					or = LT(1);
					match(OR);
					if (0==inputState.guessing)
					{
						fs.OrBlock = new Block(ToLexicalInfo(or));
					}
					compound_stmt(fs.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)
					{
						fs.ThenBlock = new Block(ToLexicalInfo(et));
					}
					compound_stmt(fs.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, "for_stmt");
				recover(ex,tokenSet_84_);
			}
			else
			{
				throw ex;
			}
		}
		return fs;
	}
 private LabelStatement CreateUpdateLabel(ForStatement node)
 {
     return new LabelStatement(LexicalInfo.Empty, Context.GetUniqueName("label"));
 }
Esempio n. 29
0
 private void EnterForNamespace(ForStatement node)
 {
     EnterNamespace(new DeclarationsNamespace(CurrentNamespace, node.Declarations));
 }
 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);
 }
Esempio n. 31
0
 public override void OnForStatement(ForStatement node)
 {
     Visit(node.Iterator);
     node.Iterator = ProcessIterator(node.Iterator, node.Declarations);
     VisitForStatementBlock(node);
 }
 public void ProcessUpdateableIteration(ForStatement node)
 {
     Expression expression = node.get_Iterator();
     MethodInvocationExpression expression2 = this.get_CodeBuilder().CreateMethodInvocation(this._UnityRuntimeServices_GetEnumerator, node.get_Iterator());
     expression2.set_LexicalInfo(new LexicalInfo(node.get_Iterator().get_LexicalInfo()));
     node.set_Iterator(expression2);
     this.ProcessDeclarationForIterator(node.get_Declarations().get_Item(0), this.GetEnumeratorItemType(this.GetExpressionType(expression)));
     this.VisitForStatementBlock(node);
     this.TransformIteration(node);
 }