Add() публичный Метод

public Add ( Block block ) : void
block Block
Результат void
Пример #1
0
		public Statement Expand(IEnumerable<Node> generator)
		{
			Block resultingBlock = new Block();
			foreach (Node node in generator)
			{
				//'yield' (ie. implicit 'yield null') means 'yield `macro`.Body'
				Node generatedNode = node ?? _node.Body;
				if (null == generatedNode)
					continue;

				TypeMember member = generatedNode as TypeMember;
				if (null != member)
				{
					ExpandTypeMember(member, resultingBlock);
					continue;
				}

				Block block = generatedNode as Block;
				if (null != block)
				{
					resultingBlock.Add(block);
					continue;
				}

				Statement statement = generatedNode as Statement;
				if (null != statement)
				{
					resultingBlock.Add(statement);
					continue;
				}

				Expression expression = generatedNode as Expression;
				if (null != expression)
				{
					resultingBlock.Add(expression);
					continue;
				}

				Import import = generatedNode as Import;
				if (null != import)
				{
					ExpandImport(import);
					continue;
				}

				throw new CompilerError(_node, "Unsupported expansion: " + generatedNode.ToCodeString());
			}

			return resultingBlock.IsEmpty
					? null
					: resultingBlock.Simplify();
		}
Пример #2
0
 protected override Statement ExpandImpl(MacroStatement macro){
     var result = new Block();
     Expression outvar = macro.Arguments.Count == 0 ? new ReferenceExpression("_out") : macro.Arguments[0];
     var tryer = new TryStatement();
     var protectblock = new Block();
     protectblock.add(new MethodInvocationExpression(new ReferenceExpression("_catchoutput")));
     protectblock.add(macro.Body);
     tryer.ProtectedBlock = protectblock;
     tryer.EnsureBlock =
         new Block().add(outvar.assign(new MethodInvocationExpression(new ReferenceExpression("_endcatchoutput"))));
     result.Add(outvar.assign(""));
     result.Add(tryer);
     return result;
 }
Пример #3
0
		public override Statement Expand(MacroStatement macro)
		{
			if (macro.Arguments.Count == 0)
				throw new MonoRailException("Section must be called with a name");

			MacroStatement component = GetParentComponent(macro);

			componentContextName = ComponentNaming.GetComponentContextName(component);
			componentVariableName = ComponentNaming.GetComponentNameFor(component);


			string sectionName = macro.Arguments[0].ToString();
			Block block = new Block();
			//if (!Component.SupportsSection(section.Name))
			//   throw new ViewComponentException( String.Format("The section '{0}' is not supported by the ViewComponent '{1}'", section.Name, ComponentName));
			MethodInvocationExpression supportsSection = new MethodInvocationExpression(
				AstUtil.CreateReferenceExpression(componentVariableName + ".SupportsSection"),
				new StringLiteralExpression(sectionName));
			//create the new exception
			RaiseStatement raiseSectionNotSupportted = new RaiseStatement(
				new MethodInvocationExpression(
					AstUtil.CreateReferenceExpression(typeof(ViewComponentException).FullName),
					new StringLiteralExpression(
						String.Format("The section '{0}' is not supported by the ViewComponent '{1}'", sectionName,
						              component.Arguments[0].ToString())
						)
					));

			Block trueBlock = new Block();
			trueBlock.Add(raiseSectionNotSupportted);
			IfStatement ifSectionNotSupported =
				new IfStatement(new UnaryExpression(UnaryOperatorType.LogicalNot, supportsSection),
				                trueBlock, null);
			block.Add(ifSectionNotSupported);
			//componentContext.RegisterSection(sectionName);
			MethodInvocationExpression mie = new MethodInvocationExpression(
				new MemberReferenceExpression(new ReferenceExpression(componentContextName), "RegisterSection"),
				new StringLiteralExpression(sectionName),
				CodeBuilderHelper.CreateCallableFromMacroBody(CodeBuilder, macro));
			block.Add(mie);

			IDictionary sections = (IDictionary) component["sections"];
			if (sections == null)
			{
				component["sections"] = sections = new Hashtable();
			}
			sections.Add(sectionName, block);
			return null;
		}
Пример #4
0
        protected override Statement ExpandImpl(MacroStatement macro){
            if (macro.Arguments.Count == 0)
            {
                Context.Errors.Add(new CompilerError(macro.LexicalInfo,
                                                     "call macro requires at least one reference or string attribute for action name"));
            }
            var basis = new ReferenceExpression("Html");
            var method = new MemberReferenceExpression(basis, "RenderAction");
            var call = new MethodInvocationExpression(method);
            int i = 0;
            var result = new Block();
            foreach (Expression argument in macro.Arguments){
                i++;
                Expression exp = argument;
                if (!(exp is HashLiteralExpression)){
//action and contrller parameters
                    if (!(exp is NullLiteralExpression)){
                        exp = new StringLiteralExpression(argument.ToCodeString());
                    }
                    call.Arguments.Add(exp);
                }
                else{
                    string name = "__rd";
                    result.Add(
                        new DeclarationStatement(
                            new Declaration(name, null),
                            new MethodInvocationExpression(AstUtil.CreateReferenceExpression("RouteValueDictionary"))
                            )
                        );
                    var dict = argument as HashLiteralExpression;
                    foreach (ExpressionPair item in dict.Items){
                        result.Add(
                            new MethodInvocationExpression(
                                AstUtil.CreateReferenceExpression(name + ".Add"),
                                item.First,
                                item.Second
                                )
                            );
                    }
                    if (i == 2){
                        call.Arguments.Add(new NullLiteralExpression());
                    }
                    call.Arguments.Add(AstUtil.CreateReferenceExpression(name));
                }
            }
            result.Add(call);
            return result;
        }
Пример #5
0
        public virtual Block ToBlock()
        {
            Block b = new Block(LexicalInfo);

            b.Add(this);
            return(b);
        }
Пример #6
0
        protected override Statement ExpandImpl(MacroStatement macro){
            var result = new Block();
            foreach (Statement st in macro.Body.Statements){
                var decl = st as DeclarationStatement;
                var refer = st as ExpressionStatement;
                if(null==decl){
                    var ex = refer.Expression;
                    if (ex is MethodInvocationExpression){
                        decl =
                            new DeclarationStatement(
                                new Declaration(((MethodInvocationExpression) refer.Expression).Target.ToCodeString(),
                                                null), null);
                    }
                    if(ex is BinaryExpression){
                        var b = ex as BinaryExpression;
                        decl = new DeclarationStatement(
                            new Declaration(b.Left.ToCodeString(),null),b.Right
                            );
                    }
                }

                var bin = new BinaryExpression(BinaryOperatorType.Assign,
                                               new TryCastExpression(new ReferenceExpression(decl.Declaration.Name),
                                                                     decl.Declaration.Type),
                                               decl.Initializer);
                var def = new MacroStatement("definebrailproperty");
                def.Arguments.Add(bin);
                result.Add(def);
            }
            return result;
        }
Пример #7
0
		public override Statement Expand(MacroStatement macro)
		{
			var codeBlock = new Block();

			// Castle.MonoRail.Views.Brail.DslProvider(BrailBase)
			var newDslWrapper = new MethodInvocationExpression
			{
				Target = AstUtil.CreateReferenceExpression("Castle.MonoRail.Views.Brail.DslProvider")
			};
			newDslWrapper.Arguments.Add(new SelfLiteralExpression());

			// dsl = Castle.MonoRail.Views.Brail.DslPRovider(BrailBase)
			var dslReference = AstUtil.CreateReferenceExpression("dsl");
			codeBlock.Add(new BinaryExpression(BinaryOperatorType.Assign, dslReference, newDslWrapper));

			if (macro.Arguments.Count == 1)
			{
				var language = LookupLanguageExtension(macro.Arguments[0].ToString());
				// LanguageExtension(OutputStream)
				var newLanguage = new MethodInvocationExpression
				{
					Target = AstUtil.CreateReferenceExpression(language)
				};
				newLanguage.Arguments.Add(AstUtil.CreateReferenceExpression("OutputStream"));

				var registerLanguage = new MethodInvocationExpression
				{
					Target = AstUtil.CreateReferenceExpression("dsl.Register")
				};
				registerLanguage.Arguments.Add(newLanguage);

				// dsl.Register(LanguageExtension(OutputStream))
				codeBlock.Add(registerLanguage);
			}

			// rewrite the remaining code to invoke methods on
			// the dsl reference
			var macroBlock = macro.Body;
			(new NameExpander(dslReference)).Visit(macroBlock);
			codeBlock.Add(macroBlock);
			// dsl.Flush();
			codeBlock.Add(new MethodInvocationExpression(AstUtil.CreateReferenceExpression("dsl.Flush")));
			return codeBlock;
		}
Пример #8
0
        void AddToBlock(Statement n, B.Block b)
        {
            object result = ConvertStatementInternal(n);

            if (result is ArrayList)
            {
                foreach (B.Statement stmt in (ArrayList)result)
                {
                    b.Add(stmt);
                }
            }
            else
            {
                B.Statement stmt = (B.Statement)result;
                if (stmt != null)
                {
                    b.Add(stmt);
                }
            }
        }
Пример #9
0
 public static Statement when(Expression expression)
 {
     var body = new Block(expression.LexicalInfo);
     body.Add(new ReturnStatement(expression));
     var result = new BlockExpression(body);
     result.Parameters.Add(
         new ParameterDeclaration("order",
                                  CurrentContext.CodeBuilder.CreateTypeReference(typeof(Order))));
     result.Parameters.Add(
         new ParameterDeclaration("customer",
                                  CurrentContext.CodeBuilder.CreateTypeReference(typeof(Customer))));
     return new ReturnStatement(result);
 }
Пример #10
0
        public static Block WriteOutCells(IEnumerable<CellDefinition> cells, bool header){
            string tagname = header ? "th" : "td";
            var onitem = new Block();
            foreach (CellDefinition cell in cells){
                var opentag = new ExpressionInterpolationExpression();
                ExpressionInterpolationExpression attrs = getAttributes(cell.Attributes);
                opentag.append("<" + tagname).append(attrs).append(">");
                onitem.add(opentag.writeOut());
                onitem.add(cell.Value.brailOutResolve());

                onitem.Add(("</" + tagname + ">").toLiteral().writeOut());
            }
            return onitem;
        }
Пример #11
0
        private void generateElement(XElement element, Block block) {
            var m = new MacroStatement(element.Name.LocalName);

            block.Add(m);

            //if ((!string.IsNullOrWhiteSpace(element.Value))) {
            //    generateText(element.Value, m.Body);
            //}

            IList<string> skips = new List<string>();
            skips.Add("_line");
            skips.Add("_file");
            if (element.Attribute("id") != null) {
                skips.Add("id");
                if(element.attr("code")==element.attr("id")) {
                    skips.Add("code");
                }
                m.Arguments.Add(getSimplified(element.attr("id")));
                if (element.Attribute("name") != null) {
                    m.Arguments.Add(getSimplified(element.attr("name")));
                    skips.Add("name");
                }
            }

            foreach (var attribute in element.Attributes()) {
                if (!skips.Contains(attribute.Name.LocalName)) {
                    generateAttribute(attribute, m.Body);
                }
            }
            foreach (var e in element.Nodes()) {
                if (e is XElement) {
                    generateElement((XElement)e, m.Body);
                }
                else if(e is XText){
                    generateText(((XText)e).Value,m.Body);
                }
            }
        }
Пример #12
0
 private void generateText(string value, Block block) {
     block.Add(new StringLiteralExpression(value));
 }
Пример #13
0
 private void generateAttribute(XAttribute attribute, Block block) {
     var exp = new BinaryExpression(BinaryOperatorType.Assign, new ReferenceExpression(attribute.Name.LocalName),
                                    getSimplified(attribute.Value));
     if (attribute.Name.LocalName == "type" || attribute.Name.LocalName == "code") {
         ((MacroStatement) block.ParentNode).Arguments.Add(exp);
     }
     else {
         block.Add(exp);
     }
 }
Пример #14
0
		public override Statement Expand(MacroStatement macro)
		{
			componentContextName = ComponentNaming.GetComponentContextName(macro);
			componentFactoryName = ComponentNaming.GetComponentFactoryName(macro);
			componentVariableName = ComponentNaming.GetComponentNameFor(macro);

			if (macro.Arguments.Count == 0) throw new MonoRailException("Component must be called with a name");

			var block = new Block();

			var method = (Method) macro.GetAncestor(NodeType.Method);

			var componentName = new StringLiteralExpression(macro.Arguments[0].ToString());

			var dictionary = CreateParametersDictionary(macro);

			var macroBody = CodeBuilderHelper.CreateCallableFromMacroBody(CodeBuilder, macro);

			var initContext = new MethodInvocationExpression
			{
				Target = AstUtil.CreateReferenceExpression("Castle.MonoRail.Views.Brail.BrailViewComponentContext")
			};
			initContext.Arguments.Extend(
				new[]
					{
						new SelfLiteralExpression(),
						macroBody, componentName,
						AstUtil.CreateReferenceExpression("OutputStream"),
						dictionary
					});

			// compilerContext = BrailViewComponentContext(macroBodyClosure, "componentName", OutputStream, dictionary)
			block.Add(new BinaryExpression(BinaryOperatorType.Assign,
			                               new ReferenceExpression(componentContextName), initContext));

			// AddViewComponentProperties( compilerContext.ComponentParams )
			var addProperties =
				new MethodInvocationExpression(AstUtil.CreateReferenceExpression("AddViewComponentProperties"));
			addProperties.Arguments.Add(AstUtil.CreateReferenceExpression(componentContextName + ".ComponentParameters"));
			block.Add(addProperties);

			var viewComponentFactoryLocal = CodeBuilder.DeclareLocal(method, componentFactoryName,
			                                                                   TypeSystemServices.Map(
			                                                                   	typeof(IViewComponentFactory)));

			// viewComponentFactory = context.GetService(IViewComponentFactory)
			var callService = new MethodInvocationExpression(
				AstUtil.CreateReferenceExpression("context.GetService"));
			callService.Arguments.Add(CodeBuilder.CreateTypeofExpression(typeof(IViewComponentFactory)));

			block.Add(new BinaryExpression(BinaryOperatorType.Assign,
			                               CodeBuilder.CreateLocalReference(componentFactoryName, viewComponentFactoryLocal),
			                               callService));

			// component = viewComponentFactory.Create( componentName)
			var createComponent = new MethodInvocationExpression(
				new MemberReferenceExpression(CodeBuilder.CreateLocalReference(componentFactoryName, viewComponentFactoryLocal),
				                              "Create"));
			createComponent.Arguments.Add(componentName);
			block.Add(new BinaryExpression(BinaryOperatorType.Assign,
			                               new ReferenceExpression(componentVariableName),
			                               createComponent));
			AddSections(block, macro);

			// component.Init(context, componentContext)
			var initComponent = new MethodInvocationExpression(
				AstUtil.CreateReferenceExpression(componentVariableName + ".Init"));
			initComponent.Arguments.Extend(
				new Expression[]
					{
						new ReferenceExpression("context"),
						new ReferenceExpression(componentContextName)
					});

			block.Add(initComponent);

			// component.Render()
			block.Add(new MethodInvocationExpression(
			          	AstUtil.CreateReferenceExpression(componentVariableName + ".Render")));

			// if component.ViewToRender is not null:
			//	OutputSubView("/"+component.ViewToRender, context.CompnentParameters)
			var renderView = new Block();
			var outputSubView = new MethodInvocationExpression(
				AstUtil.CreateReferenceExpression("OutputSubView"));
			outputSubView.Arguments.Add(new BinaryExpression(BinaryOperatorType.Addition,
			                                                 new StringLiteralExpression("/"),
			                                                 AstUtil.CreateReferenceExpression(componentContextName +
			                                                                                   ".ViewToRender")));

			outputSubView.Arguments.Add(AstUtil.CreateReferenceExpression(componentContextName + ".ComponentParameters"));
			renderView.Add(outputSubView);

			block.Add(new IfStatement(AstUtil.CreateReferenceExpression(componentContextName + ".ViewToRender"),
			                          renderView, new Block()));

			// RemoveViewComponentProperties( compilerContext.ComponentParams )
			var removeProperties =
				new MethodInvocationExpression(AstUtil.CreateReferenceExpression("RemoveViewComponentProperties"));
			removeProperties.Arguments.Add(AstUtil.CreateReferenceExpression(componentContextName + ".ComponentParameters"));
			block.Add(removeProperties);

			return block;
		}
        public override void OnDestructor(Destructor node)
        {
            Method finalizer = CodeBuilder.CreateMethod(
                "Finalize",
                TypeSystemServices.VoidType,
                TypeMemberModifiers.Protected | TypeMemberModifiers.Override);
            finalizer.LexicalInfo = node.LexicalInfo;

            MethodInvocationExpression mie = new MethodInvocationExpression(new SuperLiteralExpression());

            Block bodyNew = new Block();
            Block ensureBlock = new Block();
            ensureBlock.Add (mie);

            TryStatement tryStatement = new TryStatement();
            tryStatement.EnsureBlock = ensureBlock;
            tryStatement.ProtectedBlock = node.Body;

            bodyNew.Add(tryStatement);
            finalizer.Body = bodyNew;

            node.ParentNode.Replace(node, finalizer);
        }
Пример #16
0
		void ConvertTryStatement(TryStatementInfo currentTry)
		{
			if (currentTry._containsYield)
				return;
			currentTry._containsYield = true;
			currentTry._stateNumber = _labels.Count;
			Block tryReplacement = new Block();
			//tryReplacement.Add(CreateLabel(tryReplacement));
			// when the MoveNext() is called while the enumerator is still in running state, don't jump to the
			// try block, but handle it like MoveNext() calls when the enumerator is in the finished state.
			_labels.Add(_labels[_finishedStateNumber]);
			_tryStatementInfoForLabels.Add(currentTry);
			tryReplacement.Add(SetStateTo(currentTry._stateNumber));
			currentTry._replacement = tryReplacement;
		}
Пример #17
0
	protected void internal_closure_stmt(
		Block block
	) //throws RecognitionException, TokenStreamException
{
		
		
				Statement stmt = null;
				StatementModifier modifier = null;
			
		
		try {      // for error handling
			{
				switch ( LA(1) )
				{
				case RETURN:
				{
					stmt=return_expression_stmt();
					break;
				}
				case ESEPARATOR:
				case CAST:
				case CHAR:
				case FALSE:
				case NOT:
				case NULL:
				case RAISE:
				case SELF:
				case SUPER:
				case THEN:
				case TRUE:
				case TYPEOF:
				case YIELD:
				case TRIPLE_QUOTED_STRING:
				case LPAREN:
				case DOUBLE_QUOTED_STRING:
				case SINGLE_QUOTED_STRING:
				case ID:
				case MULTIPLY:
				case LBRACK:
				case COMMA:
				case SPLICE_BEGIN:
				case DOT:
				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:
				{
					{
						{
							switch ( LA(1) )
							{
							case RAISE:
							{
								stmt=raise_stmt();
								break;
							}
							case YIELD:
							{
								stmt=yield_stmt();
								break;
							}
							default:
								bool synPredMatched343 = false;
								if (((LA(1)==ID) && (LA(2)==AS||LA(2)==COMMA)))
								{
									int _m343 = mark();
									synPredMatched343 = true;
									inputState.guessing++;
									try {
										{
											declaration();
											match(COMMA);
										}
									}
									catch (RecognitionException)
									{
										synPredMatched343 = false;
									}
									rewind(_m343);
									inputState.guessing--;
								}
								if ( synPredMatched343 )
								{
									stmt=unpack();
								}
								else if (((LA(1)==THEN||LA(1)==ID) && (tokenSet_100_.member(LA(2))))&&(IsValidClosureMacroArgument(LA(2)))) {
									stmt=closure_macro_stmt();
								}
								else if ((tokenSet_70_.member(LA(1))) && (tokenSet_101_.member(LA(2)))) {
									stmt=closure_expression_stmt();
								}
							else
							{
								throw new NoViableAltException(LT(1), getFilename());
							}
							break; }
						}
						{
							switch ( LA(1) )
							{
							case IF:
							case UNLESS:
							case WHILE:
							{
								modifier=stmt_modifier();
								if (0==inputState.guessing)
								{
									stmt.Modifier = modifier;
								}
								break;
							}
							case EOL:
							case EOS:
							case RBRACE:
							case QQ_END:
							{
								break;
							}
							default:
							{
								throw new NoViableAltException(LT(1), getFilename());
							}
							 }
						}
					}
					break;
				}
				default:
				{
					throw new NoViableAltException(LT(1), getFilename());
				}
				 }
			}
			if (0==inputState.guessing)
			{
				
						if (null != stmt)
						{
							block.Add(stmt);
						}
					
			}
		}
		catch (RecognitionException ex)
		{
			if (0 == inputState.guessing)
			{
				reportError(ex, "internal_closure_stmt");
				recover(ex,tokenSet_98_);
			}
			else
			{
				throw ex;
			}
		}
	}
Пример #18
0
        public static Statement brailOutResolve(this Node node){
            if (null == node) return new ExpressionStatement(new StringLiteralExpression("").writeOut());
            var ex = node as Expression;
            var bl = node as Block;
            var st = node as Statement;
            if (ex != null){
                if (ex is LiteralExpression){
                    return new ExpressionStatement(ex.writeOut());
                }
                if (ex.ToCodeString().ToLower().StartsWith("out")){
                    return new ExpressionStatement(ex);
                }
                if (ex is ReferenceExpression || ex is MethodInvocationExpression || ex is BinaryExpression ||
                    ex is ExpressionInterpolationExpression){
                    return new ExpressionStatement(ex.writeOut());
                }

                else{
                    return new ExpressionStatement(ex);
                }
            }
            else if (bl != null){
                var result = new Block();
                foreach (Statement statement in bl.Statements){
                    result.Add(statement.brailOutResolve());
                }
                return result;
            }
            else if (st != null){
                if (st is ExpressionStatement){
                    return ((ExpressionStatement) st).Expression.brailOutResolve();
                }
                else{
                    return st;
                }
            }
            else{
                return new Block();
            }
        }
Пример #19
0
		public static void UnpackEnumerable(BooCodeBuilder codeBuilder, Method method, Block block, Expression expression, DeclarationCollection declarations)
		{
			TypeSystemServices tss = codeBuilder.TypeSystemServices;
			
			InternalLocal local = codeBuilder.DeclareTempLocal(method,
			                                                   tss.IEnumeratorType);
			
			IType expressionType = expression.ExpressionType;
			
			if (expressionType.IsSubclassOf(codeBuilder.TypeSystemServices.IEnumeratorType))
			{
				block.Add(
					codeBuilder.CreateAssignment(
						codeBuilder.CreateReference(local),
						expression));
			}
			else
			{
				if (!expressionType.IsSubclassOf(codeBuilder.TypeSystemServices.IEnumerableType))
				{
					expression = codeBuilder.CreateMethodInvocation(
						RuntimeServices_GetEnumerable, expression);
				}
				
				block.Add(
					codeBuilder.CreateAssignment(
						block.LexicalInfo,
						codeBuilder.CreateReference(local),
						codeBuilder.CreateMethodInvocation(
							expression, IEnumerable_GetEnumerator)));
			}
			
			for (int i=0; i<declarations.Count; ++i)
			{
				Declaration declaration = declarations[i];
				
				block.Add(
					codeBuilder.CreateAssignment(
						codeBuilder.CreateReference(declaration.Entity),
						codeBuilder.CreateMethodInvocation(RuntimeServices_MoveNext,
						                                   codeBuilder.CreateReference(local))));
			}
		}
Пример #20
0
 private void ExpandTypeMember(TypeMember member, Block resultingBlock)
 {
     ApplyPrototypeModifiersAndAttributesTo(member);
     if (_addTypeMembersToEnclosingTypeDefinition)
         AddMemberToEnclosingTypeDef(member);
     else
         resultingBlock.Add(new TypeMemberStatement(member));
 }
Пример #21
0
		public static void UnpackArray(BooCodeBuilder codeBuilder, Method method, Block block, Expression expression, DeclarationCollection declarations)
		{
			ILocalEntity local = expression.Entity as ILocalEntity;
			if (null == local)
			{
				local = codeBuilder.DeclareTempLocal(method,
				                                     expression.ExpressionType);
				block.Add(
					codeBuilder.CreateAssignment(
						codeBuilder.CreateReference(local),
						expression));
			}
			for (int i=0; i<declarations.Count; ++i)
			{
				Declaration declaration = declarations[i];
				block.Add(
					codeBuilder.CreateAssignment(
						codeBuilder.CreateReference(
							declaration.Entity),
						codeBuilder.CreateSlicing(
							codeBuilder.CreateReference(local),
							i)));
			}
		}
Пример #22
0
		private void ExpandTypeMember(TypeMember member, Block resultingBlock)
		{
			ApplyPrototypeModifiersAndAttributesTo(member);
			resultingBlock.Add(new TypeMemberStatement(member) { InsertionPoint = _typeMemberPrototype });
		}
Пример #23
0
        /// <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);
        }
Пример #24
0
 void AddRunExpressionToBody(Block block, Expression temporaryVariable)
 {
     var method = new MethodInvocationExpression(new MemberReferenceExpression(temporaryVariable, "Run"));
     block.Add(method);
 }
Пример #25
0
	    private static void AddSections(Block block, MacroStatement macro)
	    {
	        IDictionary sections = (IDictionary)macro["sections"];
            if (sections == null)
                return;
	        foreach(DictionaryEntry entry in sections)
	        {
	            block.Add((Block)entry.Value);
	        }
	    }
Пример #26
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);
		}
Пример #27
0
		public override Statement Expand(MacroStatement macro)
		{
			if (macro.Arguments.Count == 0)
				throw new RailsException("Component must be called with a name");

            Block block = new Block();

		    Method method;
			Node parent = macro.ParentNode;
			while((parent is Method) == false)
			{
				parent = parent.ParentNode;
			}
			method = (Method) parent;

			StringLiteralExpression componentName = new StringLiteralExpression(macro.Arguments[0].ToString());

			MethodInvocationExpression dictionary = CreateParametersDictionary(macro);


			Expression macroBody = CodeBuilderHelper.CreateCallableFromMacroBody(CodeBuilder, macro);

			MethodInvocationExpression initContext = new MethodInvocationExpression();
			initContext.Target = AstUtil.CreateReferenceExpression("Castle.MonoRail.Views.Brail.BrailViewComponentContext");
			initContext.Arguments.Extend(
				new Expression[]
					{
					    new SelfLiteralExpression(),
						macroBody, componentName,
						AstUtil.CreateReferenceExpression("OutputStream"),
						dictionary
					});

			// compilerContext = BrailViewComponentContext(macroBodyClosure, "componentName", OutputStream, dictionary)
			block.Add(new BinaryExpression(BinaryOperatorType.Assign,
			                               new ReferenceExpression("componentContext"), initContext));

			// AddViewComponentProperties( compilerContext.ComponentParams )
			MethodInvocationExpression addProperties = new MethodInvocationExpression(AstUtil.CreateReferenceExpression("AddViewComponentProperties"));
			addProperties.Arguments.Add(AstUtil.CreateReferenceExpression("componentContext.ComponentParameters"));
			block.Add(addProperties);

			InternalLocal viewComponentFactoryLocal = CodeBuilder.DeclareLocal(method, "viewComponentFactory",
			                                                                   TypeSystemServices.Map(
			                                                                   	typeof(IViewComponentFactory)));
		    // viewComponentFactory = MonoRailHttpHandler.CurrentContext.GetService(IViewComponentFactory)
			MethodInvocationExpression callService = new MethodInvocationExpression(
				AstUtil.CreateReferenceExpression("MonoRailHttpHandler.CurrentContext.GetService"));
			callService.Arguments.Add(CodeBuilder.CreateTypeofExpression(typeof(IViewComponentFactory)));

			block.Add(new BinaryExpression(BinaryOperatorType.Assign,
			                               CodeBuilder.CreateLocalReference("viewComponentFactory", viewComponentFactoryLocal),
			                               callService));

			// component = viewComponentFactory.Create( componentName)
			MethodInvocationExpression createComponent = new MethodInvocationExpression(
				new MemberReferenceExpression(CodeBuilder.CreateLocalReference("viewComponentFactory", viewComponentFactoryLocal),
				                              "Create"));
			createComponent.Arguments.Add(componentName);
			block.Add(new BinaryExpression(BinaryOperatorType.Assign,
			                               new ReferenceExpression("component"),
			                               createComponent));

		    
            AddSections(block, macro);
		    

			// component.Init(context, componentContext)
			MethodInvocationExpression initComponent = new MethodInvocationExpression(
				AstUtil.CreateReferenceExpression("component.Init"));
			initComponent.Arguments.Extend(
				new Expression[] {AstUtil.CreateReferenceExpression("context"), new ReferenceExpression("componentContext")});

			block.Add(initComponent);    
		    
			// component.Render()
			block.Add(new MethodInvocationExpression(
			          	AstUtil.CreateReferenceExpression("component.Render")));

			// if component.ViewToRender is not null:
			//	OutputSubView("/"+component.ViewToRender, context.CompnentParameters)
			Block renderView = new Block();
			MethodInvocationExpression outputSubView = new MethodInvocationExpression(
				AstUtil.CreateReferenceExpression("OutputSubView"));
			outputSubView.Arguments.Add(new BinaryExpression(BinaryOperatorType.Addition,
			                                                 new StringLiteralExpression("/"),
			                                                 AstUtil.CreateReferenceExpression("componentContext.ViewToRender")));

			outputSubView.Arguments.Add(AstUtil.CreateReferenceExpression("componentContext.ComponentParameters"));
			renderView.Add(outputSubView);

			block.Add(new IfStatement(AstUtil.CreateReferenceExpression("componentContext.ViewToRender"),
			                          renderView, new Block()));

			// RemoveViewComponentProperties( compilerContext.ComponentParams )
			MethodInvocationExpression removeProperties = new MethodInvocationExpression(AstUtil.CreateReferenceExpression("RemoveViewComponentProperties"));
			removeProperties.Arguments.Add(AstUtil.CreateReferenceExpression("componentContext.ComponentParameters"));
			block.Add(removeProperties);

			return block;
		}
Пример #28
0
 public virtual Block ToBlock()
 {
     Block b = new Block(LexicalInfo);
     b.Add(this);
     return b;
 }
Пример #29
0
		override public void LeaveYieldStatement(YieldStatement node)
		{
			TryStatementInfo currentTry = (_tryStatementStack.Count > 0) ? _tryStatementStack.Peek() : null;
			if (currentTry != null) {
				ConvertTryStatement(currentTry);
			}
			Block block = new Block();
			block.Add(
				new ReturnStatement(
					node.LexicalInfo,
					CreateYieldInvocation(node.LexicalInfo, _labels.Count, node.Expression),
					null));
			block.Add(CreateLabel(node));
			// setting the state back to the "running" state not required, as that state has the same ensure blocks
			// as the state we are currently in.
//			if (currentTry != null) {
//				block.Add(SetStateTo(currentTry._stateNumber));
//			}
			ReplaceCurrentNode(block);
		}
Пример #30
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;
        }
Пример #31
0
        void AddInitializedGuardToInitializer(TypeDefinition type, Method initializer)
        {
            Field field = GetFieldsInitializerInitializedField(type);

            //run initializer code only if $initialized$ is false
            //hmm quasi-notation would be lovely here
            Block trueBlock = new Block();
            trueBlock.Add(new GotoStatement(LexicalInfo.Empty, new ReferenceExpression("___initialized___")));
            IfStatement cond = new IfStatement(CodeBuilder.CreateReference(field),
                trueBlock, null);
            initializer.Body.Insert(0, cond);

            //set $initialized$ field to true
            initializer.Body.Add(
                CodeBuilder.CreateFieldAssignment(field, new BoolLiteralExpression(true)));

            //label we're past the initializer
            initializer.Body.Add(
                new LabelStatement(LexicalInfo.Empty, "___initialized___"));
        }
Пример #32
0
        /// <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);
        }