public static Statement MapStatementModifier(StatementModifier modifier, out Block block)
        {
            switch (modifier.Type)
            {
                case StatementModifierType.If:
                {
                    IfStatement stmt = new IfStatement(modifier.LexicalInfo);
                    stmt.Condition = modifier.Condition;
                    stmt.TrueBlock = new Block();
                    block = stmt.TrueBlock;
                    return stmt;
                }

                case StatementModifierType.Unless:
                {
                    UnlessStatement stmt = new UnlessStatement(modifier.LexicalInfo);
                    stmt.Condition = modifier.Condition;
                    block = stmt.Block;
                    return stmt;
                }

                case StatementModifierType.While:
                {
                    WhileStatement stmt = new WhileStatement(modifier.LexicalInfo);
                    stmt.Condition = modifier.Condition;
                    block = stmt.Block;
                    return stmt;
                }
            }
            throw CompilerErrorFactory.NotImplemented(modifier, string.Format("modifier {0} supported", modifier.Type));
        }
Example #2
0
 public object VisitIfElseStatement(IfElseStatement ifElseStatement, object data)
 {
     B.IfStatement ifs     = new B.IfStatement(GetLexicalInfo(ifElseStatement));
     B.IfStatement outerIf = ifs;
     ifs.EndSourceLocation = GetLocation(ifElseStatement.EndLocation);
     ifs.Condition         = ConvertExpression(ifElseStatement.Condition);
     ifs.TrueBlock         = ConvertBlock(ifElseStatement.TrueStatement);
     if (ifElseStatement.HasElseIfSections)
     {
         foreach (ElseIfSection sec in ifElseStatement.ElseIfSections)
         {
             B.IfStatement elif = new B.IfStatement(GetLexicalInfo(sec));
             elif.EndSourceLocation = GetLocation(sec.EndLocation);
             elif.Condition         = ConvertExpression(sec.Condition);
             elif.TrueBlock         = ConvertBlock(sec.EmbeddedStatement);
             ifs.FalseBlock         = new B.Block();
             ifs.FalseBlock.Add(elif);
             ifs = elif;
         }
     }
     if (ifElseStatement.HasElseStatements)
     {
         ifs.FalseBlock = ConvertBlock(ifElseStatement.FalseStatement);
     }
     return(outerIf);
 }
Example #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;
		}
Example #4
0
 public override void LeaveIfStatement(IfStatement node)
 {
     CheckNotConstant(node.Condition);
 }
 public void if_statement(Block container)
 {
     IToken token = null;
     IToken token2 = null;
     try
     {
         IfStatement statement2;
         Block block;
         token = this.LT(1);
         this.match(0x15);
         Expression expression = this.paren_expression();
         if (base.inputState.guessing == 0)
         {
             IfStatement statement;
             Block block2;
             IfStatement statement1 = statement = new IfStatement(ToLexicalInfo(token));
             statement.set_Condition(expression);
             statement2 = statement;
             statement2.set_TrueBlock(block2 = new Block());
             block = block2;
             container.Add(statement2);
         }
         this.compound_or_single_stmt(block);
         if ((this.LA(1) == 11) && tokenSet_2_.member(this.LA(2)))
         {
             token2 = this.LT(1);
             this.match(11);
             if (base.inputState.guessing == 0)
             {
                 Block block3;
                 statement2.set_FalseBlock(block3 = new Block(ToLexicalInfo(token2)));
                 block = block3;
             }
             this.compound_or_single_stmt(block);
         }
         else if (!tokenSet_15_.member(this.LA(1)) || !tokenSet_20_.member(this.LA(2)))
         {
             throw new NoViableAltException(this.LT(1), this.getFilename());
         }
     }
     catch (RecognitionException exception)
     {
         if (base.inputState.guessing != 0)
         {
             throw;
         }
         this.reportError(exception);
         this.recover(exception, tokenSet_15_);
     }
 }
Example #6
0
	protected IfStatement  if_stmt() //throws RecognitionException, TokenStreamException
{
		IfStatement returnValue;
		
		IToken  it = null;
		IToken  ei = null;
		IToken  et = null;
		
				returnValue = null;
				
				IfStatement s = null;
				Expression e = null;
			
		
		try {      // for error handling
			it = LT(1);
			match(IF);
			e=expression();
			if (0==inputState.guessing)
			{
				
						returnValue = s = new IfStatement(ToLexicalInfo(it));
						s.Condition = e;
						s.TrueBlock = new Block();
					
			}
			compound_stmt(s.TrueBlock);
			{    // ( ... )*
				for (;;)
				{
					if ((LA(1)==ELIF))
					{
						ei = LT(1);
						match(ELIF);
						e=expression();
						if (0==inputState.guessing)
						{
							
										s.FalseBlock = new Block();
										
										IfStatement elif = new IfStatement(ToLexicalInfo(ei));
										elif.TrueBlock = new Block();
										elif.Condition = e;
										
										s.FalseBlock.Add(elif);
										s = elif;
									
						}
						compound_stmt(s.TrueBlock);
					}
					else
					{
						goto _loop413_breakloop;
					}
					
				}
_loop413_breakloop:				;
			}    // ( ... )*
			{
				switch ( LA(1) )
				{
				case ELSE:
				{
					et = LT(1);
					match(ELSE);
					if (0==inputState.guessing)
					{
						s.FalseBlock = new Block(ToLexicalInfo(et));
					}
					compound_stmt(s.FalseBlock);
					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());
				}
				 }
			}
		}
		catch (RecognitionException ex)
		{
			if (0 == inputState.guessing)
			{
				reportError(ex, "if_stmt");
				recover(ex,tokenSet_84_);
			}
			else
			{
				throw ex;
			}
		}
		return returnValue;
	}
Example #7
0
        //throws RecognitionException, TokenStreamException
        protected IfStatement if_stmt()
        {
            IfStatement returnValue;

            IToken  it = null;
            IToken  ei = null;
            IToken  et = null;

                returnValue = null;

                IfStatement s = null;
                Expression e = null;
                Block lastBlock = null;

            try {      // for error handling
            it = LT(1);
            match(IF);
            e=expression();
            if (0==inputState.guessing)
            {

                        returnValue = s = new IfStatement(SourceLocationFactory.ToLexicalInfo(it));
                        s.Condition = e;
                        lastBlock = s.TrueBlock = new Block();

            }
            begin();
            block(s.TrueBlock.Statements);
            {    // ( ... )*
                for (;;)
                {
                    if ((LA(1)==ELIF))
                    {
                        ei = LT(1);
                        match(ELIF);
                        e=expression();
                        if (0==inputState.guessing)
                        {

                                        s.FalseBlock = new Block();

                                        IfStatement elif = new IfStatement(SourceLocationFactory.ToLexicalInfo(ei));
                                        lastBlock = elif.TrueBlock = new Block();
                                        elif.Condition = e;

                                        s.FalseBlock.Add(elif);
                                        s = elif;

                        }
                        begin();
                        block(s.TrueBlock.Statements);
                    }
                    else
                    {
                        goto _loop358_breakloop;
                    }

                }
            _loop358_breakloop:				;
            }    // ( ... )*
            {
                switch ( LA(1) )
                {
                case ELSE:
                {
                    et = LT(1);
                    match(ELSE);
                    if (0==inputState.guessing)
                    {
                        lastBlock = s.FalseBlock = new Block(SourceLocationFactory.ToLexicalInfo(et));
                    }
                    begin();
                    block(s.FalseBlock.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 returnValue;
        }
Example #8
0
 public override void LeaveIfStatement(IfStatement node)
 {
     node.Condition = AssertBoolContext(node.Condition);
 }
 public override void LeaveIfStatement(IfStatement node)
 {
     node.Condition = ExplicitBooleanContext(node.Condition);
 }
Example #10
0
 public override void OnIfStatement(IfStatement node)
 {
     WriteIfBlock("if ", node);
     Block elseBlock = WriteElifs(node);
     if (null != elseBlock)
     {
         WriteIndented();
         WriteKeyword("else:");
         WriteLine();
         WriteBlock(elseBlock);
     }
     else
     {
         if (IsWhiteSpaceAgnostic)
         {
             WriteEnd();
         }
     }
 }
Example #11
0
 private void WriteIfBlock(string keyword, IfStatement ifs)
 {
     WriteIndented();
     WriteKeyword(keyword);
     Visit(ifs.Condition);
     WriteLine(":");
     Indent();
     WriteBlockStatements(ifs.TrueBlock);
     Dedent();
 }
Example #12
0
 private Block WriteElifs(IfStatement node)
 {
     Block falseBlock = node.FalseBlock;
     while (IsElif(falseBlock))
     {
         IfStatement stmt = (IfStatement) falseBlock.Statements[0];
         WriteIfBlock("elif ", stmt);
         falseBlock = stmt.FalseBlock;
     }
     return falseBlock;
 }
		public object VisitSwitchSection(SwitchSection switchSection, object data)
		{
			B.IfStatement surroundingIf = (B.IfStatement)data;
			bool isDefault = false;
			ArrayList conditions = new ArrayList();
			ArrayList labels = new ArrayList();
			foreach (CaseLabel caseLabel in switchSection.SwitchLabels) {
				if (caseLabel.IsDefault) {
					isDefault = true;
				} else {
					if (caseLabel.BinaryOperatorType != BinaryOperatorType.None) {
						AddError(caseLabel, "VB's Case Is currently not supported (Daniel's too lazy for VB stuff)");
					} else {
						B.Expression expr = ConvertExpression(caseLabel.Label);
						if (expr != null) {
							conditions.Add(new B.BinaryExpression(B.BinaryOperatorType.Equality,
							                                      new B.ReferenceExpression(currentSwitchTempName),
							                                      expr));
							string labelName = expr.ToCodeString().GetHashCode().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
							labels.Add(MakeLabel(currentSwitchTempName + "_" + labelName));
						}
					}
				}
			}
			B.IfStatement s = null;
			if (conditions.Count > 0) {
				s = new B.IfStatement(GetLexicalInfo(switchSection));
				if (surroundingIf != null) {
					s.FalseBlock = surroundingIf.FalseBlock;
					surroundingIf.FalseBlock = new B.Block();
					surroundingIf.FalseBlock.Add(s);
				}
				s.TrueBlock = new B.Block();
				foreach (B.Statement stmt in labels) {
					s.TrueBlock.Add(stmt);
				}
				B.Expression combined = (B.Expression)conditions[0];
				for (int i = 1; i < conditions.Count; i++) {
					combined = new B.BinaryExpression(B.BinaryOperatorType.Or, combined, (B.Expression)conditions[i]);
				}
				s.Condition = combined;
				foreach (Statement node in switchSection.Children) {
					AddToBlock(node, s.TrueBlock);
				}
			}
			if (s == null)
				s = surroundingIf;
			if (isDefault) {
				if (s.FalseBlock == null)
					s.FalseBlock = new B.Block();
				s.FalseBlock.Add(MakeLabel(currentSwitchTempName + "_default"));
				foreach (Statement node in switchSection.Children) {
					AddToBlock(node, s.FalseBlock);
				}
			}
			return s;
		}
		public object VisitSwitchStatement(SwitchStatement switchStatement, object data)
		{
			// We have a problem: given is still not implemented in boo.
			// So here's the if / else workaround:
			string oldSwitchTempName = currentSwitchTempName;
			currentSwitchTempName = GenerateName();
			ArrayList l = new ArrayList(3);
			B.BinaryExpression init = new B.BinaryExpression(B.BinaryOperatorType.Assign,
			                                                 new B.ReferenceExpression(currentSwitchTempName),
			                                                 ConvertExpression(switchStatement.SwitchExpression));
			l.Add(new B.ExpressionStatement(init));
			B.IfStatement dummyStatement = new B.IfStatement(GetLexicalInfo(switchStatement));
			B.IfStatement first = null;
			B.IfStatement current = dummyStatement;
			B.BreakStatement bs;
			for (int i = 0; i < switchStatement.SwitchSections.Count; i++) {
				current = (B.IfStatement)((INode)switchStatement.SwitchSections[i]).AcceptVisitor(this, current);
				if (i == 0) {
					first = current;
				}
				bs = GetLastStatement(current.TrueBlock) as B.BreakStatement;
				if (bs != null)
					bs.ReplaceBy(null);
			}
			bs = GetLastStatement(current.FalseBlock) as B.BreakStatement;
			if (bs != null)
				bs.ReplaceBy(null);
			
			string endSwitchName = currentSwitchTempName + "_end";
			first.Accept(new ReplaceBreakStatementsVisitor(endSwitchName));
			
			FindUnneededLabelsVisitor fulv = new FindUnneededLabelsVisitor(currentSwitchTempName + "_", nameComparer);
			first.Accept(fulv);
			
			bool needsEndLabel = fulv.NeededLabels.Contains(endSwitchName);
			
			fulv.RemoveLabels(); // remove "goto case" labels that aren't needed
			currentSwitchTempName = oldSwitchTempName;
			
			if (first == dummyStatement) {
				l.AddRange(dummyStatement.FalseBlock.Statements);
			} else {
				l.Add(first);
			}
			if (needsEndLabel)
				l.Add(MakeLabel(endSwitchName));
			
			return l;
		}
		public object VisitIfElseStatement(IfElseStatement ifElseStatement, object data)
		{
			B.IfStatement ifs = new B.IfStatement(GetLexicalInfo(ifElseStatement));
			B.IfStatement outerIf = ifs;
			ifs.EndSourceLocation = GetLocation(ifElseStatement.EndLocation);
			ifs.Condition = ConvertExpression(ifElseStatement.Condition);
			ifs.TrueBlock = ConvertBlock(ifElseStatement.TrueStatement);
			if (ifElseStatement.HasElseIfSections) {
				foreach (ElseIfSection sec in ifElseStatement.ElseIfSections) {
					B.IfStatement elif = new B.IfStatement(GetLexicalInfo(sec));
					elif.EndSourceLocation = GetLocation(sec.EndLocation);
					elif.Condition = ConvertExpression(sec.Condition);
					elif.TrueBlock = ConvertBlock(sec.EmbeddedStatement);
					ifs.FalseBlock = new B.Block();
					ifs.FalseBlock.Add(elif);
					ifs = elif;
				}
			}
			if (ifElseStatement.HasElseStatements) {
				ifs.FalseBlock = ConvertBlock(ifElseStatement.FalseStatement);
			}
			return outerIf;
		}
		void CreateMoveNext()
		{
			BooMethodBuilder method = _enumerator.AddVirtualMethod("MoveNext", TypeSystemServices.BoolType);
			
			Expression moveNext = CodeBuilder.CreateMethodInvocation(
				CodeBuilder.CreateReference((InternalField)_enumeratorField.Entity),
				TypeSystemServices.Map(Methods.InstanceFunctionOf<IEnumerator, bool>(e => e.MoveNext)));
						
			Expression current = CodeBuilder.CreateMethodInvocation(
				CodeBuilder.CreateReference((InternalField)_enumeratorField.Entity),
				((IProperty)GetMember(_sourceEnumeratorType, "Current", EntityType.Property)).GetGetMethod());
			
			Statement filter = null;
			Statement stmt = null;
			Block outerBlock = null;
			Block innerBlock = null;
			
			if (null == _generator.Filter)
			{
				IfStatement istmt = new IfStatement(moveNext, new Block(), null);
				outerBlock = innerBlock = istmt.TrueBlock;
				
				stmt = istmt;
			}
			else
			{
				WhileStatement wstmt = new WhileStatement(moveNext);
				outerBlock = wstmt.Block;
				
				if (StatementModifierType.If == _generator.Filter.Type)
				{
					IfStatement ifstmt = new IfStatement(_generator.Filter.Condition, new Block(), null);
					innerBlock = ifstmt.TrueBlock;
					filter = ifstmt;
				}
				else
				{
					UnlessStatement ustmt = new UnlessStatement(_generator.Filter.Condition);
					innerBlock = ustmt.Block;
					filter = ustmt;
				}
				
				stmt = wstmt;
			}
												
			DeclarationCollection declarations = _generator.Declarations;
			if (declarations.Count > 1)
			{
				NormalizeIterationStatements.UnpackExpression(CodeBuilder,
				                                              method.Method,
				                                              outerBlock,
				                                              current,
				                                              declarations);
												
				foreach (Declaration declaration in declarations)
				{
					method.Locals.Add(((InternalLocal)declaration.Entity).Local);
				}
			}
			else
			{
				InternalLocal local = (InternalLocal)declarations[0].Entity;
				method.Locals.Add(local.Local);
				outerBlock.Add(CodeBuilder.CreateAssignment(
				               	CodeBuilder.CreateReference(local),
				               	current));
			}
			
			if (null != filter)
			{
				outerBlock.Add(filter);
			}
			
			innerBlock.Add(CodeBuilder.CreateAssignment(
			               	CodeBuilder.CreateReference((InternalField)_current.Entity),
			               	_generator.Expression));
			innerBlock.Add(new ReturnStatement(new BoolLiteralExpression(true)));
			
			method.Body.Add(stmt);
			method.Body.Add(new ReturnStatement(new BoolLiteralExpression(false)));
		}
			public override void OnWhileStatement(WhileStatement node)
			{
				if (node.OrBlock == null) return;

				InternalLocal enteredLoop = CodeBuilder().DeclareTempLocal(_currentMethod, BoolType());

				IfStatement orPart = new IfStatement(
					node.OrBlock.LexicalInfo,
					CodeBuilder().CreateNotExpression(CodeBuilder().CreateReference(enteredLoop)),
					node.OrBlock,
					null);

				node.OrBlock = orPart.ToBlock();
				node.Block.Insert(0,
					CodeBuilder().CreateAssignment(
						CreateReference(enteredLoop),
						CreateTrueLiteral()));

			}
Example #18
0
        Method CreateEventRaiseMethod(Event node, Field backingField)
        {
            TypeMemberModifiers modifiers = RemoveAccessiblityModifiers(node.Modifiers);
            if (node.IsPrivate)
            {
                modifiers |= TypeMemberModifiers.Private;
            }
            else
            {
                modifiers |= TypeMemberModifiers.Protected | TypeMemberModifiers.Internal;
            }

            Method method = CodeBuilder.CreateMethod("raise_" + node.Name,
                TypeSystemServices.VoidType,
                modifiers);

            ICallableType type = GetEntity(node.Type) as ICallableType;
            if (null != type)
            {
                int index = CodeBuilder.GetFirstParameterIndex(node);
                foreach (IParameter parameter in type.GetSignature().Parameters)
                {
                    method.Parameters.Add(
                        CodeBuilder.CreateParameterDeclaration(
                        index,
                        parameter.Name,
                        parameter.Type,
                        parameter.IsByRef));
                    ++index;
                }
            }

            MethodInvocationExpression mie = CodeBuilder.CreateMethodInvocation(
                CodeBuilder.CreateReference(backingField),
                NameResolutionService.ResolveMethod(GetType(backingField.Type), "Invoke"));
            foreach (ParameterDeclaration parameter in method.Parameters)
            {
                mie.Arguments.Add(CodeBuilder.CreateReference(parameter));
            }

            IfStatement stmt = new IfStatement(node.LexicalInfo);
            stmt.Condition = CodeBuilder.CreateNotNullTest(
                CodeBuilder.CreateReference(backingField));
            stmt.TrueBlock = new Block();
            stmt.TrueBlock.Add(mie);
            method.Body.Add(stmt);
            return method;
        }
Example #19
0
        public object VisitSwitchStatement(SwitchStatement switchStatement, object data)
        {
            // We have a problem: given is still not implemented in boo.
            // So here's the if / else workaround:
            string oldSwitchTempName = currentSwitchTempName;

            currentSwitchTempName = GenerateName();
            ArrayList l = new ArrayList(3);

            B.BinaryExpression init = new B.BinaryExpression(B.BinaryOperatorType.Assign,
                                                             new B.ReferenceExpression(currentSwitchTempName),
                                                             ConvertExpression(switchStatement.SwitchExpression));
            l.Add(new B.ExpressionStatement(init));
            B.IfStatement    dummyStatement = new B.IfStatement(GetLexicalInfo(switchStatement));
            B.IfStatement    first          = null;
            B.IfStatement    current        = dummyStatement;
            B.BreakStatement bs;
            for (int i = 0; i < switchStatement.SwitchSections.Count; i++)
            {
                current = (B.IfStatement)((INode)switchStatement.SwitchSections[i]).AcceptVisitor(this, current);
                if (i == 0)
                {
                    first = current;
                }
                bs = GetLastStatement(current.TrueBlock) as B.BreakStatement;
                if (bs != null)
                {
                    bs.ReplaceBy(null);
                }
            }
            bs = GetLastStatement(current.FalseBlock) as B.BreakStatement;
            if (bs != null)
            {
                bs.ReplaceBy(null);
            }

            string endSwitchName = currentSwitchTempName + "_end";

            first.Accept(new ReplaceBreakStatementsVisitor(endSwitchName));

            FindUnneededLabelsVisitor fulv = new FindUnneededLabelsVisitor(currentSwitchTempName + "_", nameComparer);

            first.Accept(fulv);

            bool needsEndLabel = fulv.NeededLabels.Contains(endSwitchName);

            fulv.RemoveLabels();             // remove "goto case" labels that aren't needed
            currentSwitchTempName = oldSwitchTempName;

            if (first == dummyStatement)
            {
                l.AddRange(dummyStatement.FalseBlock.Statements);
            }
            else
            {
                l.Add(first);
            }
            if (needsEndLabel)
            {
                l.Add(MakeLabel(endSwitchName));
            }

            return(l);
        }
		public override void OnIfStatement(IfStatement node)
		{
			base.OnIfStatement(node);
			node.Condition = FixCondition(node.Condition);
		}
Example #21
0
        public object VisitSwitchSection(SwitchSection switchSection, object data)
        {
            B.IfStatement surroundingIf = (B.IfStatement)data;
            bool          isDefault     = false;
            ArrayList     conditions    = new ArrayList();
            ArrayList     labels        = new ArrayList();

            foreach (CaseLabel caseLabel in switchSection.SwitchLabels)
            {
                if (caseLabel.IsDefault)
                {
                    isDefault = true;
                }
                else
                {
                    if (caseLabel.BinaryOperatorType != BinaryOperatorType.None)
                    {
                        AddError(caseLabel, "VB's Case Is currently not supported (Daniel's too lazy for VB stuff)");
                    }
                    else
                    {
                        B.Expression expr = ConvertExpression(caseLabel.Label);
                        if (expr != null)
                        {
                            conditions.Add(new B.BinaryExpression(B.BinaryOperatorType.Equality,
                                                                  new B.ReferenceExpression(currentSwitchTempName),
                                                                  expr));
                            string labelName = expr.ToCodeString().GetHashCode().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
                            labels.Add(MakeLabel(currentSwitchTempName + "_" + labelName));
                        }
                    }
                }
            }
            B.IfStatement s = null;
            if (conditions.Count > 0)
            {
                s = new B.IfStatement(GetLexicalInfo(switchSection));
                if (surroundingIf != null)
                {
                    s.FalseBlock             = surroundingIf.FalseBlock;
                    surroundingIf.FalseBlock = new B.Block();
                    surroundingIf.FalseBlock.Add(s);
                }
                s.TrueBlock = new B.Block();
                foreach (B.Statement stmt in labels)
                {
                    s.TrueBlock.Add(stmt);
                }
                B.Expression combined = (B.Expression)conditions[0];
                for (int i = 1; i < conditions.Count; i++)
                {
                    combined = new B.BinaryExpression(B.BinaryOperatorType.Or, combined, (B.Expression)conditions[i]);
                }
                s.Condition = combined;
                foreach (Statement node in switchSection.Children)
                {
                    AddToBlock(node, s.TrueBlock);
                }
            }
            if (s == null)
            {
                s = surroundingIf;
            }
            if (isDefault)
            {
                if (s.FalseBlock == null)
                {
                    s.FalseBlock = new B.Block();
                }
                s.FalseBlock.Add(MakeLabel(currentSwitchTempName + "_default"));
                foreach (Statement node in switchSection.Children)
                {
                    AddToBlock(node, s.FalseBlock);
                }
            }
            return(s);
        }
Example #22
0
        public override void OnIfStatement(IfStatement node)
        {
            Label endLabel = _il.DefineLabel();

            EmitDebugInfo(node);
            EmitBranchFalse(node.Condition, endLabel);

            node.TrueBlock.Accept(this);
            if (null != node.FalseBlock)
            {
                Label elseEndLabel = _il.DefineLabel();
                if (!node.TrueBlock.EndsWith<ReturnStatement>() && !node.TrueBlock.EndsWith<RaiseStatement>())
                    _il.Emit(OpCodes.Br, elseEndLabel);
                _il.MarkLabel(endLabel);

                endLabel = elseEndLabel;
                node.FalseBlock.Accept(this);
            }

            _il.MarkLabel(endLabel);
        }
        /// <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);
        }
Example #24
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___"));
        }
Example #25
0
		override public object Clone()
		{
		
			IfStatement clone = new IfStatement();
			clone._lexicalInfo = _lexicalInfo;
			clone._endSourceLocation = _endSourceLocation;
			clone._documentation = _documentation;
			clone._isSynthetic = _isSynthetic;
			clone._entity = _entity;
			if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
			if (null != _modifier)
			{
				clone._modifier = _modifier.Clone() as StatementModifier;
				clone._modifier.InitializeParent(clone);
			}
			if (null != _condition)
			{
				clone._condition = _condition.Clone() as Expression;
				clone._condition.InitializeParent(clone);
			}
			if (null != _trueBlock)
			{
				clone._trueBlock = _trueBlock.Clone() as Block;
				clone._trueBlock.InitializeParent(clone);
			}
			if (null != _falseBlock)
			{
				clone._falseBlock = _falseBlock.Clone() as Block;
				clone._falseBlock.InitializeParent(clone);
			}
			return clone;


		}