public override object VisitSwitchStatement(SwitchStatement switchStatement, object data)
            {
                foreach (var section in switchStatement.SwitchSections)
                {
                    foreach (var label in section.CaseLabels)
                    {
                        var memberRef = label.Expression as MemberReferenceExpression;
                        var targetObject = memberRef != null ? memberRef.Target as IdentifierExpression : null;
                        if (targetObject != null)
                        {
                            var hasEnums = codebaseDeclarationInfos.Any(a =>
                                     a.Name == targetObject.Identifier &&
                                     a.DeclarationClassType == TypeDeclarationKind.Enum);

                            if (hasEnums)
                            {
                                UnlockWith(switchStatement);
                                break;
                            }
                        }
                    }
                }

                return base.VisitSwitchStatement(switchStatement, data);
            }
Beispiel #2
0
        public override void VisitSwitchStatement(SwitchStatement switchStatement)
        {
            var token = CreateBlock(string.Format("switch ({0})", switchStatement.Expression.GetText()), SDNodeRole.Switch);
            _tokenList.Add(token);

            var tmp = _tokenList;
            _tokenList = token.Statements;

            foreach (var section in switchStatement.SwitchSections)
            {
                var caseToken = CreateBlock(string.Join(" ", section.CaseLabels.Select(o => o.GetText())), SDNodeRole.Case);
                _tokenList.Add(caseToken);

                VisitChildren(caseToken.Statements, section);
            }            
        }
Beispiel #3
0
			public override object Visit(Switch switchStatement)
			{
				var result = new SwitchStatement();
				
				var location = LocationsBag.GetLocations(switchStatement);
				result.AddChild(new CSharpTokenNode(Convert(switchStatement.loc), SwitchStatement.SwitchKeywordRole), SwitchStatement.SwitchKeywordRole);
				if (location != null)
					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
				if (switchStatement.Expr != null)
					result.AddChild((Expression)switchStatement.Expr.Accept(this), Roles.Expression);
				if (location != null && location.Count > 1)
					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
				if (location != null && location.Count > 2)
					result.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.LBrace), Roles.LBrace);
				SwitchSection newSection = null;
				bool lastWasCase = false, added = true;
				if (switchStatement.Block != null) {
					foreach (var child in switchStatement.Block.Statements) {
						var statement = child.Accept(this);
						var caseLabel = statement as CaseLabel;
						if (caseLabel != null) {
							if (!lastWasCase) {
								newSection = new SwitchSection();
								added = false;
							}
							newSection.AddChild(caseLabel, SwitchSection.CaseLabelRole);
							lastWasCase = true;
						} else {
							if (lastWasCase) {
								result.AddChild(newSection, SwitchStatement.SwitchSectionRole);
								lastWasCase = false;
								added = true;
							}
							newSection.AddChild((Statement)statement, Roles.EmbeddedStatement);
						}
					}
				}
				if (!added)
					result.AddChild(newSection, SwitchStatement.SwitchSectionRole);

				if (location != null && location.Count > 3) {
					result.AddChild(new CSharpTokenNode(Convert(location [3]), Roles.RBrace), Roles.RBrace);
				} else {
					// parser error, set end node to max value.
					result.AddChild(new ErrorNode(), Roles.Error);
				}
				
				return result;
			}
 protected internal virtual void PostWalk(SwitchStatement node) { }
		public virtual void Visit(SwitchStatement.CaseStatement s)
		{
			VisitChildren(s);

			if (s.ArgumentList != null)
				s.ArgumentList.Accept(this);
			if (s.LastExpression != null)
				s.LastExpression.Accept(this);
		}
		public override void VisitSwitchStatement(SwitchStatement switchStatement) {
			var compiledExpr = CompileExpression(switchStatement.Expression, CompileExpressionFlags.ReturnValueIsImportant);
			_result.AddRange(compiledExpr.AdditionalStatements);

			var oldGotoCaseMap = _currentGotoCaseMap;

			var gotoCaseData = new GatherGotoCaseAndDefaultDataVisitor(_resolver, _nextLabelIndex).Process(switchStatement);
			_currentGotoCaseMap = gotoCaseData.Item2;

			var caseClauses = new List<JsSwitchSection>();
			foreach (var section in switchStatement.SwitchSections) {
				SetRegion(section.GetRegion());
				var values = new List<JsExpression>();
				foreach (var v in section.CaseLabels) {
					if (v.Expression.IsNull) {
						values.Add(null);	// Default
					}
					else {
						var rr = _resolver.Resolve(v.Expression);
						object value = rr.ConstantValue;
						if (rr is MemberResolveResult && ((MemberResolveResult)rr).Member is IField) {
							var sem = _metadataImporter.GetFieldSemantics((IField)((MemberResolveResult)rr).Member);
							if (sem.Type == FieldScriptSemantics.ImplType.Constant)
								value = sem.Value;
						}

						if (value == null) {
							values.Add(JsExpression.Null);
						}
						else if (value is string) {
							values.Add(JsExpression.String((string)value));
						}
						else {
							values.Add(JsExpression.Number((int)Convert.ChangeType(value, typeof(int))));
						}
					}
				}

				var ic = CreateInnerCompiler();
				IList<JsStatement> statements;
				if (section.Statements.Count == 1 && section.Statements.First() is BlockStatement) {
					statements = ic.Compile(section.Statements.First()).Statements;
				}
				else {
					ic.VisitChildren(section);
					statements = ic._result;
				}

				if (gotoCaseData.Item1.ContainsKey(section))
					statements = new[] { JsStatement.Label(gotoCaseData.Item1[section], statements[0]) }.Concat(statements.Skip(1)).ToList();

				caseClauses.Add(JsStatement.SwitchSection(values, JsStatement.Block(statements)));
			}

			_result.Add(JsStatement.Switch(compiledExpr.Expression, caseClauses));
			_currentGotoCaseMap = oldGotoCaseMap;
		}
 public virtual void Exit(SwitchStatement node)
 {
 }
 public virtual void VisitSwitchStatement(SwitchStatement switchStatement)
 {
     if (this.ThrowException)
     {
         throw (Exception)this.CreateException(switchStatement);
     }
 }
 internal SwitchStatementAdapter(SwitchStatement switchStatement)
 {
     m_switchStatement     = switchStatement;
     m_caseExpressionNodes = new HashSet <Node>(switchStatement.CaseClauses.Select(cc => cc.CaseExpression));
 }
Beispiel #10
0
        protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
        {
            SwitchStatement o = other as SwitchStatement;

            return(o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match));
        }
Beispiel #11
0
 public override IEnumerable <Expression> VisitSwitchStatement(SwitchStatement switchStatement)
 {
     yield return(switchStatement.Expression);
 }
 public override object VisitSwitchStatement(SwitchStatement switchStatement, object data)
 {
     UnlockWith(switchStatement);
     return(base.VisitSwitchStatement(switchStatement, data));
 }
Beispiel #13
0
 public virtual void VisitSwitchStatement(SwitchStatement node)
 {
     this.Visit(node.get_Condition());
     this.Visit(node.get_Cases());
     return;
 }
 public DefaultSwitchCase(SourceRange source, SwitchStatement @switch) : base(source, @switch)
 {
 }
 public ValueSwitchCase(SourceRange source, SwitchStatement @switch, IExpression value) : base(source, @switch)
     => Value = value;
 /**
  * Call back method that must be called when the given <code>
  * SwitchStatement</code> will become the next <i>traverse candidate</i>.
  *
  * @param pSwitchStatement  The <code>SwitchStatement</code> object that
  *                          will become the next <i>traverse candidate</i>.
  */
 public void performAction(
      SwitchStatement pSwitchStatement)
 {
     // Nothing to do.
 }
Beispiel #17
0
 public override INode VisitSwitchStatement(SwitchStatement switchStatement)
 {
     return(new SwitchStatement(switchStatement.Context, switchStatement.Children.Select(Visit)));
 }
Beispiel #18
0
        public override Object Visit(SwitchStatement node, Object obj)
        {
            Object        aux             = null;
            List <SSAMap> mapsSwitch      = new List <SSAMap>();
            int           indexDefaultMap = -1;

            if ((aux = node.Condition.Accept(this, false)) is SingleIdentifierExpression)
            {
                node.Condition = (SingleIdentifierExpression)aux;
            }
            SSAMap map0 = this.map.Clone();

            IList <SingleIdentifierExpression> previousCaseReferences = this.referencesUsedInCaseBody;

            for (int i = 0; i < node.SwitchBlockCount; i++)
            {
                // * Updates the current if statatement body being analyzed
                IList <SingleIdentifierExpression> caseReferences = new List <SingleIdentifierExpression>();
                node.ReferencesUsedCases[node.GetSwitchSectionElement(i).SwitchBlock] = caseReferences;
                IList <SingleIdentifierExpression> previousReferencesUsedInCaseBody = this.referencesUsedInCaseBody;
                this.referencesUsedInCaseBody = caseReferences;

                this.map.SetScope();
                node.GetSwitchSectionElement(i).Accept(this, false);
                if (node.GetSwitchSectionElement(i).IsDefaultCase())
                {
                    indexDefaultMap = i;
                }
                this.addLocalVariable(this.map.ResetScope(), node.GetSwitchSectionElement(i).SwitchBlock);
                mapsSwitch.Add(this.map.Clone());
            }
            this.referencesUsedInCaseBody = previousCaseReferences;

            // lastMap => this.map

            List <MoveStatement> mvSt;

            if (indexDefaultMap == -1)
            {
                mvSt = map0.GetMoveStatements(this.map, node.Location.FileName, node.Location.Line);
            }
            else
            {
                mvSt = map0.GetMoveStatementsForSwitch(mapsSwitch, node.Location.FileName, node.Location.Line);
            }
            if (mvSt.Count != 0)
            {
                node.AfterCondition = mvSt;
            }


            for (int i = 0; i < node.SwitchBlockCount; i++)
            {
                SSAInfo info;
                if (i > 0)
                {
                    info = new SSAInfo(mapsSwitch[i], this.map, mapsSwitch[i - 1], map0);
                }
                else
                {
                    info = new SSAInfo(mapsSwitch[i], this.map, null, null);
                }
                node.GetSwitchSectionElement(i).Accept(new VisitorSSA2(), info);
            }

            List <ThetaStatement> thSt;

            if (indexDefaultMap != -1)
            {
                thSt = map0.GetThetaStatements(mapsSwitch, ref this.map, true, node.Location.FileName, node.GetSwitchSectionElement(node.SwitchBlockCount - 1).SwitchBlock.Location.Line);
            }
            else
            {
                thSt = map0.GetThetaStatements(mapsSwitch, ref this.map, false, node.Location.FileName, node.GetSwitchSectionElement(node.SwitchBlockCount - 1).SwitchBlock.Location.Line);
            }

            if (thSt.Count != 0)
            {
                node.ThetaStatements = thSt;
            }

            return(null);
        }
		public void SwitchStatement()
		{
			SwitchStatement type = new SwitchStatement {
				Expression = new IdentifierExpression("i"),
				SwitchSections = {
					new SwitchSection {
						CaseLabels = {
							new CaseLabel(new PrimitiveExpression(1)),
							new CaseLabel(new PrimitiveExpression(2))
						},
						Statements = {
							new ExpressionStatement(new IdentifierExpression("A").Invoke()),
							new ExpressionStatement(new IdentifierExpression("B").Invoke()),
							new BreakStatement()
						}
					},
					new SwitchSection {
						CaseLabels = {
							new CaseLabel(new PrimitiveExpression(3))
						},
						Statements = {
							new BlockStatement {
								new VariableDeclarationStatement(new PrimitiveType("int"), "a", new PrimitiveExpression(3)),
								new ReturnStatement(new IdentifierExpression("a")),
							}
						}
					},
					new SwitchSection {
						CaseLabels = {
							new CaseLabel()
						},
						Statements = {
							new BreakStatement()
						}
					}
				}};
			
			AssertOutput("switch (i) {\ncase 1:\ncase 2:\n$A ();\n$B ();\n$break;\n" +
			             "case 3: {\n$int a = 3;\n$return a;\n}\n" +
			             "default:\n$break;\n}\n", type);
		}
Beispiel #20
0
        public static void Compile(ByteCodeCompiler bcc, ParserContext parser, ByteBuffer buffer, SwitchStatement switchStatement)
        {
            bool isInt = switchStatement.UsesIntegers;

            bcc.CompileExpression(parser, buffer, switchStatement.Condition, true);

            ByteBuffer chunkBuffer = new ByteBuffer();

            Dictionary <int, int>    chunkIdsToOffsets  = new Dictionary <int, int>();
            Dictionary <int, int>    integersToChunkIds = new Dictionary <int, int>();
            Dictionary <string, int> stringsToChunkIds  = new Dictionary <string, int>();

            int defaultChunkId = -1;

            foreach (SwitchStatement.Chunk chunk in switchStatement.Chunks)
            {
                int chunkId = chunk.ID;

                if (chunk.Cases.Length == 1 && chunk.Cases[0] == null)
                {
                    defaultChunkId = chunkId;
                }
                else
                {
                    foreach (Expression expression in chunk.Cases)
                    {
                        if (isInt)
                        {
                            integersToChunkIds[((IntegerConstant)expression).Value] = chunkId;
                        }
                        else
                        {
                            stringsToChunkIds[((StringConstant)expression).Value] = chunkId;
                        }
                    }
                }

                chunkIdsToOffsets[chunkId] = chunkBuffer.Size;

                bcc.Compile(parser, chunkBuffer, chunk.Code);
            }

            chunkBuffer.ResolveBreaks();

            int defaultOffsetLength = defaultChunkId == -1
                ? chunkBuffer.Size
                : chunkIdsToOffsets[defaultChunkId];

            List <int> args = new List <int>()
            {
                defaultOffsetLength
            };

            if (isInt)
            {
                foreach (int caseValue in integersToChunkIds.Keys.OrderBy(_ => _))
                {
                    int chunkId = integersToChunkIds[caseValue];
                    int offset  = chunkIdsToOffsets[chunkId];
                    args.Add(caseValue);
                    args.Add(offset);
                }
            }
            else
            {
                foreach (string caseValue in stringsToChunkIds.Keys.OrderBy(_ => _))
                {
                    int chunkId = stringsToChunkIds[caseValue];
                    int offset  = chunkIdsToOffsets[chunkId];
                    args.Add(parser.GetStringConstant(caseValue));
                    args.Add(offset);
                }
            }

            buffer.Add(
                switchStatement.FirstToken,
                isInt ? OpCode.SWITCH_INT : OpCode.SWITCH_STRING,
                args.ToArray());

            buffer.Concat(chunkBuffer);
        }
			public Tuple<Dictionary<SwitchSection, string>, Dictionary<object, string>> Process(SwitchStatement switchStatement) {
				_labels      = new Dictionary<SwitchSection, string>();
				_gotoCaseMap = new Dictionary<object, string>();
				_sectionLookup = (  from section in switchStatement.SwitchSections
				                    from label in section.CaseLabels
				                  select new { section, rr = !label.Expression.IsNull ? _resolver.Resolve(label.Expression) : null }
				                 ).ToDictionary(x => x.rr != null ? NormalizeSwitchLabelValue(x.rr.ConstantValue) : _gotoCaseMapDefaultKey, x => x.section);

				foreach (var section in switchStatement.SwitchSections)
					section.AcceptVisitor(this);

				return Tuple.Create(_labels, _gotoCaseMap);
			}
Beispiel #22
0
 public virtual Statement visit(SwitchStatement statement)
 {
     return(statement);
 }
Beispiel #23
0
 public override void Exit(SwitchStatement node)
 {
     level--;
 }
Beispiel #24
0
 public void Visit(SwitchStatement node)
 {
     ReportError(node);
 }
Beispiel #25
0
        /*private LocalRef CreateLoopVariable(string name)
        {
            LocalRef ret = new LocalRef(name);
            GetScope().AddSymbol(ret);

            return ret;
        }

        private void RemoveLoopVariable(LocalRef var)
        {
            GetScope().RemoveSymbol(var);
        }*/

        private void AddCase(SwitchStatement ss, object label, Statement block)
        {
            ss.cases.Add(new SwitchStatement.Case(label, block));
        }
Beispiel #26
0
        public Ust VisitStatement(JavaParser.StatementContext context)
        {
            var              textSpan = context.GetTextSpan();
            Statement        result;
            Expression       expression;
            Statement        statement;
            List <Statement> statements;

            if (context.blockLabel != null)
            {
                result = (Statement)Visit(context.blockLabel);
                return(result);
            }

            if (context.statementExpression != null)
            {
                result = Visit(context.statementExpression).ToStatementIfRequired();
                return(result);
            }

            if (context.identifierLabel != null)
            {
                var defaultResult = VisitChildren(context);
                return(new WrapperStatement(defaultResult, textSpan));
            }

            int firstTokenType = context.GetChild <ITerminalNode>(0).Symbol.Type;

            if (firstTokenType == JavaLexer.ASSERT)
            {
                var defaultResult = VisitChildren(context);
                return(new WrapperStatement(defaultResult, textSpan));
            }

            if (firstTokenType == JavaLexer.IF)
            {
                var condition     = (Expression)Visit(context.parExpression());
                var trueStatement = (Statement)Visit(context.statement(0));
                var falseStatment = context.ELSE() == null
                    ? null
                    : (Statement)Visit(context.statement(1));

                result = new IfElseStatement(condition, trueStatement, textSpan)
                {
                    FalseStatement = falseStatment
                };
                return(result);
            }

            if (firstTokenType == JavaLexer.FOR)
            {
                result = (Statement)Visit(context.forControl());
                return(result);
            }

            if (firstTokenType == JavaLexer.WHILE)
            {
                var conditionWhile = (Expression)Visit(context.parExpression());
                statement = (Statement)Visit(context.statement(0));

                result = new WhileStatement(conditionWhile, statement, textSpan);
                return(result);
            }

            if (firstTokenType == JavaLexer.DO)
            {
                statement  = (Statement)Visit(context.statement(0));
                expression = (Expression)Visit(context.parExpression());

                result = new DoWhileStatement(statement, expression, textSpan);
                return(result);
            }

            if (firstTokenType == JavaLexer.TRY)
            {
                // TODO: implement 'try' resourceSpecification block catchClause* finallyBlock? (C# using)

                var block = (BlockStatement)Visit(context.block());
                JavaParser.ResourceSpecificationContext resSpec = context.resourceSpecification();

                List <CatchClause> catchClauses = context.catchClause()
                                                  ?.Select(cc => (CatchClause)Visit(cc))
                                                  .Where(cc => cc != null).ToList();

                var finallyBlock = context.finallyBlock() == null ? null
                    : (BlockStatement)Visit(context.finallyBlock());

                if (resSpec == null)
                {
                    result = new TryCatchStatement(block, textSpan)
                    {
                        CatchClauses = catchClauses,
                        FinallyBlock = finallyBlock
                    };
                }
                else
                {
                    // C# using conversion to tryCatch
                    statements = new List <Statement>();
                    statements.AddRange(resSpec.resources().resource()
                                        .Select(res =>
                    {
                        var e = (VariableDeclarationExpression)Visit(res);
                        return(e == null ? null : new ExpressionStatement(e));
                    })
                                        .Where(res => res != null));
                    statements.AddRange(block.Statements);
                    var blockStatement = new BlockStatement(statements, context.GetTextSpan());

                    result = new TryCatchStatement(block, textSpan)
                    {
                        CatchClauses = catchClauses,
                        FinallyBlock = finallyBlock
                    };
                }
                return(result);
            }

            if (firstTokenType == JavaLexer.SWITCH)
            {
                expression = (Expression)Visit(context.parExpression());
                SwitchSection[] switchSections = context.switchBlockStatementGroup()
                                                 .Select(group => (SwitchSection)Visit(group))
                                                 .Where(group => group != null).ToArray();

                result = new SwitchStatement(expression, switchSections, textSpan);
                return(result);
            }

            if (firstTokenType == JavaLexer.SYNCHRONIZED) // synchronized(a) { b; c; } => { a; b; c; }
            {
                var resultStatements = new List <Statement>();
                expression = (Expression)Visit(context.parExpression());
                statements = context.block().blockStatement()
                             .Select(s => (Statement)Visit(s))
                             .Where(s => s != null).ToList();
                resultStatements.Add(new ExpressionStatement(expression, expression.TextSpan));
                resultStatements.AddRange(statements);

                result = new BlockStatement(resultStatements, textSpan);
                return(result);
            }

            if (firstTokenType == JavaLexer.RETURN)
            {
                expression = context.expression(0) != null
                            ? (Expression)Visit(context.expression(0))
                            : null;
                result = new ReturnStatement(expression, textSpan);
                return(result);
            }

            if (firstTokenType == JavaLexer.THROW)
            {
                expression = (Expression)Visit(context.expression(0));
                result     = new ThrowStatement(expression, textSpan);
                return(result);
            }

            if (firstTokenType == JavaLexer.BREAK)
            {
                result = new BreakStatement(textSpan);
                return(result);
            }

            if (firstTokenType == JavaLexer.CONTINUE)
            {
                result = new ContinueStatement(textSpan);
                return(result);
            }

            if (firstTokenType == JavaLexer.SEMI)
            {
                result = new EmptyStatement(textSpan);
                return(result);
            }

            return(VisitShouldNotBeVisited(context));
        }
Beispiel #27
0
            public override object Visit(Switch switchStatement)
            {
                var result = new SwitchStatement ();

                var location = LocationsBag.GetLocations (switchStatement);
                result.AddChild (new CSharpTokenNode (Convert (switchStatement.loc), SwitchStatement.SwitchKeywordRole), SwitchStatement.SwitchKeywordRole);
                if (location != null)
                    result.AddChild (new CSharpTokenNode (Convert (location [0]), Roles.LPar), Roles.LPar);
                if (switchStatement.Expr != null)
                    result.AddChild ((Expression)switchStatement.Expr.Accept (this), Roles.Expression);
                if (location != null && location.Count > 1)
                    result.AddChild (new CSharpTokenNode (Convert (location [1]), Roles.RPar), Roles.RPar);
                if (location != null && location.Count > 2)
                    result.AddChild (new CSharpTokenNode (Convert (location [2]), Roles.LBrace), Roles.LBrace);
                if (switchStatement.Sections != null) {
                    foreach (var section in switchStatement.Sections) {
                        var newSection = new SwitchSection ();
                        if (section.Labels != null) {
                            foreach (var caseLabel in section.Labels) {
                                var newLabel = new CaseLabel ();
                                if (caseLabel.Label != null) {
                                    newLabel.AddChild (new CSharpTokenNode (Convert (caseLabel.Location), CaseLabel.CaseKeywordRole), CaseLabel.CaseKeywordRole);
                                    if (caseLabel.Label != null)
                                        newLabel.AddChild ((Expression)caseLabel.Label.Accept (this), Roles.Expression);
                                    var colonLocation = LocationsBag.GetLocations (caseLabel);
                                    if (colonLocation != null)
                                        newLabel.AddChild (new CSharpTokenNode (Convert (colonLocation [0]), Roles.Colon), Roles.Colon);
                                } else {
                                    newLabel.AddChild (new CSharpTokenNode (Convert (caseLabel.Location), CaseLabel.DefaultKeywordRole), CaseLabel.DefaultKeywordRole);
                                    newLabel.AddChild (new CSharpTokenNode (new TextLocation (caseLabel.Location.Row, caseLabel.Location.Column + "default".Length), Roles.Colon), Roles.Colon);
                                }
                                newSection.AddChild (newLabel, SwitchSection.CaseLabelRole);
                            }
                        }

                        var blockStatement = section.Block;
                        var bodyBlock = new BlockStatement ();
                        int curLocal = 0;
                        AddBlockChildren (bodyBlock, blockStatement, ref curLocal);
                        foreach (var statement in bodyBlock.Statements) {
                            statement.Remove ();
                            newSection.AddChild (statement, Roles.EmbeddedStatement);

                        }
                        result.AddChild (newSection, SwitchStatement.SwitchSectionRole);
                    }
                }

                if (location != null && location.Count > 3) {
                    result.AddChild (new CSharpTokenNode (Convert (location [3]), Roles.RBrace), Roles.RBrace);
                } else {
                    // parser error, set end node to max value.
                    result.AddChild (new ErrorNode (), Roles.Error);
                }

                return result;
            }
Beispiel #28
0
        private static StatementBlock ParseStatementBlock(BinaryReader reader, Encoding encoding, BinaryWriter lineOffestWriter, BinaryWriter blockOffestWriter)
        {
            var block = new StatementBlock();

            while (!(reader.BaseStream.Position == reader.BaseStream.Length))
            {
                var type = reader.ReadByte();
                while (Array.BinarySearch(KnownTypeId, type) < 0)
                {
                    // 尝试跳过未知信息
                    type = reader.ReadByte();
                }
                var startOffest = (int)reader.BaseStream.Position - 1; // typeId到代码数据开头的偏移位置
                if (lineOffestWriter != null)
                {
                    if (true && // 部分数据不需要将位置写入LineOffest(一般为在IDE无显示的数据)
                        type != 0x50 && // 否则
                        type != 0x51 && // 如果结束
                        type != 0x52 && // 如果真结束
                        type != 0x55 && // 循环块结束标识:0x71前
                        type != 0x54 && // .判断结束
                        type != 0x53 && // .判断 某Case结束
                        type != 0x6D && // .判断开始(紧接着就是 0x6E)
                        type != 0x6F)    // .默认)
                    {
                        lineOffestWriter.Write(startOffest);
                    }
                }
                switch (type)
                {
                case 0x50:     // 否则
                case 0x51:     // 如果结束
                case 0x52:     // 如果真结束
                case 0x53:     // .判断 某Case结束
                case 0x54:     // .判断结束
                case 0x6F:     // .默认
                case 0x71:     // 循环结束语句:XX循环尾(参数...)
                    reader.BaseStream.Position = startOffest;
                    return(block);

                case 0x55:     // 循环体结束标识(0x71前)
                    continue;

                case 0x6D:     // .判断开始(紧接着就是 0x6E)
                {
                    blockOffestWriter.Write((byte)4);
                    blockOffestWriter.Write(startOffest);
                    long posToFillEndOffest = blockOffestWriter.BaseStream.Position;
                    blockOffestWriter.Write(0);
                    var s = new SwitchStatement();
                    if (reader.ReadByte() != 0x6E)         // .判断 某Case开始
                    {
                        throw new Exception();
                    }
                    byte switch_type;
                    do
                    {
                        lineOffestWriter.Write((int)reader.BaseStream.Position - 1);
                        var caseInfo = new SwitchStatement.CaseInfo();
                        caseInfo.Condition      = ParseCallExpressionWithoutType(reader, encoding, out var caseInfo_UnexaminedCode, out var caseInfo_Comment, out var caseInfo_Mask).ParamList.ElementAtOrDefault(0);
                        caseInfo.UnexaminedCode = caseInfo_UnexaminedCode;
                        caseInfo.Comment        = caseInfo_Comment;
                        caseInfo.Mask           = caseInfo_Mask;
                        caseInfo.Block          = ParseStatementBlock(reader, encoding, lineOffestWriter, blockOffestWriter);
                        s.Case.Add(caseInfo);
                        if (reader.ReadByte() != 0x53)
                        {
                            throw new Exception();
                        }
                    } while ((switch_type = reader.ReadByte()) == 0x6E);
                    if (switch_type != 0x6F)         // .默认
                    {
                        throw new Exception();
                    }
                    s.DefaultBlock = ParseStatementBlock(reader, encoding, lineOffestWriter, blockOffestWriter);
                    if (reader.ReadByte() != 0x54)         // .判断结束
                    {
                        throw new Exception();
                    }
                    int endOffest = (int)reader.BaseStream.Position;
                    blockOffestWriter.BaseStream.Position = posToFillEndOffest;
                    blockOffestWriter.Write(endOffest);
                    blockOffestWriter.BaseStream.Seek(0, SeekOrigin.End);
                    reader.ReadByte();         // 0x74
                    block.Add(s);
                }
                    continue;
                }
                var exp = ParseCallExpressionWithoutType(reader, encoding, out string unexaminedCode, out string comment, out bool mask);
                switch (type)
                {
                case 0x70:     // 循环开始语句:XX循环首(参数...)
                {
                    blockOffestWriter.Write((byte)3);
                    blockOffestWriter.Write(startOffest);
                    long posToFillEndOffest = blockOffestWriter.BaseStream.Position;
                    blockOffestWriter.Write(0);

                    var            loopblock = ParseStatementBlock(reader, encoding, lineOffestWriter, blockOffestWriter);
                    CallExpression endexp    = null;

                    var endOffest = (int)reader.BaseStream.Position;
                    blockOffestWriter.BaseStream.Position = posToFillEndOffest;
                    blockOffestWriter.Write(endOffest);
                    blockOffestWriter.BaseStream.Seek(0, SeekOrigin.End);

                    string endexp_unexaminedCode;
                    string endexp_comment;
                    bool   endexp_mask;
                    switch (reader.ReadByte())
                    {
                    case 0x71:
                        endexp = ParseCallExpressionWithoutType(reader, encoding, out endexp_unexaminedCode, out endexp_comment, out endexp_mask);
                        break;

                    default:
                        throw new Exception();
                    }
                    if (exp.LibraryId != 0)
                    {
                        throw new Exception();
                    }
                    LoopStatement s = null;
                    switch (exp.MethodId)
                    {
                    case 3:
                        s = new WhileStatement()
                        {
                            Condition      = exp.ParamList.ElementAtOrDefault(0),
                            Block          = loopblock,
                            UnexaminedCode = unexaminedCode
                        };
                        break;

                    case 5:
                        s = new DoWhileStatement()
                        {
                            Condition      = endexp.ParamList.ElementAtOrDefault(0),
                            Block          = loopblock,
                            UnexaminedCode = endexp_unexaminedCode
                        };
                        break;

                    case 7:
                        s = new CounterStatement()
                        {
                            Count          = exp.ParamList.ElementAtOrDefault(0),
                            Var            = exp.ParamList.ElementAtOrDefault(1),
                            Block          = loopblock,
                            UnexaminedCode = unexaminedCode
                        };
                        break;

                    case 9:
                        s = new ForStatement()
                        {
                            Start          = exp.ParamList.ElementAtOrDefault(0),
                            End            = exp.ParamList.ElementAtOrDefault(1),
                            Step           = exp.ParamList.ElementAtOrDefault(2),
                            Var            = exp.ParamList.ElementAtOrDefault(3),
                            Block          = loopblock,
                            UnexaminedCode = unexaminedCode
                        };
                        break;

                    default:
                        throw new Exception();
                    }

                    s.CommentOnStart = comment;
                    s.CommentOnEnd   = endexp_comment;

                    s.MaskOnStart = mask;
                    s.MaskOnEnd   = endexp_mask;

                    block.Add(s);
                }
                break;

                case 0x6C:     // 如果真
                {
                    blockOffestWriter.Write((byte)2);
                    blockOffestWriter.Write(startOffest);
                    long posToFillEndOffest = blockOffestWriter.BaseStream.Position;
                    blockOffestWriter.Write(0);

                    var s = new IfStatement()
                    {
                        Condition      = exp.ParamList.ElementAtOrDefault(0),
                        UnexaminedCode = unexaminedCode,
                        Block          = ParseStatementBlock(reader, encoding, lineOffestWriter, blockOffestWriter),
                        Comment        = comment,
                        Mask           = mask
                    };
                    if (reader.ReadByte() != 0x52)
                    {
                        throw new Exception();
                    }

                    var endOffest = (int)reader.BaseStream.Position;
                    blockOffestWriter.BaseStream.Position = posToFillEndOffest;
                    blockOffestWriter.Write(endOffest);
                    blockOffestWriter.BaseStream.Seek(0, SeekOrigin.End);

                    reader.ReadByte();         // 0x73

                    block.Add(s);
                }
                break;

                case 0x6B:     // 如果
                {
                    var s = new IfElseStatement()
                    {
                        Condition      = exp.ParamList.ElementAtOrDefault(0),
                        UnexaminedCode = unexaminedCode,
                        Comment        = comment,
                        Mask           = mask
                    };
                    blockOffestWriter.Write((byte)1);
                    blockOffestWriter.Write(startOffest);
                    long posToFillEndOffest = blockOffestWriter.BaseStream.Position;
                    blockOffestWriter.Write(0);

                    s.BlockOnTrue = ParseStatementBlock(reader, encoding, lineOffestWriter, blockOffestWriter);
                    if (reader.ReadByte() != 0x50)
                    {
                        throw new Exception();
                    }
                    s.BlockOnFalse = ParseStatementBlock(reader, encoding, lineOffestWriter, blockOffestWriter);
                    if (reader.ReadByte() != 0x51)
                    {
                        throw new Exception();
                    }
                    var endOffest = (int)reader.BaseStream.Position;

                    blockOffestWriter.BaseStream.Position = posToFillEndOffest;
                    blockOffestWriter.Write(endOffest);
                    blockOffestWriter.BaseStream.Seek(0, SeekOrigin.End);

                    reader.ReadByte();         // 0x72

                    block.Add(s);
                }
                break;

                case 0x6A:     // 常规Call
                {
                    if (unexaminedCode != null)
                    {
                        block.Add(new UnexaminedStatement()
                            {
                                UnexaminedCode = unexaminedCode,
                                Mask           = mask
                            });
                    }
                    else
                    {
                        if (exp.LibraryId == -1)
                        {
                            block.Add(new ExpressionStatement()
                                {
                                    Expression = null,
                                    Comment    = comment
                                });
                        }
                        else
                        {
                            block.Add(new ExpressionStatement()
                                {
                                    Expression = exp,
                                    Comment    = comment,
                                    Mask       = mask
                                });
                        }
                    }
                }
                break;
                }
            }
            return(block);
        }
Beispiel #29
0
			public override object Visit (Switch switchStatement)
			{
				var result = new SwitchStatement ();
				
				var location = LocationsBag.GetLocations (switchStatement);
				result.AddChild (new CSharpTokenNode (Convert (switchStatement.loc), "switch".Length), SwitchStatement.Roles.Keyword);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), SwitchStatement.Roles.LPar);
				result.AddChild ((INode)switchStatement.Expr.Accept (this), SwitchStatement.Roles.Expression);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), SwitchStatement.Roles.RPar);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[2]), 1), SwitchStatement.Roles.LBrace);
				foreach (var section in switchStatement.Sections) {
					var newSection = new MonoDevelop.CSharp.Dom.SwitchSection ();
					foreach (var caseLabel in section.Labels) {
						var newLabel = new CaseLabel ();
						newLabel.AddChild (new CSharpTokenNode (Convert (caseLabel.Location), "case".Length), SwitchStatement.Roles.Keyword);
						if (caseLabel.Label != null)
							newLabel.AddChild ((INode)caseLabel.Label.Accept (this), SwitchStatement.Roles.Expression);
						
						newSection.AddChild (newLabel, MonoDevelop.CSharp.Dom.SwitchSection.CaseLabelRole);
					}
					newSection.AddChild ((INode)section.Block.Accept (this), MonoDevelop.CSharp.Dom.SwitchSection.Roles.Body);
					result.AddChild (newSection, SwitchStatement.SwitchSectionRole);
				}
				
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[3]), 1), SwitchStatement.Roles.RBrace);
				return result;
			}
Beispiel #30
0
            public override ControlFlowNode VisitSwitchStatement(SwitchStatement switchStatement, ControlFlowNode data)
            {
                // First, figure out which switch section will get called (if the expression is constant):
                ConstantResolveResult constant                 = builder.EvaluateConstant(switchStatement.Expression);
                SwitchSection         defaultSection           = null;
                SwitchSection         sectionMatchedByConstant = null;

                foreach (SwitchSection section in switchStatement.SwitchSections)
                {
                    foreach (CaseLabel label in section.CaseLabels)
                    {
                        if (label.Expression.IsNull)
                        {
                            defaultSection = section;
                        }
                        else if (constant != null)
                        {
                            ConstantResolveResult labelConstant = builder.EvaluateConstant(label.Expression);
                            if (builder.AreEqualConstants(constant, labelConstant))
                            {
                                sectionMatchedByConstant = section;
                            }
                        }
                    }
                }
                if (constant != null && sectionMatchedByConstant == null)
                {
                    sectionMatchedByConstant = defaultSection;
                }

                int gotoCaseOrDefaultInOuterScope = gotoCaseOrDefault.Count;

                ControlFlowNode end = builder.CreateEndNode(switchStatement, addToNodeList: false);

                breakTargets.Push(end);
                foreach (SwitchSection section in switchStatement.SwitchSections)
                {
                    if (constant == null || section == sectionMatchedByConstant)
                    {
                        HandleStatementList(section.Statements, data);
                    }
                    else
                    {
                        // This section is unreachable: pass null to HandleStatementList.
                        HandleStatementList(section.Statements, null);
                    }
                    // Don't bother connecting the ends of the sections: the 'break' statement takes care of that.
                }
                breakTargets.Pop();
                if (defaultSection == null && sectionMatchedByConstant == null)
                {
                    Connect(data, end);
                }

                if (gotoCaseOrDefault.Count > gotoCaseOrDefaultInOuterScope)
                {
                    // Resolve 'goto case' statements:
                    throw new NotImplementedException();
                }

                builder.nodes.Add(end);
                return(end);
            }
		public override void VisitSwitchStatement(SwitchStatement switchStatement)
		{
			ForceSpacesBefore(switchStatement.LParToken, policy.SpaceBeforeSwitchParentheses);

			ForceSpacesAfter(switchStatement.LParToken, policy.SpacesWithinSwitchParentheses);
			ForceSpacesBefore(switchStatement.RParToken, policy.SpacesWithinSwitchParentheses);

			EnforceBraceStyle(policy.StatementBraceStyle, switchStatement.LBraceToken, switchStatement.RBraceToken);
			VisitChildren(switchStatement);
		}
Beispiel #32
0
            public override ControlFlowNode VisitSwitchStatement(SwitchStatement switchStatement, ControlFlowNode data)
            {
                // First, figure out which switch section will get called (if the expression is constant):
                ResolveResult constant                 = builder.EvaluateConstant(switchStatement.Expression);
                SwitchSection defaultSection           = null;
                SwitchSection sectionMatchedByConstant = null;

                foreach (SwitchSection section in switchStatement.SwitchSections)
                {
                    foreach (CaseLabel label in section.CaseLabels)
                    {
                        if (label.Expression.IsNull)
                        {
                            defaultSection = section;
                        }
                        else if (constant != null && constant.IsCompileTimeConstant)
                        {
                            ResolveResult labelConstant = builder.EvaluateConstant(label.Expression);
                            if (builder.AreEqualConstants(constant, labelConstant))
                            {
                                sectionMatchedByConstant = section;
                            }
                        }
                    }
                }
                if (constant != null && constant.IsCompileTimeConstant && sectionMatchedByConstant == null)
                {
                    sectionMatchedByConstant = defaultSection;
                }

                int gotoCaseOrDefaultInOuterScope        = gotoCaseOrDefault.Count;
                List <ControlFlowNode> sectionStartNodes = new List <ControlFlowNode>();

                ControlFlowNode end = builder.CreateEndNode(switchStatement, addToNodeList: false);

                breakTargets.Push(end);
                foreach (SwitchSection section in switchStatement.SwitchSections)
                {
                    int sectionStartNodeID = builder.nodes.Count;
                    if (constant == null || !constant.IsCompileTimeConstant || section == sectionMatchedByConstant)
                    {
                        HandleStatementList(section.Statements, data);
                    }
                    else
                    {
                        // This section is unreachable: pass null to HandleStatementList.
                        HandleStatementList(section.Statements, null);
                    }
                    // Don't bother connecting the ends of the sections: the 'break' statement takes care of that.

                    // Store the section start node for 'goto case' statements.
                    sectionStartNodes.Add(sectionStartNodeID < builder.nodes.Count ? builder.nodes[sectionStartNodeID] : null);
                }
                breakTargets.Pop();
                if (defaultSection == null && sectionMatchedByConstant == null)
                {
                    Connect(data, end);
                }

                if (gotoCaseOrDefault.Count > gotoCaseOrDefaultInOuterScope)
                {
                    // Resolve 'goto case' statements:
                    for (int i = gotoCaseOrDefaultInOuterScope; i < gotoCaseOrDefault.Count; i++)
                    {
                        ControlFlowNode   gotoCaseNode      = gotoCaseOrDefault[i];
                        GotoCaseStatement gotoCaseStatement = gotoCaseNode.NextStatement as GotoCaseStatement;
                        ResolveResult     gotoCaseConstant  = null;
                        if (gotoCaseStatement != null)
                        {
                            gotoCaseConstant = builder.EvaluateConstant(gotoCaseStatement.LabelExpression);
                        }
                        int targetSectionIndex  = -1;
                        int currentSectionIndex = 0;
                        foreach (SwitchSection section in switchStatement.SwitchSections)
                        {
                            foreach (CaseLabel label in section.CaseLabels)
                            {
                                if (gotoCaseStatement != null)
                                {
                                    // goto case
                                    if (!label.Expression.IsNull)
                                    {
                                        ResolveResult labelConstant = builder.EvaluateConstant(label.Expression);
                                        if (builder.AreEqualConstants(gotoCaseConstant, labelConstant))
                                        {
                                            targetSectionIndex = currentSectionIndex;
                                        }
                                    }
                                }
                                else
                                {
                                    // goto default
                                    if (label.Expression.IsNull)
                                    {
                                        targetSectionIndex = currentSectionIndex;
                                    }
                                }
                            }
                            currentSectionIndex++;
                        }
                        if (targetSectionIndex >= 0 && sectionStartNodes[targetSectionIndex] != null)
                        {
                            Connect(gotoCaseNode, sectionStartNodes[targetSectionIndex], ControlFlowEdgeType.Jump);
                        }
                        else
                        {
                            Connect(gotoCaseNode, end, ControlFlowEdgeType.Jump);
                        }
                    }
                    gotoCaseOrDefault.RemoveRange(gotoCaseOrDefaultInOuterScope, gotoCaseOrDefault.Count - gotoCaseOrDefaultInOuterScope);
                }

                builder.nodes.Add(end);
                return(end);
            }
 /**
  * Call back method that must be called as soon as the given <code>
  * SwitchStatement</code> object has been traversed.
  *
  * @param pSwitchStatement  The <code>SwitchStatement</code> object that has
  *                          just been traversed.
  */
 public void actionPerformed(
      SwitchStatement pSwitchStatement)
 {
     // Nothing to do.
 }
 public virtual void VisitSwitchStatement(SwitchStatement node)
 {
     Visit(node.Condition);
     Visit(node.Cases);
 }
Beispiel #35
0
        public void Visit(SwitchStatement expression)
        {
            outStream.Write("switch (");
            expression.Expression.Accept(this);
            outStream.WriteLine(") {");

            foreach (var cc in expression.CaseClauses)
            {
                if (cc.IsDefault)
                    outStream.WriteLine("default:");
                else
                {
                    outStream.Write("case ");
                    cc.Expression.Accept(this);
                    outStream.WriteLine(":");
                }

                VisitStatements(cc.Statements);
            }

            outStream.Write("}");
        }
 public override void VisitSwitchStatement(SwitchStatement syntax)
 {
     _underlyingVisitor.VisitSwitchStatement(syntax);
 }
		public void SwitchWithGotoCase()
		{
			SwitchStatement @switch = new SwitchStatement {
				Expression = new PrimitiveExpression(1),
				SwitchSections = {
					new SwitchSection { // case 0:
						CaseLabels = { new CaseLabel(new PrimitiveExpression(0)) },
						Statements = { new BreakStatement() }
					},
					new SwitchSection { // case 1:
						CaseLabels = { new CaseLabel(new PrimitiveExpression(1)) },
						Statements = {
							new ExpressionStatement(new AssignmentExpression(new IdentifierExpression("a"), new PrimitiveExpression(0))),
							new GotoCaseStatement { LabelExpression = new PrimitiveExpression(2) }
						}
					},
					new SwitchSection { // case 2:
						CaseLabels = { new CaseLabel(new PrimitiveExpression(2)) },
						Statements = { new BreakStatement() }
					}
				}};
			
			SwitchSection case0 = @switch.SwitchSections.ElementAt(0);
			SwitchSection case1 = @switch.SwitchSections.ElementAt(1);
			SwitchSection case2 = @switch.SwitchSections.ElementAt(2);
			
			DefiniteAssignmentAnalysis da = CreateDefiniteAssignmentAnalysis(@switch);
			da.Analyze("a");
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(@switch));
			Assert.AreEqual(DefiniteAssignmentStatus.CodeUnreachable, da.GetStatusBefore(case0.Statements.First()));
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(case1.Statements.First()));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusBefore(case2.Statements.First()));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusAfter(@switch));
		}
Beispiel #38
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------

        public virtual void VisitSwitchStatement(SwitchStatement statement)
        {
            VisitAbstractStatement(statement);
        }
 public virtual bool Enter(SwitchStatement node)
 {
     return true;
 }
        public SwitchStatement TransformSwitchOnString(IfElseStatement node)
        {
            Match m = switchOnStringPattern.Match(node);

            if (!m.Success)
            {
                return(null);
            }
            // switchVar must be the same as switchExpr; or switchExpr must be an assignment and switchVar the left side of that assignment
            if (!m.Get("switchVar").Single().IsMatch(m.Get("switchExpr").Single()))
            {
                AssignmentExpression assign = m.Get("switchExpr").Single() as AssignmentExpression;
                if (!(assign != null && m.Get("switchVar").Single().IsMatch(assign.Left)))
                {
                    return(null);
                }
            }
            FieldReference cachedDictField = m.Get <AstNode>("cachedDict").Single().Annotation <FieldReference>();

            if (cachedDictField == null)
            {
                return(null);
            }
            List <Statement> dictCreation           = m.Get <BlockStatement>("dictCreation").Single().Statements.ToList();
            List <KeyValuePair <string, int> > dict = BuildDictionary(dictCreation);
            SwitchStatement sw = m.Get <SwitchStatement>("switch").Single();

            sw.Expression = m.Get <Expression>("switchExpr").Single().Detach();
            foreach (SwitchSection section in sw.SwitchSections)
            {
                List <CaseLabel> labels = section.CaseLabels.ToList();
                section.CaseLabels.Clear();
                foreach (CaseLabel label in labels)
                {
                    PrimitiveExpression expr = label.Expression as PrimitiveExpression;
                    if (expr == null || !(expr.Value is int))
                    {
                        continue;
                    }
                    int val = (int)expr.Value;
                    foreach (var pair in dict)
                    {
                        if (pair.Value == val)
                        {
                            section.CaseLabels.Add(new CaseLabel {
                                Expression = new PrimitiveExpression(pair.Key)
                            });
                        }
                    }
                }
            }
            if (m.Has("nullStmt"))
            {
                SwitchSection section = new SwitchSection();
                section.CaseLabels.Add(new CaseLabel {
                    Expression = new NullReferenceExpression()
                });
                BlockStatement block = m.Get <BlockStatement>("nullStmt").Single();
                block.Statements.Add(new BreakStatement());
                section.Statements.Add(block.Detach());
                sw.SwitchSections.Add(section);
            }
            else if (m.Has("nonNullDefaultStmt"))
            {
                sw.SwitchSections.Add(
                    new SwitchSection {
                    CaseLabels = { new CaseLabel {
                                       Expression = new NullReferenceExpression()
                                   } },
                    Statements = { new BlockStatement {
                                       new BreakStatement()
                                   } }
                });
            }
            if (m.Has("nonNullDefaultStmt"))
            {
                SwitchSection section = new SwitchSection();
                section.CaseLabels.Add(new CaseLabel());
                BlockStatement block = new BlockStatement();
                block.Statements.AddRange(m.Get <Statement>("nonNullDefaultStmt").Select(s => s.Detach()));
                block.Add(new BreakStatement());
                section.Statements.Add(block);
                sw.SwitchSections.Add(section);
            }
            node.ReplaceWith(sw);
            return(sw);
        }
Beispiel #41
0
        public override StringBuilder VisitSwitchStatement(SwitchStatement switchStatement, int data)
        {
            var result = new StringBuilder("switch (").Append(switchStatement.Expression.AcceptVisitor(this, data)).Append(")");

            result.Append(Environment.NewLine + "{");

            foreach (var section in switchStatement.SwitchSections)
                result.Append(Environment.NewLine).Append(Indent(section, section.AcceptVisitor(this, data)));

            result.Append(Environment.NewLine + "}");

            return result;
        }
Beispiel #42
0
        public override void visit_switch_statement(SwitchStatement stmt)
        {
            if (unreachable(stmt))
            {
                return;
            }

            var after_switch_block = new BasicBlock();

            jump_stack.Add(JumpTarget.break_target(after_switch_block));

            // condition
            current_block.add_node(stmt.expression);
            var condition_block = current_block;

            handle_errors(stmt.expression);

            bool has_default_label = false;

            foreach (SwitchSection section in stmt.get_sections())
            {
                current_block = new BasicBlock();
                condition_block.connect(current_block);
                foreach (Statement section_stmt in section.get_statements())
                {
                    section_stmt.node.accept(this);
                }

                if (section.has_default_label())
                {
                    has_default_label = true;
                }

                if (current_block != null)
                {
                    // end of switch section reachable
                    // we don't allow fall-through

                    Report.error(section.source_reference, "missing break statement at end of switch section");
                    section.error = true;

                    current_block.connect(after_switch_block);
                }
            }

            if (!has_default_label)
            {
                condition_block.connect(after_switch_block);
            }

            // after switch
            // reachable?
            if (after_switch_block.get_predecessors().Count > 0)
            {
                current_block = after_switch_block;
            }
            else
            {
                mark_unreachable();
            }

            jump_stack.RemoveAt(jump_stack.Count - 1);
        }
			public override void VisitSwitchStatement(SwitchStatement switchStatement) {
				// Switch statements start a new context so we don't want to go there.
			}
Beispiel #44
0
 public override void VisitSwitchStatement(SwitchStatement switchStatement)
 {
     new SwitchBlock(this, switchStatement).Emit();
 }
Beispiel #45
0
 public override bool Enter(SwitchStatement node)
 {
     Print("SwitchStatement");
     level++;
     return true;
 }
 public virtual object VisitSwitchStatement(SwitchStatement switchStatement, object data)
 {
     throw new global::System.NotImplementedException("SwitchStatement");
 }
		public virtual void Visit(SwitchStatement s)
		{
			VisitChildren(s);

			if (s.SwitchExpression != null)
				s.SwitchExpression.Accept(this);
		}
 public override ICodeNode VisitSwitchStatement(SwitchStatement node)
 {
     fixSwitchCasesStep.FixCases(node);
     return(base.VisitSwitchStatement(fixSwitchConditionStep.VisitSwitchStatement(node)));
 }
		public virtual void Visit(SwitchStatement.DefaultStatement s)
		{
			VisitChildren(s);
		}
 public virtual bool Enter(SwitchStatement node)
 {
     return(true);
 }
 // SwitchStatement
 protected internal virtual bool Walk(SwitchStatement node) { return true; }
 public virtual void Exit(SwitchStatement node)
 {
 }
Beispiel #53
0
		IEnumerable<Statement> TransformNode(ILNode node)
		{
			if (node is ILLabel) {
				yield return new Ast.LabelStatement { Label = ((ILLabel)node).Name };
			} else if (node is ILExpression) {
				List<ILRange> ilRanges = ILRange.OrderAndJoint(node.GetSelfAndChildrenRecursive<ILExpression>().SelectMany(e => e.ILRanges));
				AstNode codeExpr = TransformExpression((ILExpression)node);
				if (codeExpr != null) {
					codeExpr = codeExpr.WithAnnotation(ilRanges);
					if (codeExpr is Ast.Expression) {
						yield return new Ast.ExpressionStatement { Expression = (Ast.Expression)codeExpr };
					} else if (codeExpr is Ast.Statement) {
						yield return (Ast.Statement)codeExpr;
					} else {
						throw new Exception();
					}
				}
			} else if (node is ILWhileLoop) {
				ILWhileLoop ilLoop = (ILWhileLoop)node;
				WhileStatement whileStmt = new WhileStatement() {
					Condition = ilLoop.Condition != null ? (Expression)TransformExpression(ilLoop.Condition) : new PrimitiveExpression(true),
					EmbeddedStatement = TransformBlock(ilLoop.BodyBlock)
				};
				yield return whileStmt;
			} else if (node is ILCondition) {
				ILCondition conditionalNode = (ILCondition)node;
				bool hasFalseBlock = conditionalNode.FalseBlock.EntryGoto != null || conditionalNode.FalseBlock.Body.Count > 0;
				yield return new Ast.IfElseStatement {
					Condition = (Expression)TransformExpression(conditionalNode.Condition),
					TrueStatement = TransformBlock(conditionalNode.TrueBlock),
					FalseStatement = hasFalseBlock ? TransformBlock(conditionalNode.FalseBlock) : null
				};
			} else if (node is ILSwitch) {
				ILSwitch ilSwitch = (ILSwitch)node;
				SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) };
				foreach (var caseBlock in ilSwitch.CaseBlocks) {
					SwitchSection section = new SwitchSection();
					if (caseBlock.Values != null) {
						section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, ilSwitch.Condition.InferredType) }));
					} else {
						section.CaseLabels.Add(new CaseLabel());
					}
					section.Statements.Add(TransformBlock(caseBlock));
					switchStmt.SwitchSections.Add(section);
				}
				yield return switchStmt;
			} else if (node is ILTryCatchBlock) {
				ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node);
				var tryCatchStmt = new Ast.TryCatchStatement();
				tryCatchStmt.TryBlock = TransformBlock(tryCatchNode.TryBlock);
				foreach (var catchClause in tryCatchNode.CatchBlocks) {
					if (catchClause.ExceptionVariable == null
					    && (catchClause.ExceptionType == null || catchClause.ExceptionType.MetadataType == MetadataType.Object))
					{
						tryCatchStmt.CatchClauses.Add(new Ast.CatchClause { Body = TransformBlock(catchClause) });
					} else {
						tryCatchStmt.CatchClauses.Add(
							new Ast.CatchClause {
								Type = AstBuilder.ConvertType(catchClause.ExceptionType),
								VariableName = catchClause.ExceptionVariable == null ? null : catchClause.ExceptionVariable.Name,
								Body = TransformBlock(catchClause)
							});
					}
				}
				if (tryCatchNode.FinallyBlock != null)
					tryCatchStmt.FinallyBlock = TransformBlock(tryCatchNode.FinallyBlock);
				if (tryCatchNode.FaultBlock != null) {
					CatchClause cc = new CatchClause();
					cc.Body = TransformBlock(tryCatchNode.FaultBlock);
					cc.Body.Add(new ThrowStatement()); // rethrow
					tryCatchStmt.CatchClauses.Add(cc);
				}
				yield return tryCatchStmt;
			} else if (node is ILFixedStatement) {
				ILFixedStatement fixedNode = (ILFixedStatement)node;
				FixedStatement fixedStatement = new FixedStatement();
				foreach (ILExpression initializer in fixedNode.Initializers) {
					Debug.Assert(initializer.Code == ILCode.Stloc);
					ILVariable v = (ILVariable)initializer.Operand;
					fixedStatement.Variables.Add(
						new VariableInitializer {
							Name = v.Name,
							Initializer = (Expression)TransformExpression(initializer.Arguments[0])
						}.WithAnnotation(v));
				}
				fixedStatement.Type = AstBuilder.ConvertType(((ILVariable)fixedNode.Initializers[0].Operand).Type);
				fixedStatement.EmbeddedStatement = TransformBlock(fixedNode.BodyBlock);
				yield return fixedStatement;
			} else if (node is ILBlock) {
				yield return TransformBlock((ILBlock)node);
			} else {
				throw new Exception("Unknown node type");
			}
		}
Beispiel #54
0
 public SwitchBlock(IEmitter emitter, SwitchStatement switchStatement)
     : base(emitter, switchStatement)
 {
     this.Emitter         = emitter;
     this.SwitchStatement = switchStatement;
 }
		public override void VisitSwitchStatement (SwitchStatement switchStatement)
		{
			if (!switchStatement.RBraceToken.IsNull)
				AddFolding (GetEndOfPrev(switchStatement.LBraceToken),
				            switchStatement.RBraceToken.EndLocation);
			base.VisitSwitchStatement (switchStatement);
		}
Beispiel #56
0
        protected void VisitAsyncSwitchStatement()
        {
            SwitchStatement switchStatement = this.SwitchStatement;

            this.ParentAsyncSwitch   = this.Emitter.AsyncSwitch;
            this.Emitter.AsyncSwitch = switchStatement;

            this.WriteAwaiters(switchStatement.Expression);

            var oldValue = this.Emitter.ReplaceAwaiterByVar;

            this.Emitter.ReplaceAwaiterByVar = true;
            string key = null;

            if (switchStatement.Expression is IdentifierExpression)
            {
                var oldBuilder = this.Emitter.Output;
                this.Emitter.Output = new StringBuilder();

                switchStatement.Expression.AcceptVisitor(this.Emitter);
                key = this.Emitter.Output.ToString().Trim();

                this.Emitter.Output = oldBuilder;
            }
            else
            {
                key = this.AddLocal(this.GetTempVarName(), AstType.Null);
                this.Write(key);
                this.Write(" = ");
                switchStatement.Expression.AcceptVisitor(this.Emitter);
                this.WriteSemiColon();
                this.WriteNewLine();
            }

            this.Emitter.ReplaceAwaiterByVar = oldValue;

            var list = switchStatement.SwitchSections.ToList();

            list.Sort((s1, s2) =>
            {
                var lbl = s1.CaseLabels.FirstOrDefault(l => l.Expression.IsNull);

                if (lbl != null)
                {
                    return(1);
                }

                lbl = s2.CaseLabels.FirstOrDefault(l => l.Expression.IsNull);

                if (lbl != null)
                {
                    return(-1);
                }

                return(0);
            });

            var jumpStatements = this.Emitter.JumpStatements;

            this.Emitter.JumpStatements = new List <IJumpInfo>();
            bool writeElse = false;
            var  thisStep  = this.Emitter.AsyncBlock.Steps.Last();

            foreach (var switchSection in list)
            {
                this.VisitAsyncSwitchSection(switchSection, writeElse, key);
                writeElse = true;
            }

            var nextStep = this.Emitter.AsyncBlock.AddAsyncStep();

            thisStep.JumpToStep = nextStep.Step;

            if (this.Emitter.JumpStatements.Count > 0)
            {
                this.Emitter.JumpStatements.Sort((j1, j2) => - j1.Position.CompareTo(j2.Position));
                foreach (var jump in this.Emitter.JumpStatements)
                {
                    if (jump.Break)
                    {
                        jump.Output.Insert(jump.Position, nextStep.Step);
                    }
                    else if (jumpStatements != null)
                    {
                        jumpStatements.Add(jump);
                    }
                }
            }

            this.Emitter.JumpStatements = jumpStatements;
            this.Emitter.AsyncSwitch    = this.ParentAsyncSwitch;
        }
		public virtual void VisitSwitchStatement (SwitchStatement switchStatement)
		{
			VisitChildren (switchStatement);
		}
            // IfStatement not handled by visitor, but special-cased in the code consuming the control flow graph

            public override DefiniteAssignmentStatus VisitSwitchStatement(SwitchStatement switchStatement, DefiniteAssignmentStatus data)
            {
                return(switchStatement.Expression.AcceptVisitor(this, data));
            }
Beispiel #59
0
		public void VisitSwitchStatement(SwitchStatement switchStatement)
		{
			StartNode(switchStatement);
			WriteKeyword(SwitchStatement.SwitchKeywordRole);
			Space(policy.SpaceBeforeSwitchParentheses);
			LPar();
			Space(policy.SpacesWithinSwitchParentheses);
			switchStatement.Expression.AcceptVisitor(this);
			Space(policy.SpacesWithinSwitchParentheses);
			RPar();
			OpenBrace(policy.StatementBraceStyle);
			if (!policy.IndentSwitchBody) {
				formatter.Unindent();
			}
			
			foreach (var section in switchStatement.SwitchSections) {
				section.AcceptVisitor(this);
			}
			
			if (!policy.IndentSwitchBody) {
				formatter.Indent();
			}
			CloseBrace(policy.StatementBraceStyle);
			NewLine();
			EndNode(switchStatement);
		}
Beispiel #60
0
 public override object VisitSwitchStatement(SwitchStatement switchStatement, object data)
 {
     return(base.VisitSwitchStatement(switchStatement, true));
 }