示例#1
0
 public override void VisitForStatement(ForStatement forStatement)
 {
     if (findReturn)
     {
         base.VisitForStatement(forStatement);
     }
 }
		public void Run (RefactoringContext context)
		{
			var foreachStatement = GetForeachStatement (context);
			
			var result = context.ResolveType (foreachStatement.InExpression);
			var countProperty = GetCountProperty (result);
			
			var initializer = new VariableDeclarationStatement (new PrimitiveType ("int"), "i", new PrimitiveExpression (0));
			var id1 = new IdentifierExpression ("i");
			var id2 = id1.Clone ();
			var id3 = id1.Clone ();
			
			var forStatement = new ForStatement () {
				Initializers = { initializer },
				Condition = new BinaryOperatorExpression (id1, BinaryOperatorType.LessThan, new MemberReferenceExpression (foreachStatement.InExpression.Clone (), countProperty)),
				Iterators = { new ExpressionStatement (new UnaryOperatorExpression (UnaryOperatorType.PostIncrement, id2)) },
				EmbeddedStatement = new BlockStatement {
					new VariableDeclarationStatement (foreachStatement.VariableType.Clone (), foreachStatement.VariableName, new IndexerExpression (foreachStatement.InExpression.Clone (), id3))
				}
			};
			
			if (foreachStatement.EmbeddedStatement is BlockStatement) {
				foreach (var child in ((BlockStatement)foreachStatement.EmbeddedStatement).Statements) {
					forStatement.EmbeddedStatement.AddChild (child.Clone (), BlockStatement.StatementRole);
				}
			} else {
				forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
			}
			
			using (var script = context.StartScript ()) {
				script.Replace (foreachStatement, forStatement);
				script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
			}
		}
示例#3
0
文件: Mangle.cs 项目: evanw/minisharp
        public override void VisitForStatement(ForStatement node)
        {
            VisitChildren(node);

            // Special-case constant conditions
            var constant = BoolConstant(node.Condition);
            if (constant == true) {
                node.Condition.Remove();
            }

            ReplaceBlockWithSingleStatement(node.EmbeddedStatement);
        }
			public override void VisitForStatement (ForStatement forStatement)
			{
				base.VisitForStatement (forStatement);

				if (forStatement.Initializers.Count != 1)
					return;
				var variableDecl = forStatement.Initializers.First () as VariableDeclarationStatement;
				if (variableDecl == null)
					return;

				VariableInitializer controlVariable = null;
				if (forStatement.Condition is BinaryOperatorExpression) {
					controlVariable = GetControlVariable (variableDecl, (BinaryOperatorExpression)forStatement.Condition);
				} else if (forStatement.Condition is UnaryOperatorExpression) {
					controlVariable = GetControlVariable (variableDecl, (UnaryOperatorExpression)forStatement.Condition);
				} else if (forStatement.Condition is IdentifierExpression) {
					controlVariable = variableDecl.Variables.FirstOrDefault (
						v => v.Name == ((IdentifierExpression)forStatement.Condition).Identifier);
				}

				if (controlVariable == null)
					return;

				var localResolveResult = ctx.Resolve (controlVariable) as LocalResolveResult;
				if (localResolveResult == null)
					return;

				var results = ctx.FindReferences (forStatement, localResolveResult.Variable);
				var modified = false;
				foreach (var result in results) {
					if (modified)
						break;
					var node = result.Node;
					var unary = node.Parent as UnaryOperatorExpression;
					if (unary != null && unary.Expression == node) {
						modified = unary.Operator == UnaryOperatorType.Decrement ||
							unary.Operator == UnaryOperatorType.PostDecrement ||
							unary.Operator == UnaryOperatorType.Increment ||
							unary.Operator == UnaryOperatorType.PostIncrement;
						continue;
					}

					var assignment = node.Parent as AssignmentExpression;
					modified = assignment != null && assignment.Left == node;
				}

				if (!modified)
					AddIssue (controlVariable.NameToken,
						ctx.TranslateString ("'for' loop control variable is never modified"));

			}
		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var foreachStatement = GetForeachStatement(context);
			if (foreachStatement == null) {
				yield break;
			}
			yield return new CodeAction(context.TranslateString("Convert 'foreach' loop to 'for'"), script => {
				var result = context.Resolve(foreachStatement.InExpression);
				var countProperty = GetCountProperty(result.Type);
				
				// TODO: use another variable name if 'i' is already in use
				var initializer = new VariableDeclarationStatement(new PrimitiveType("int"), "i", new PrimitiveExpression(0));
				var id1 = new IdentifierExpression("i");
				var id2 = id1.Clone();
				var id3 = id1.Clone();
				
				var variableDeclarationStatement = new VariableDeclarationStatement(
					foreachStatement.VariableType.Clone(),
					foreachStatement.VariableName,
					new IndexerExpression(foreachStatement.InExpression.Clone(), id3)
				);
				var forStatement = new ForStatement() {
					Initializers = { initializer },
					Condition = new BinaryOperatorExpression (id1, BinaryOperatorType.LessThan, new MemberReferenceExpression (foreachStatement.InExpression.Clone (), countProperty)),
					Iterators = { new ExpressionStatement (new UnaryOperatorExpression (UnaryOperatorType.PostIncrement, id2)) },
					EmbeddedStatement = new BlockStatement {
						variableDeclarationStatement
					}
				};
				
				if (foreachStatement.EmbeddedStatement is BlockStatement) {
					variableDeclarationStatement.Remove();
					var oldBlock = (BlockStatement)foreachStatement.EmbeddedStatement.Clone();
					if (oldBlock.Statements.Any()) {
						oldBlock.Statements.InsertBefore(oldBlock.Statements.First(), variableDeclarationStatement);
					} else {
						oldBlock.Statements.Add(variableDeclarationStatement);
					}
					forStatement.EmbeddedStatement = oldBlock;
				} else {
					forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
				}
				script.Replace (foreachStatement, forStatement);
				script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
			});
		}
            public override void VisitForStatement(ForStatement forStatement)
            {
                base.VisitForStatement(forStatement);

                if (forStatement.Initializers.Count != 1)
                {
                    return;
                }
                var variableDecl = forStatement.Initializers.First() as VariableDeclarationStatement;

                if (variableDecl == null)
                {
                    return;
                }

                VariableInitializer controlVariable = null;

                if (forStatement.Condition is BinaryOperatorExpression)
                {
                    controlVariable = GetControlVariable(variableDecl, (BinaryOperatorExpression)forStatement.Condition);
                }
                else if (forStatement.Condition is UnaryOperatorExpression)
                {
                    controlVariable = GetControlVariable(variableDecl, (UnaryOperatorExpression)forStatement.Condition);
                }
                else if (forStatement.Condition is IdentifierExpression)
                {
                    controlVariable = variableDecl.Variables.FirstOrDefault(
                        v => v.Name == ((IdentifierExpression)forStatement.Condition).Identifier);
                }

                if (controlVariable == null)
                {
                    return;
                }

                var localResolveResult = ctx.Resolve(controlVariable) as LocalResolveResult;

                if (localResolveResult == null)
                {
                    return;
                }

                var results  = ctx.FindReferences(forStatement, localResolveResult.Variable);
                var modified = false;

                foreach (var result in results)
                {
                    if (modified)
                    {
                        break;
                    }
                    var node  = result.Node;
                    var unary = node.Parent as UnaryOperatorExpression;
                    if (unary != null && unary.Expression == node)
                    {
                        modified = unary.Operator == UnaryOperatorType.Decrement ||
                                   unary.Operator == UnaryOperatorType.PostDecrement ||
                                   unary.Operator == UnaryOperatorType.Increment ||
                                   unary.Operator == UnaryOperatorType.PostIncrement;
                        continue;
                    }

                    var assignment = node.Parent as AssignmentExpression;
                    modified = assignment != null && assignment.Left == node;
                }

                if (!modified)
                {
                    AddIssue(controlVariable.NameToken,
                             ctx.TranslateString("'for' loop control variable is never modified"));
                }
            }
示例#7
0
    public Expr ProcessOperand(object operand, FunctionBlock block, bool isInsideBoolean = false)
    {
        Expr                     returnExpr  = new Expr();
        StringBuilder            exprBuilder = new StringBuilder();
        bool                     hasSign     = false;
        DeclareVariableStatement resultVar   = new DeclareVariableStatement();

        resultVar.IsHidden = true;
        int insertResultIndex = block.Statements.Count;

        block.Statements.Add("");
        char signChar = ' ';

        if (operand is ExprAtom)
        {
            if ((operand as ExprAtom).Op == ExprAtom.UnaryOp.Inverse)
            {
                signChar = '!';
            }
            else if ((operand as ExprAtom).Op == ExprAtom.UnaryOp.Not)
            {
                signChar = '-';
            }
            operand = (operand as ExprAtom).Content;
        }

        BindingFlags any = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public;

        if (operand is Scope)
        {
            //bool exprIsResultVar = false;
            var  scope           = (operand as Scope).Parts;
            bool contextVariable = true;
            var  contextVar      = block.FindStatement <DeclareVariableStatement> (v => v.Name == scope [0] as string);
            if (contextVariable = (contextVar == null))
            {
                contextVar = block.FindStatement <DeclareVariableStatement> (v => v.IsContext);
            }
            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogWarningFormat("S_CTX {0} {1}", contextVar, operand);
            }
            string contextName = null;           //!contextVariable ? "root" : contextVar.Name;
            Type   contextType = null;           //!contextVariable ? typeof(GameObject) : contextVar.Type;
            if (contextVar == null)
            {
                contextName = block.DefaultScope;
                contextType = typeof(GameObject);
            }
            else
            {
                contextName = contextVar.Name;
                contextType = contextVar.Type;
            }

            exprBuilder.Append(contextName).Append(".");
            bool          firstTimeList = true;
            FunctionBlock curBlock      = block;
            for (int i = contextVariable ? 0 : 1; i < scope.Count; i++)
            {
                if (ScriptEngine.AnalyzeDebug)
                {
                    Debug.LogWarningFormat("scope part {0} {1} {2}", scope [i], contextType.IsGenericType, contextType.IsGenericType ? (contextType.GetGenericTypeDefinition() == typeof(List <>)).ToString() : "");
                }
                if (contextType.IsGenericType && contextType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    if (firstTimeList)
                    {
                        CleanUpContextes.Push(resultVar);
                        resultVar.IsTemp = true;
                        resultVar.Name   = "result" + DeclareVariableStatement.VariableId++;
                        block.Statements [insertResultIndex] = resultVar;
                        resultVar.IsHidden = false;
                        resultVar.IsResult = true;

                        //resultList.Type = contextType;
                        //exprIsResultVar = true;
                        firstTimeList = false;
                    }
                    Debug.Log("scope list " + scope [i]);
                    DeclareVariableStatement declVar = new DeclareVariableStatement();
                    CleanUpContextes.Push(declVar);
                    declVar.IsTemp = true;
                    declVar.Name   = "list" + DeclareVariableStatement.VariableId++;
                    declVar.Type   = contextType;
                    if (exprBuilder [exprBuilder.Length - 1] == '.')
                    {
                        exprBuilder.Length -= 1;
                    }
                    if (hasSign)
                    {
                        declVar.InitExpression = exprBuilder.ToString(1, exprBuilder.Length - 1);
                        exprBuilder.Length     = 1;
                        //exprBuilder.Append (declVar.Name).Append ('.');
                    }
                    else
                    {
                        declVar.InitExpression = exprBuilder.ToString();
                        exprBuilder.Length     = 0;
                        //exprBuilder.Append (declVar.Name).Append ('.');
                    }
                    curBlock.Statements.Add(declVar);
                    ForStatement forStatement = new ForStatement();
                    forStatement.RepeatBlock = new FunctionBlock(block, block.Method, block.Type);
                    var repeatContext = new DeclareVariableStatement();
                    repeatContext.IsTemp = true;
                    CleanUpContextes.Push(repeatContext);
                    forStatement.RepeatBlock.Statements.Add(repeatContext);
                    curBlock.Statements.Add(forStatement);
                    curBlock = forStatement.RepeatBlock;
                    var iterName = "i" + DeclareVariableStatement.VariableId++;
                    forStatement.InsideExpr = String.Format(@"int {0} = 0; {0} < {1}.Count; {0}++", iterName, declVar.Name);

                    contextType                  = contextType.GetGenericArguments() [0];
                    repeatContext.Name           = "SubContext" + DeclareVariableStatement.VariableId++;
                    repeatContext.Type           = contextType;
                    repeatContext.IsContext      = true;
                    repeatContext.InitExpression = String.Format(@"{0}[{1}]", declVar.Name, iterName);
                }
                bool isFunc = false;
                if (scope [i] is FunctionCall || scope [i] is string)
                {
//					var callOp = ProcessOperand (scope [i], block);
                    Expression[] callArgs = defaultArgsList;
                    string       callName = null;
                    var          call     = scope [i] as FunctionCall;
                    if (call != null)
                    {
                        callName = call.Name;
                        callArgs = call.Args;
                    }
                    else
                    {
                        callName = scope [i] as string;
                    }
                    if (scopeInterpreters.ContainsKey(callName))
                    {
                        var    interpreter = scopeInterpreters [callName];
                        string outExpr     = null;
                        interpreter.Interpret(callArgs, curBlock, contextType, exprBuilder.ToString(), out outExpr, out curBlock, out contextType, i == scope.Count - 1);
                        if (hasSign)
                        {
                            exprBuilder.Length = 1;
                            exprBuilder.Append(outExpr).Append('.');
                        }
                        else
                        {
                            exprBuilder.Length = 0;
                            exprBuilder.Append(outExpr).Append('.');
                        }
                        isFunc = true;
                    }
                    else
                    {
                        var methodName = NameTranslator.CSharpNameFromScript(callName);
                        var method     = contextType.GetMethod(methodName);
                        if (i == 0 && method == null)
                        {
                            var otherContext = block.FindStatement <DeclareVariableStatement> (v => (v.IsContext || v.IsArg) && (method = v.Type.GetMethod(methodName, any)) != null);
                            if (otherContext != null)
                            {
                                exprBuilder.Length = hasSign ? 1 : 0;
                                if (ScriptEngine.AnalyzeDebug)
                                {
                                    Debug.LogWarning("OTHER CONTEXT" + otherContext.DebugString());
                                }
                                exprBuilder.Append(otherContext.Name).Append('.');
                                contextType = otherContext.Type;
                            }
                            else
                            {
                                if (ScriptEngine.AnalyzeDebug)
                                {
                                    Debug.LogWarning("Can't find context for method " + methodName);
                                }
                                block.FindStatement <DeclareVariableStatement> (v => {
                                    if (ScriptEngine.AnalyzeDebug)
                                    {
                                        Debug.LogFormat("{0} {1} {3}                  ||||{2}", v.Name, v.Type, IfStatement.AntiMergeValue++, v.IsContext || v.IsArg);
                                    }
                                    return(false);
                                });
                            }
                        }
                        if (method == null)
                        {
                            if (ScriptEngine.AnalyzeDebug)
                            {
                                Debug.LogFormat("Can't find {0} in {1}", NameTranslator.CSharpNameFromScript(callName), contextType);
                            }
                        }
                        else
                        {
                            exprBuilder.Append(method.Name).Append("(");
                            var argsDef = method.GetParameters();
                            if (callArgs != null)
                            {
                                for (int j = 0; j < callArgs.Length; j++)
                                {
                                    if (argsDef [j].ParameterType.IsSubclassOf(typeof(Delegate)))
                                    {
                                        exprBuilder.Append(InterpretClosure(callArgs [j], curBlock, argsDef [j].ParameterType).ExprString).Append(",");
                                    }
                                    else
                                    {
                                        exprBuilder.Append(InterpretExpression(callArgs [j], curBlock).ExprString).Append(",");
                                    }
                                }
                                if (callArgs.Length > 0)
                                {
                                    exprBuilder.Length -= 1;
                                }
                            }

                            exprBuilder.Append(")");
                            contextType = method.ReturnType;


                            var declVar = new DeclareVariableStatement();
                            CleanUpContextes.Push(declVar);
                            declVar.IsTemp    = true;
                            declVar.Name      = "prop" + DeclareVariableStatement.VariableId++;
                            declVar.IsContext = true;
                            if (exprBuilder.Length > 0 && exprBuilder [exprBuilder.Length - 1] == '.')
                            {
                                exprBuilder.Length -= 1;
                            }
                            if (hasSign)
                            {
                                declVar.InitExpression = exprBuilder.ToString(1, exprBuilder.Length - 1);
                                exprBuilder.Length     = 1;
                                exprBuilder.Append(declVar.Name).Append('.');
                            }
                            else
                            {
                                declVar.InitExpression = exprBuilder.ToString();
                                exprBuilder.Length     = 0;
                                exprBuilder.Append(declVar.Name).Append('.');
                            }
                            declVar.Type = contextType;
                            curBlock.Statements.Add(declVar);
                            if (contextType.IsClass)
                            {
                                IfStatement ifSt = new IfStatement();
                                ifSt.CheckExpression = String.Format("{0} != null", declVar.Name);
                                ifSt.TrueBlock       = new FunctionBlock(curBlock);
                                curBlock.Statements.Add(ifSt);
                                curBlock = ifSt.TrueBlock;
                            }
                            isFunc = true;
                        }
                    }
                }
                if (!isFunc)
                {
                    var propName = NameTranslator.CSharpNameFromScript(scope [i] as string);

                    var prop = contextType.GetProperty(propName);

                    if (i == 0 && prop == null)
                    {
                        var customVar = block.FindStatement <DeclareVariableStatement> (v => v.Name == scope [i] as string);
                        if (customVar == null)
                        {
                            var otherContext = block.FindStatement <DeclareVariableStatement> (v => {
                                //Debug.LogWarning (v.Type);
                                //Debug.Log (v.IsContext || v.IsArg);
                                //var props = v.Type.GetProperties (any);
                                //foreach (var allProp in props)
                                //	Debug.Log (allProp.Name);
                                return((v.IsContext || v.IsArg) && (prop = v.Type.GetProperty(propName, any)) != null);
                            });
                            if (otherContext != null)
                            {
                                exprBuilder.Length = hasSign ? 1 : 0;

                                exprBuilder.Append(otherContext.Name).Append('.');
                                contextType = otherContext.Type;
                                if (contextType.IsClass && !prop.GetGetMethod().IsStatic)
                                {
                                    IfStatement ifSt = new IfStatement();
                                    ifSt.CheckExpression = String.Format("{0} != null", otherContext.Name);
                                    ifSt.TrueBlock       = new FunctionBlock(curBlock);
                                    curBlock.Statements.Add(ifSt);
                                    curBlock = ifSt.TrueBlock;
                                }
                            }
                            else
                            if (ScriptEngine.AnalyzeDebug)
                            {
                                Debug.LogWarning("Can't find context for property " + propName);
                            }
                        }
                        else
                        {
                            exprBuilder.Length = hasSign ? 1 : 0;
                            exprBuilder.Append(customVar.Name).Append('.');
                            contextType = customVar.Type;
                            if (contextType.IsClass && !prop.GetGetMethod().IsStatic)
                            {
                                IfStatement ifSt = new IfStatement();
                                ifSt.CheckExpression = String.Format("{0} != null", customVar.Name);
                                ifSt.TrueBlock       = new FunctionBlock(curBlock);
                                curBlock.Statements.Add(ifSt);
                                curBlock = ifSt.TrueBlock;
                            }
                        }
                    }
                    if (ScriptEngine.AnalyzeDebug)
                    {
                        Debug.LogWarning(prop);
                    }
                    if (prop == null && components.ContainsKey(scope [i] as string))
                    {
                        var    type           = components [scope [i] as string];
                        string storedFromName = null;
                        if (hasSign)
                        {
                            storedFromName = exprBuilder.ToString(1, exprBuilder.Length - 1);
                        }
                        else
                        {
                            storedFromName = exprBuilder.ToString();
                        }
                        if (ScriptEngine.AnalyzeDebug)
                        {
                            Debug.LogWarning("Component found " + type);
                        }
                        var storedVar = curBlock.FindStatement <DeclareVariableStatement> (v => v.Type == type && v.storedOf != null && storedFromName == v.storedOf);

                        contextType = type;
                        if (storedVar == null)
                        {
                            storedVar = new DeclareVariableStatement();
                            CleanUpContextes.Push(storedVar);
                            storedVar.IsTemp    = true;
                            storedVar.IsContext = true;
                            curBlock.Statements.Add(storedVar);                             //block.FindStatement<DeclareVariableStatement> (v => !v.IsContext && v.Type == type);
                            storedVar.Name = "StoredVariable" + DeclareVariableStatement.VariableId++;
                            storedVar.Type = type;

                            storedVar.storedOf = hasSign ? exprBuilder.ToString(1, exprBuilder.Length) : exprBuilder.ToString(0, exprBuilder.Length);
                            exprBuilder.Append(String.Format("GetComponent(typeof({0})))", type));
                            exprBuilder.Insert(0, String.Format("(({0})", type));
                            if (hasSign)
                            {
                                storedVar.InitExpression = exprBuilder.ToString(1, exprBuilder.Length - 1);
                                exprBuilder.Length       = 1;
                                exprBuilder.Append(storedVar.Name).Append('.');
                            }
                            else
                            {
                                storedVar.InitExpression = exprBuilder.ToString();
                                exprBuilder.Length       = 0;
                                exprBuilder.Append(storedVar.Name).Append('.');
                            }
                        }
                        if (hasSign)
                        {
                            exprBuilder.Length = 1;
                            exprBuilder.Append(storedVar.Name).Append('.');
                        }
                        else
                        {
                            exprBuilder.Length = 0;
                            exprBuilder.Append(storedVar.Name).Append('.');
                        }

                        if (contextType.IsClass)
                        {
                            IfStatement ifSt = new IfStatement();
                            ifSt.CheckExpression = String.Format("{0} != null", storedVar.Name);
                            ifSt.TrueBlock       = new FunctionBlock(curBlock);
                            curBlock.Statements.Add(ifSt);
                            curBlock = ifSt.TrueBlock;
                        }
                    }
                    else if (scopeInterpreters.ContainsKey(scope [i] as string))
                    {
                        var    interpreter = scopeInterpreters [scope [i] as string];
                        string outExpr     = null;
                        interpreter.Interpret(null, curBlock, contextType, exprBuilder.ToString(), out outExpr, out curBlock, out contextType, i == scope.Count - 1);
                        if (hasSign)
                        {
                            exprBuilder.Length = 1;
                            exprBuilder.Append(outExpr).Append('.');
                        }
                        else
                        {
                            exprBuilder.Length = 0;
                            exprBuilder.Append(outExpr).Append('.');
                        }
                    }
                    else if (prop == null && scope.Count == 1)
                    {
                        if (ScriptEngine.AnalyzeDebug)
                        {
                            Debug.LogWarningFormat("Can't find {0} in {1}, interpreting as a string", propName, contextType);
                        }
                        contextType        = typeof(string);
                        exprBuilder.Length = 0;
                        exprBuilder.Append("\"").Append(scope [i]).Append("\"");
                        break;
                    }
                    else if (prop == null)
                    {
                        Debug.LogWarningFormat("Can't find {0} in {1}", propName, contextType);
                        break;
                    }
                    else
                    {
                        contextType = prop.PropertyType;
                        exprBuilder.Append(propName).Append('.');
                        var declVar = new DeclareVariableStatement();
                        CleanUpContextes.Push(declVar);
                        declVar.IsTemp    = true;
                        declVar.IsContext = true;
                        declVar.Name      = "prop" + DeclareVariableStatement.VariableId++;
                        if (exprBuilder.Length > 0 && exprBuilder [exprBuilder.Length - 1] == '.')
                        {
                            exprBuilder.Length -= 1;
                        }
                        if (hasSign)
                        {
                            declVar.InitExpression = exprBuilder.ToString(1, exprBuilder.Length - 1);
                            exprBuilder.Length     = 1;
                            exprBuilder.Append(declVar.Name).Append('.');
                        }
                        else
                        {
                            declVar.InitExpression = exprBuilder.ToString();
                            exprBuilder.Length     = 0;
                            exprBuilder.Append(declVar.Name).Append('.');
                        }
                        declVar.Type = contextType;
                        curBlock.Statements.Add(declVar);
                        if (contextType.IsClass)
                        {
                            IfStatement ifSt = new IfStatement();
                            ifSt.CheckExpression = String.Format("{0} != null", declVar.Name);
                            ifSt.TrueBlock       = new FunctionBlock(curBlock);
                            curBlock.Statements.Add(ifSt);
                            curBlock = ifSt.TrueBlock;
                        }
                    }
                }
            }
            returnExpr.Type = contextType;
            var res = resultVar;
            if (!res.IsHidden)
            {
                var list   = curBlock.FindStatement <DeclareVariableStatement> (v => v.Type != null && v.Type.IsGenericType && v.Type.GetGenericTypeDefinition() == typeof(List <>));
                var lasVar = curBlock.FindStatement <DeclareVariableStatement> (v => v.IsContext);
                if (list != null && !firstTimeList)
                {
                    curBlock.Statements.Add(String.Format(@"{0}.Add({1});", res.Name, lasVar.Name));
                    res.Type           = typeof(List <>).MakeGenericType(lasVar.Type);
                    res.InitExpression = String.Format("new {0}();", TypeName.NameOf(res.Type));
                }
                else
                {
                    res.Type = lasVar.Type;
                    curBlock.Statements.Add(String.Format(@"{0} = {1};", res.Name, lasVar.Name));
                }
                if (hasSign)
                {
                    exprBuilder.Length = 1;
                    exprBuilder.Append(res.Name).Append('.');
                }
                else
                {
                    exprBuilder.Length = 0;
                    exprBuilder.Append(res.Name).Append('.');
                }

                returnExpr.Type = res.Type;
            }

            if (!res.IsHidden && res.Type != null)
            {
                var resType = res.Type;
                res.IsResult = false;
                Debug.Log(isInsideBoolean);
                if (isInsideBoolean && resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    exprBuilder.Append(String.Format(" != null ? {0}.Count : 0", exprBuilder));
                }
            }
            if (exprBuilder.Length > 0 && exprBuilder [exprBuilder.Length - 1] == '.')
            {
                exprBuilder.Length -= 1;
            }
            if (res.IsHidden)
            {
                resultVar.Name                       = "OperandVar" + DeclareVariableStatement.VariableId++;
                resultVar.Type                       = contextType;
                resultVar.InitExpression             = string.Format("default({0})", TypeName.NameOf(contextType));
                resultVar.IsHidden                   = false;
                block.Statements [insertResultIndex] = resultVar;
                curBlock.Statements.Add(String.Format("{0} = {1};", resultVar.Name, exprBuilder));
                exprBuilder.Length = hasSign ? 1 : 0;
                var resType = res.Type;
                if (isInsideBoolean && resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    exprBuilder.Append(String.Format("{0} != null ? {0}.Count : 0", resultVar.Name));
                }
                else
                {
                    exprBuilder.Append(resultVar.Name);
                }
            }
        }
        else if (operand is FunctionCall)
        {
//			var call = operand as FunctionCall;
//			for (int i = 0; i < call.Args.Length; i++)
//			{
//
//			}
        }
        else if (operand is Expression)
        {
            var ex = InterpretExpression(operand as Expression, block, false, isInsideBoolean);
            exprBuilder.Append(ex.ExprString);
            returnExpr.Type = ex.Type;
        }
        else
        {
            returnExpr.Type = operand.GetType();
            if (operand is bool)
            {
                exprBuilder.Append((bool)operand ? "true" : "false");
            }
            else
            {
                exprBuilder.Append(operand);
            }
            if (operand is float)
            {
                exprBuilder.Append('f');
            }
        }
        string head = String.Format("{0}(", signChar);

        exprBuilder.Insert(0, head).Append(')');
        returnExpr.ExprString = exprBuilder.ToString();
        return(returnExpr);
    }
 // ForStatement
 public override bool Walk(ForStatement node) { return false; }
		public virtual void VisitForStatement (ForStatement forStatement)
		{
			VisitChildren (forStatement);
		}
		public override void VisitForStatement(ForStatement forStatement) {
			foreach (var s in forStatement.Initializers)
				s.AcceptVisitor(this);
			forStatement.Condition.AcceptVisitor(this);
			foreach (var s in forStatement.Iterators)
				s.AcceptVisitor(this);

			bool oldIsInsideLoop = _isInsideLoop;
			try {
				_isInsideLoop = true;
				forStatement.EmbeddedStatement.AcceptVisitor(this);
			}
			finally {
				_isInsideLoop = oldIsInsideLoop;
			}
		}
		public override void VisitForStatement(ForStatement forStatement) {
			// Initializer. In case we need more than one statement, put all other statements just before this loop.
			JsStatement initializer;
			if (forStatement.Initializers.Count == 1 && forStatement.Initializers.First() is VariableDeclarationStatement) {
				forStatement.Initializers.First().AcceptVisitor(this);
				initializer = _result[_result.Count - 1];
				_result.RemoveAt(_result.Count - 1);
			}
			else {
				JsExpression initExpr = null;
				foreach (var init in forStatement.Initializers) {
					var compiledInit = CompileExpression(((ExpressionStatement)init).Expression, CompileExpressionFlags.None);
					if (compiledInit.AdditionalStatements.Count == 0) {
						initExpr = (initExpr != null ? JsExpression.Comma(initExpr, compiledInit.Expression) : compiledInit.Expression);
					}
					else {
						if (initExpr != null)
							_result.Add(initExpr);
						_result.AddRange(compiledInit.AdditionalStatements);
						initExpr = compiledInit.Expression;
					}
				}
				initializer = (initExpr != null ? (JsStatement)initExpr : JsStatement.Empty);
			}

			// Condition
			JsExpression condition;
			List<JsStatement> preBody = null;
			if (!forStatement.Condition.IsNull) {
				var compiledCondition = CompileExpression(forStatement.Condition, CompileExpressionFlags.ReturnValueIsImportant);
				if (compiledCondition.AdditionalStatements.Count == 0) {
					condition = compiledCondition.Expression;
				}
				else {
					// The condition requires additional statements. Transform "for (int i = 0; i < (SomeProperty = 1); i++) { ... }" to "for (var i = 0;; i++) { this.set_SomeProperty(1); if (!(i < 1)) { break; } ... }
					preBody = new List<JsStatement>();
					preBody.AddRange(compiledCondition.AdditionalStatements);
					preBody.Add(JsStatement.If(JsExpression.LogicalNot(compiledCondition.Expression), JsStatement.Break(), null));
					condition = null;
				}
			}
			else {
				condition = null;
			}

			// Iterators
			JsExpression iterator = null;
			List<JsStatement> postBody = null;
			if (forStatement.Iterators.Count > 0) {
				var compiledIterators = forStatement.Iterators.Select(i => CompileExpression(((ExpressionStatement)i).Expression, CompileExpressionFlags.None)).ToList();
				if (compiledIterators.All(i => i.AdditionalStatements.Count == 0)) {
					// No additional statements are required, add them as a single comma-separated expression to the JS iterator.
					iterator = compiledIterators.Aggregate(iterator, (current, i) => (current != null ? JsExpression.Comma(current, i.Expression) : i.Expression));
				}
				else {
					// At least one of the compiled iterators need additional statements. We could add the last expressions that don't need extra statements to the iterators section of the for loop, but for simplicity we'll just add everything to the end of the loop.
					postBody = new List<JsStatement>();
					foreach (var i in compiledIterators) {
						postBody.AddRange(i.AdditionalStatements);
						postBody.Add(i.Expression);
					}
				}
			}

			// Body
			var body = CreateInnerCompiler().Compile(forStatement.EmbeddedStatement);

			if (preBody != null || postBody != null) {
				body = JsStatement.Block(((IEnumerable<JsStatement>)preBody ?? new JsStatement[0]).Concat(body.Statements).Concat((IEnumerable<JsStatement>)postBody ?? new JsStatement[0]));
			}

			_result.Add(JsStatement.For(initializer, condition, iterator, body));
		}
示例#12
0
 public override bool Walk(ForStatement node) => LoopHandler.HandleFor(node);
示例#13
0
 public override void VisitForStatement(ForStatement forStatement)
 {
     new ForBlock(this, forStatement).Emit();
 }
示例#14
0
        public static StatementBlock ParseStatementBlock(BinaryReader reader, CodeSectionInfo codeSectionInfo, int blockId)
        {
            StatementBlock statementBlock = new StatementBlock();

            while (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                int  num = (int)reader.BaseStream.Position;
                byte b   = reader.ReadByte();

                switch (b)
                {
                case 80:
                case 81:
                case 82:
                case 84:
                case 110:
                case 111:
                case 113:
                    reader.BaseStream.Position = num;
                    return(statementBlock);

                case 109:
                    reader.ReadByte();
                    goto default;

                default:
                {
                    string         text;
                    string         text2;
                    bool           flag;
                    CallExpression callExpression = ParseCallExpressionWithoutType(reader, codeSectionInfo, blockId, out text, out text2, out flag);
                    switch (b)
                    {
                    case 109:
                    {
                        SwitchStatement switchStatement = new SwitchStatement();
                        Expression      condition       = callExpression.ParamList.Value.ElementAtOrDefault(0);
                        StatementBlock  statementBlock2 = ParseStatementBlock(reader, codeSectionInfo, blockId);
                        while (true)
                        {
                            switch (reader.ReadByte())
                            {
                            case 110:
                                switchStatement.Case.Add(new SwitchStatement.CaseInfo
                                        {
                                            Condition   = condition,
                                            Block       = statementBlock2,
                                            UnvalidCode = text,
                                            Comment     = text2,
                                            Mask        = flag
                                        });
                                condition       = ParseCallExpressionWithoutType(reader, codeSectionInfo, blockId, out text, out text2, out flag).ParamList.Value.ElementAtOrDefault(0);
                                statementBlock2 = ParseStatementBlock(reader, codeSectionInfo, blockId);
                                continue;

                            case 111:
                                switchStatement.Case.Add(new SwitchStatement.CaseInfo
                                        {
                                            Condition   = condition,
                                            Block       = statementBlock2,
                                            UnvalidCode = text,
                                            Comment     = text2,
                                            Mask        = flag
                                        });
                                condition       = null;
                                statementBlock2 = ParseStatementBlock(reader, codeSectionInfo, blockId);
                                continue;

                            case 84:
                                break;

                            default:
                                throw new Exception();
                            }
                            break;
                        }
                        switchStatement.EndOffest = (int)reader.BaseStream.Position;
                        reader.ReadByte();
                        switchStatement.DefaultBlock = statementBlock2;
                        switchStatement.StartOffest  = num;
                        statementBlock.Statements.Add(switchStatement);
                        break;
                    }

                    case 112:
                    {
                        StatementBlock block           = ParseStatementBlock(reader, codeSectionInfo, blockId);
                        CallExpression callExpression2 = null;
                        int            endOffest3      = (int)reader.BaseStream.Position;
                        byte           b2 = reader.ReadByte();
                        if (b2 == 113)
                        {
                            callExpression2 = ParseCallExpressionWithoutType(reader, codeSectionInfo, blockId, out string unvalidCode, out string commentOnEnd, out bool maskOnEnd);
                            if (callExpression.LibraryId != 0)
                            {
                                throw new Exception();
                            }
                            LoopStatement loopStatement = null;
                            switch (callExpression.MethodId)
                            {
                            case 3:
                                loopStatement = new WhileStatement
                                {
                                    Condition   = callExpression.ParamList.Value.ElementAtOrDefault(0),
                                    Block       = block,
                                    UnvalidCode = text
                                };
                                break;

                            case 5:
                                loopStatement = new DoWhileStatement
                                {
                                    Condition   = callExpression2.ParamList.Value.ElementAtOrDefault(0),
                                    Block       = block,
                                    UnvalidCode = unvalidCode
                                };
                                break;

                            case 7:
                                loopStatement = new CounterStatement
                                {
                                    Count       = callExpression.ParamList.Value.ElementAtOrDefault(0),
                                    Var         = callExpression.ParamList.Value.ElementAtOrDefault(1),
                                    Block       = block,
                                    UnvalidCode = text
                                };
                                break;

                            case 9:
                                loopStatement = new ForStatement
                                {
                                    Start       = callExpression.ParamList.Value.ElementAtOrDefault(0),
                                    End         = callExpression.ParamList.Value.ElementAtOrDefault(1),
                                    Step        = callExpression.ParamList.Value.ElementAtOrDefault(2),
                                    Var         = callExpression.ParamList.Value.ElementAtOrDefault(3),
                                    Block       = block,
                                    UnvalidCode = text
                                };
                                break;

                            default:
                                throw new Exception();
                            }
                            loopStatement.StartOffest    = num;
                            loopStatement.EndOffest      = endOffest3;
                            loopStatement.CommentOnStart = text2;
                            loopStatement.CommentOnEnd   = commentOnEnd;
                            loopStatement.MaskOnStart    = flag;
                            loopStatement.MaskOnEnd      = maskOnEnd;
                            statementBlock.Statements.Add(loopStatement);
                            break;
                        }
                        throw new Exception();
                    }

                    case 108:
                    {
                        IfStatement ifStatement = new IfStatement
                        {
                            Condition   = callExpression.ParamList.Value.ElementAtOrDefault(0),
                            UnvalidCode = text,
                            Block       = ParseStatementBlock(reader, codeSectionInfo, blockId),
                            Comment     = text2,
                            Mask        = flag
                        };
                        if (reader.ReadByte() != 82)
                        {
                            throw new Exception();
                        }
                        int endOffest = (int)reader.BaseStream.Position;
                        reader.ReadByte();
                        ifStatement.StartOffest = num;
                        ifStatement.EndOffest   = endOffest;
                        statementBlock.Statements.Add(ifStatement);
                        break;
                    }

                    case 107:
                    {
                        IfElseStatement ifElseStatement = new IfElseStatement
                        {
                            Condition   = callExpression.ParamList.Value.ElementAtOrDefault(0),
                            UnvalidCode = text,
                            Comment     = text2,
                            Mask        = flag
                        };
                        ifElseStatement.BlockOnTrue = ParseStatementBlock(reader, codeSectionInfo, blockId);
                        if (reader.ReadByte() != 80)
                        {
                            throw new Exception();
                        }
                        ifElseStatement.BlockOnFalse = ParseStatementBlock(reader, codeSectionInfo, blockId);
                        if (reader.ReadByte() != 81)
                        {
                            throw new Exception();
                        }
                        int endOffest2 = (int)reader.BaseStream.Position;
                        reader.ReadByte();
                        ifElseStatement.StartOffest = num;
                        ifElseStatement.EndOffest   = endOffest2;
                        statementBlock.Statements.Add(ifElseStatement);
                        break;
                    }

                    default:
                        if (text != null)
                        {
                            statementBlock.Statements.Add(new UnvalidStatement
                                {
                                    UnvalidCode = text,
                                    Mask        = flag
                                });
                        }
                        else if (callExpression.LibraryId == -1)
                        {
                            statementBlock.Statements.Add(new ExpressionStatement
                                {
                                    Expression = null,
                                    Comment    = text2
                                });
                        }
                        else
                        {
                            statementBlock.Statements.Add(new ExpressionStatement
                                {
                                    Expression = callExpression,
                                    Comment    = text2,
                                    Mask       = flag
                                });
                        }
                        break;
                    }
                    break;
                }

                case 83:
                case 85:
                    break;
                }
            }
            return(statementBlock);
        }
示例#15
0
        public static Doc Print(SyntaxNode syntaxNode)
        {
            if (syntaxNode == null)
            {
                return(Doc.Null);
            }

            // TODO 0 kill? runtime repo has files that will fail on deep recursion
            if (depth > 200)
            {
                throw new InTooDeepException();
            }

            depth++;
            try
            {
                switch (syntaxNode)
                {
                case AliasQualifiedNameSyntax aliasQualifiedNameSyntax:
                    return(AliasQualifiedName.Print(aliasQualifiedNameSyntax));

                case AnonymousMethodExpressionSyntax anonymousMethodExpressionSyntax:
                    return(AnonymousMethodExpression.Print(anonymousMethodExpressionSyntax));

                case AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpressionSyntax:
                    return(AnonymousObjectCreationExpression.Print(
                               anonymousObjectCreationExpressionSyntax
                               ));

                case AnonymousObjectMemberDeclaratorSyntax anonymousObjectMemberDeclaratorSyntax:
                    return(AnonymousObjectMemberDeclarator.Print(
                               anonymousObjectMemberDeclaratorSyntax
                               ));

                case ArgumentListSyntax argumentListSyntax:
                    return(ArgumentList.Print(argumentListSyntax));

                case ArgumentSyntax argumentSyntax:
                    return(Argument.Print(argumentSyntax));

                case ArrayCreationExpressionSyntax arrayCreationExpressionSyntax:
                    return(ArrayCreationExpression.Print(arrayCreationExpressionSyntax));

                case ArrayRankSpecifierSyntax arrayRankSpecifierSyntax:
                    return(ArrayRankSpecifier.Print(arrayRankSpecifierSyntax));

                case ArrayTypeSyntax arrayTypeSyntax:
                    return(ArrayType.Print(arrayTypeSyntax));

                case ArrowExpressionClauseSyntax arrowExpressionClauseSyntax:
                    return(ArrowExpressionClause.Print(arrowExpressionClauseSyntax));

                case AssignmentExpressionSyntax assignmentExpressionSyntax:
                    return(AssignmentExpression.Print(assignmentExpressionSyntax));

                case AttributeListSyntax attributeListSyntax:
                    return(AttributeList.Print(attributeListSyntax));

                case AwaitExpressionSyntax awaitExpressionSyntax:
                    return(AwaitExpression.Print(awaitExpressionSyntax));

                case BaseExpressionSyntax baseExpressionSyntax:
                    return(BaseExpression.Print(baseExpressionSyntax));

                case BaseFieldDeclarationSyntax baseFieldDeclarationSyntax:
                    return(BaseFieldDeclaration.Print(baseFieldDeclarationSyntax));

                case BaseListSyntax baseListSyntax:
                    return(BaseList.Print(baseListSyntax));

                case BaseMethodDeclarationSyntax baseMethodDeclarationSyntax:
                    return(BaseMethodDeclaration.Print(baseMethodDeclarationSyntax));

                case BasePropertyDeclarationSyntax basePropertyDeclarationSyntax:
                    return(BasePropertyDeclaration.Print(basePropertyDeclarationSyntax));

                case BaseTypeDeclarationSyntax baseTypeDeclarationSyntax:
                    return(BaseTypeDeclaration.Print(baseTypeDeclarationSyntax));

                case BinaryExpressionSyntax binaryExpressionSyntax:
                    return(BinaryExpression.Print(binaryExpressionSyntax));

                case BinaryPatternSyntax binaryPatternSyntax:
                    return(BinaryPattern.Print(binaryPatternSyntax));

                case BlockSyntax blockSyntax:
                    return(Block.Print(blockSyntax));

                case BracketedArgumentListSyntax bracketedArgumentListSyntax:
                    return(BracketedArgumentList.Print(bracketedArgumentListSyntax));

                case BracketedParameterListSyntax bracketedParameterListSyntax:
                    return(BracketedParameterList.Print(bracketedParameterListSyntax));

                case BreakStatementSyntax breakStatementSyntax:
                    return(BreakStatement.Print(breakStatementSyntax));

                case CasePatternSwitchLabelSyntax casePatternSwitchLabelSyntax:
                    return(CasePatternSwitchLabel.Print(casePatternSwitchLabelSyntax));

                case CaseSwitchLabelSyntax caseSwitchLabelSyntax:
                    return(CaseSwitchLabel.Print(caseSwitchLabelSyntax));

                case CastExpressionSyntax castExpressionSyntax:
                    return(CastExpression.Print(castExpressionSyntax));

                case CatchClauseSyntax catchClauseSyntax:
                    return(CatchClause.Print(catchClauseSyntax));

                case CheckedExpressionSyntax checkedExpressionSyntax:
                    return(CheckedExpression.Print(checkedExpressionSyntax));

                case CheckedStatementSyntax checkedStatementSyntax:
                    return(CheckedStatement.Print(checkedStatementSyntax));

                case ClassOrStructConstraintSyntax classOrStructConstraintSyntax:
                    return(ClassOrStructConstraint.Print(classOrStructConstraintSyntax));

                case CompilationUnitSyntax compilationUnitSyntax:
                    return(CompilationUnit.Print(compilationUnitSyntax));

                case ConditionalAccessExpressionSyntax conditionalAccessExpressionSyntax:
                    return(ConditionalAccessExpression.Print(conditionalAccessExpressionSyntax));

                case ConditionalExpressionSyntax conditionalExpressionSyntax:
                    return(ConditionalExpression.Print(conditionalExpressionSyntax));

                case ConstantPatternSyntax constantPatternSyntax:
                    return(ConstantPattern.Print(constantPatternSyntax));

                case ConstructorConstraintSyntax constructorConstraintSyntax:
                    return(ConstructorConstraint.Print(constructorConstraintSyntax));

                case ConstructorInitializerSyntax constructorInitializerSyntax:
                    return(ConstructorInitializer.Print(constructorInitializerSyntax));

                case ContinueStatementSyntax continueStatementSyntax:
                    return(ContinueStatement.Print(continueStatementSyntax));

                case DeclarationExpressionSyntax declarationExpressionSyntax:
                    return(DeclarationExpression.Print(declarationExpressionSyntax));

                case DeclarationPatternSyntax declarationPatternSyntax:
                    return(DeclarationPattern.Print(declarationPatternSyntax));

                case DefaultConstraintSyntax defaultConstraintSyntax:
                    return(DefaultConstraint.Print(defaultConstraintSyntax));

                case DefaultExpressionSyntax defaultExpressionSyntax:
                    return(DefaultExpression.Print(defaultExpressionSyntax));

                case DefaultSwitchLabelSyntax defaultSwitchLabelSyntax:
                    return(DefaultSwitchLabel.Print(defaultSwitchLabelSyntax));

                case DelegateDeclarationSyntax delegateDeclarationSyntax:
                    return(DelegateDeclaration.Print(delegateDeclarationSyntax));

                case DiscardDesignationSyntax discardDesignationSyntax:
                    return(DiscardDesignation.Print(discardDesignationSyntax));

                case DiscardPatternSyntax discardPatternSyntax:
                    return(DiscardPattern.Print(discardPatternSyntax));

                case DoStatementSyntax doStatementSyntax:
                    return(DoStatement.Print(doStatementSyntax));

                case ElementAccessExpressionSyntax elementAccessExpressionSyntax:
                    return(ElementAccessExpression.Print(elementAccessExpressionSyntax));

                case ElementBindingExpressionSyntax elementBindingExpressionSyntax:
                    return(ElementBindingExpression.Print(elementBindingExpressionSyntax));

                case ElseClauseSyntax elseClauseSyntax:
                    return(ElseClause.Print(elseClauseSyntax));

                case EmptyStatementSyntax emptyStatementSyntax:
                    return(EmptyStatement.Print(emptyStatementSyntax));

                case EnumMemberDeclarationSyntax enumMemberDeclarationSyntax:
                    return(EnumMemberDeclaration.Print(enumMemberDeclarationSyntax));

                case EqualsValueClauseSyntax equalsValueClauseSyntax:
                    return(EqualsValueClause.Print(equalsValueClauseSyntax));

                case ExpressionStatementSyntax expressionStatementSyntax:
                    return(ExpressionStatement.Print(expressionStatementSyntax));

                case ExternAliasDirectiveSyntax externAliasDirectiveSyntax:
                    return(ExternAliasDirective.Print(externAliasDirectiveSyntax));

                case FinallyClauseSyntax finallyClauseSyntax:
                    return(FinallyClause.Print(finallyClauseSyntax));

                case FixedStatementSyntax fixedStatementSyntax:
                    return(FixedStatement.Print(fixedStatementSyntax));

                case ForEachStatementSyntax forEachStatementSyntax:
                    return(ForEachStatement.Print(forEachStatementSyntax));

                case ForEachVariableStatementSyntax forEachVariableStatementSyntax:
                    return(ForEachVariableStatement.Print(forEachVariableStatementSyntax));

                case ForStatementSyntax forStatementSyntax:
                    return(ForStatement.Print(forStatementSyntax));

                case FromClauseSyntax fromClauseSyntax:
                    return(FromClause.Print(fromClauseSyntax));

                case FunctionPointerTypeSyntax functionPointerTypeSyntax:
                    return(FunctionPointerType.Print(functionPointerTypeSyntax));

                case GenericNameSyntax genericNameSyntax:
                    return(GenericName.Print(genericNameSyntax));

                case GlobalStatementSyntax globalStatementSyntax:
                    return(GlobalStatement.Print(globalStatementSyntax));

                case GotoStatementSyntax gotoStatementSyntax:
                    return(GotoStatement.Print(gotoStatementSyntax));

                case GroupClauseSyntax groupClauseSyntax:
                    return(GroupClause.Print(groupClauseSyntax));

                case IdentifierNameSyntax identifierNameSyntax:
                    return(IdentifierName.Print(identifierNameSyntax));

                case IfStatementSyntax ifStatementSyntax:
                    return(IfStatement.Print(ifStatementSyntax));

                case ImplicitArrayCreationExpressionSyntax implicitArrayCreationExpressionSyntax:
                    return(ImplicitArrayCreationExpression.Print(
                               implicitArrayCreationExpressionSyntax
                               ));

                case ImplicitElementAccessSyntax implicitElementAccessSyntax:
                    return(ImplicitElementAccess.Print(implicitElementAccessSyntax));

                case ImplicitObjectCreationExpressionSyntax implicitObjectCreationExpressionSyntax:
                    return(ImplicitObjectCreationExpression.Print(
                               implicitObjectCreationExpressionSyntax
                               ));

                case ImplicitStackAllocArrayCreationExpressionSyntax implicitStackAllocArrayCreationExpressionSyntax:
                    return(ImplicitStackAllocArrayCreationExpression.Print(
                               implicitStackAllocArrayCreationExpressionSyntax
                               ));

                case IncompleteMemberSyntax incompleteMemberSyntax:
                    return(IncompleteMember.Print(incompleteMemberSyntax));

                case InitializerExpressionSyntax initializerExpressionSyntax:
                    return(InitializerExpression.Print(initializerExpressionSyntax));

                case InterpolatedStringExpressionSyntax interpolatedStringExpressionSyntax:
                    return(InterpolatedStringExpression.Print(
                               interpolatedStringExpressionSyntax
                               ));

                case InterpolatedStringTextSyntax interpolatedStringTextSyntax:
                    return(InterpolatedStringText.Print(interpolatedStringTextSyntax));

                case InterpolationSyntax interpolationSyntax:
                    return(Interpolation.Print(interpolationSyntax));

                case InvocationExpressionSyntax invocationExpressionSyntax:
                    return(InvocationExpression.Print(invocationExpressionSyntax));

                case IsPatternExpressionSyntax isPatternExpressionSyntax:
                    return(IsPatternExpression.Print(isPatternExpressionSyntax));

                case JoinClauseSyntax joinClauseSyntax:
                    return(JoinClause.Print(joinClauseSyntax));

                case LabeledStatementSyntax labeledStatementSyntax:
                    return(LabeledStatement.Print(labeledStatementSyntax));

                case LetClauseSyntax letClauseSyntax:
                    return(LetClause.Print(letClauseSyntax));

                case LiteralExpressionSyntax literalExpressionSyntax:
                    return(LiteralExpression.Print(literalExpressionSyntax));

                case LocalDeclarationStatementSyntax localDeclarationStatementSyntax:
                    return(LocalDeclarationStatement.Print(localDeclarationStatementSyntax));

                case LocalFunctionStatementSyntax localFunctionStatementSyntax:
                    return(LocalFunctionStatement.Print(localFunctionStatementSyntax));

                case LockStatementSyntax lockStatementSyntax:
                    return(LockStatement.Print(lockStatementSyntax));

                case MakeRefExpressionSyntax makeRefExpressionSyntax:
                    return(MakeRefExpression.Print(makeRefExpressionSyntax));

                case MemberAccessExpressionSyntax memberAccessExpressionSyntax:
                    return(MemberAccessExpression.Print(memberAccessExpressionSyntax));

                case MemberBindingExpressionSyntax memberBindingExpressionSyntax:
                    return(MemberBindingExpression.Print(memberBindingExpressionSyntax));

                case NameColonSyntax nameColonSyntax:
                    return(NameColon.Print(nameColonSyntax));

                case NameEqualsSyntax nameEqualsSyntax:
                    return(NameEquals.Print(nameEqualsSyntax));

                case NamespaceDeclarationSyntax namespaceDeclarationSyntax:
                    return(NamespaceDeclaration.Print(namespaceDeclarationSyntax));

                case NullableTypeSyntax nullableTypeSyntax:
                    return(NullableType.Print(nullableTypeSyntax));

                case ObjectCreationExpressionSyntax objectCreationExpressionSyntax:
                    return(ObjectCreationExpression.Print(objectCreationExpressionSyntax));

                case OmittedArraySizeExpressionSyntax omittedArraySizeExpressionSyntax:
                    return(OmittedArraySizeExpression.Print(omittedArraySizeExpressionSyntax));

                case OmittedTypeArgumentSyntax omittedTypeArgumentSyntax:
                    return(OmittedTypeArgument.Print(omittedTypeArgumentSyntax));

                case OrderByClauseSyntax orderByClauseSyntax:
                    return(OrderByClause.Print(orderByClauseSyntax));

                case ParameterListSyntax parameterListSyntax:
                    return(ParameterList.Print(parameterListSyntax));

                case ParameterSyntax parameterSyntax:
                    return(Parameter.Print(parameterSyntax));

                case ParenthesizedExpressionSyntax parenthesizedExpressionSyntax:
                    return(ParenthesizedExpression.Print(parenthesizedExpressionSyntax));

                case ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpressionSyntax:
                    return(ParenthesizedLambdaExpression.Print(
                               parenthesizedLambdaExpressionSyntax
                               ));

                case ParenthesizedPatternSyntax parenthesizedPatternSyntax:
                    return(ParenthesizedPattern.Print(parenthesizedPatternSyntax));

                case ParenthesizedVariableDesignationSyntax parenthesizedVariableDesignationSyntax:
                    return(ParenthesizedVariableDesignation.Print(
                               parenthesizedVariableDesignationSyntax
                               ));

                case PointerTypeSyntax pointerTypeSyntax:
                    return(PointerType.Print(pointerTypeSyntax));

                case PostfixUnaryExpressionSyntax postfixUnaryExpressionSyntax:
                    return(PostfixUnaryExpression.Print(postfixUnaryExpressionSyntax));

                case PredefinedTypeSyntax predefinedTypeSyntax:
                    return(PredefinedType.Print(predefinedTypeSyntax));

                case PrefixUnaryExpressionSyntax prefixUnaryExpressionSyntax:
                    return(PrefixUnaryExpression.Print(prefixUnaryExpressionSyntax));

                case PrimaryConstructorBaseTypeSyntax primaryConstructorBaseTypeSyntax:
                    return(PrimaryConstructorBaseType.Print(primaryConstructorBaseTypeSyntax));

                case QualifiedNameSyntax qualifiedNameSyntax:
                    return(QualifiedName.Print(qualifiedNameSyntax));

                case QueryBodySyntax queryBodySyntax:
                    return(QueryBody.Print(queryBodySyntax));

                case QueryContinuationSyntax queryContinuationSyntax:
                    return(QueryContinuation.Print(queryContinuationSyntax));

                case QueryExpressionSyntax queryExpressionSyntax:
                    return(QueryExpression.Print(queryExpressionSyntax));

                case RangeExpressionSyntax rangeExpressionSyntax:
                    return(RangeExpression.Print(rangeExpressionSyntax));

                case RecursivePatternSyntax recursivePatternSyntax:
                    return(RecursivePattern.Print(recursivePatternSyntax));

                case RefExpressionSyntax refExpressionSyntax:
                    return(RefExpression.Print(refExpressionSyntax));

                case RefTypeExpressionSyntax refTypeExpressionSyntax:
                    return(RefTypeExpression.Print(refTypeExpressionSyntax));

                case RefTypeSyntax refTypeSyntax:
                    return(RefType.Print(refTypeSyntax));

                case RefValueExpressionSyntax refValueExpressionSyntax:
                    return(RefValueExpression.Print(refValueExpressionSyntax));

                case RelationalPatternSyntax relationalPatternSyntax:
                    return(RelationalPattern.Print(relationalPatternSyntax));

                case ReturnStatementSyntax returnStatementSyntax:
                    return(ReturnStatement.Print(returnStatementSyntax));

                case SelectClauseSyntax selectClauseSyntax:
                    return(SelectClause.Print(selectClauseSyntax));

                case SimpleBaseTypeSyntax simpleBaseTypeSyntax:
                    return(SimpleBaseType.Print(simpleBaseTypeSyntax));

                case SimpleLambdaExpressionSyntax simpleLambdaExpressionSyntax:
                    return(SimpleLambdaExpression.Print(simpleLambdaExpressionSyntax));

                case SingleVariableDesignationSyntax singleVariableDesignationSyntax:
                    return(SingleVariableDesignation.Print(singleVariableDesignationSyntax));

                case SizeOfExpressionSyntax sizeOfExpressionSyntax:
                    return(SizeOfExpression.Print(sizeOfExpressionSyntax));

                case StackAllocArrayCreationExpressionSyntax stackAllocArrayCreationExpressionSyntax:
                    return(StackAllocArrayCreationExpression.Print(
                               stackAllocArrayCreationExpressionSyntax
                               ));

                case SwitchExpressionSyntax switchExpressionSyntax:
                    return(SwitchExpression.Print(switchExpressionSyntax));

                case SwitchSectionSyntax switchSectionSyntax:
                    return(SwitchSection.Print(switchSectionSyntax));

                case SwitchStatementSyntax switchStatementSyntax:
                    return(SwitchStatement.Print(switchStatementSyntax));

                case ThisExpressionSyntax thisExpressionSyntax:
                    return(ThisExpression.Print(thisExpressionSyntax));

                case ThrowExpressionSyntax throwExpressionSyntax:
                    return(ThrowExpression.Print(throwExpressionSyntax));

                case ThrowStatementSyntax throwStatementSyntax:
                    return(ThrowStatement.Print(throwStatementSyntax));

                case TryStatementSyntax tryStatementSyntax:
                    return(TryStatement.Print(tryStatementSyntax));

                case TupleElementSyntax tupleElementSyntax:
                    return(TupleElement.Print(tupleElementSyntax));

                case TupleExpressionSyntax tupleExpressionSyntax:
                    return(TupleExpression.Print(tupleExpressionSyntax));

                case TupleTypeSyntax tupleTypeSyntax:
                    return(TupleType.Print(tupleTypeSyntax));

                case TypeArgumentListSyntax typeArgumentListSyntax:
                    return(TypeArgumentList.Print(typeArgumentListSyntax));

                case TypeConstraintSyntax typeConstraintSyntax:
                    return(TypeConstraint.Print(typeConstraintSyntax));

                case TypeOfExpressionSyntax typeOfExpressionSyntax:
                    return(TypeOfExpression.Print(typeOfExpressionSyntax));

                case TypeParameterConstraintClauseSyntax typeParameterConstraintClauseSyntax:
                    return(TypeParameterConstraintClause.Print(
                               typeParameterConstraintClauseSyntax
                               ));

                case TypeParameterListSyntax typeParameterListSyntax:
                    return(TypeParameterList.Print(typeParameterListSyntax));

                case TypeParameterSyntax typeParameterSyntax:
                    return(TypeParameter.Print(typeParameterSyntax));

                case TypePatternSyntax typePatternSyntax:
                    return(TypePattern.Print(typePatternSyntax));

                case UnaryPatternSyntax unaryPatternSyntax:
                    return(UnaryPattern.Print(unaryPatternSyntax));

                case UnsafeStatementSyntax unsafeStatementSyntax:
                    return(UnsafeStatement.Print(unsafeStatementSyntax));

                case UsingDirectiveSyntax usingDirectiveSyntax:
                    return(UsingDirective.Print(usingDirectiveSyntax));

                case UsingStatementSyntax usingStatementSyntax:
                    return(UsingStatement.Print(usingStatementSyntax));

                case VariableDeclarationSyntax variableDeclarationSyntax:
                    return(VariableDeclaration.Print(variableDeclarationSyntax));

                case VariableDeclaratorSyntax variableDeclaratorSyntax:
                    return(VariableDeclarator.Print(variableDeclaratorSyntax));

                case VarPatternSyntax varPatternSyntax:
                    return(VarPattern.Print(varPatternSyntax));

                case WhenClauseSyntax whenClauseSyntax:
                    return(WhenClause.Print(whenClauseSyntax));

                case WhereClauseSyntax whereClauseSyntax:
                    return(WhereClause.Print(whereClauseSyntax));

                case WhileStatementSyntax whileStatementSyntax:
                    return(WhileStatement.Print(whileStatementSyntax));

                case WithExpressionSyntax withExpressionSyntax:
                    return(WithExpression.Print(withExpressionSyntax));

                case YieldStatementSyntax yieldStatementSyntax:
                    return(YieldStatement.Print(yieldStatementSyntax));

                default:
                    throw new Exception("Can't handle " + syntaxNode.GetType().Name);
                }
            }

            finally
            {
                depth--;
            }
        }
示例#16
0
 public override object VisitForStatement(ForStatement forStatement, object data)
 {
     return(base.VisitForStatement(forStatement, true));
 }
示例#17
0
 public virtual Node VisitForStatement(ForStatement forStatement)
 {
     throw new System.NotImplementedException();
 }
示例#18
0
 public override IEnumerable <Expression> VisitForStatement(ForStatement forStatement)
 {
     yield return(forStatement.Condition);
 }
示例#19
0
 public void Visit(ForStatement expression)
 {
     outStream.Write("for (");
     expression.InitialisationStatement.Accept(this);
     outStream.Write(" ; ");
     expression.ConditionExpression.Accept(this);
     outStream.Write(" ; ");
     expression.IncrementExpression.Accept(this);
     outStream.WriteLine(") {");
     expression.Statement.Accept(this);
     outStream.WriteLine();
     outStream.Write("}");
 }
示例#20
0
            public override void VisitForStatement(ForStatement forStatement)
            {
                base.VisitForStatement(forStatement);

                CheckCondition(forStatement.Condition);
            }
		public void ForLoop()
		{
			ForStatement loop = new ForStatement {
				Initializers = {
					new ExpressionStatement(
						new AssignmentExpression(new IdentifierExpression("i"), new PrimitiveExpression(0))
					)
				},
				Condition = new BinaryOperatorExpression(new IdentifierExpression("i"), BinaryOperatorType.LessThan, new PrimitiveExpression(1000)),
				Iterators = {
					new ExpressionStatement(
						new AssignmentExpression {
							Left = new IdentifierExpression("i"),
							Operator = AssignmentOperatorType.Add,
							Right = new IdentifierExpression("j")
						}
					)
				},
				EmbeddedStatement = new ExpressionStatement(
					new AssignmentExpression(new IdentifierExpression("j"), new IdentifierExpression("i"))
				)};
			
			DefiniteAssignmentAnalysis da = CreateDefiniteAssignmentAnalysis(loop);
			da.Analyze("i");
			Assert.AreEqual(0, da.UnassignedVariableUses.Count);
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(loop));
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(loop.Initializers.Single()));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusAfter(loop.Initializers.Single()));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusBeforeLoopCondition(loop));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusBefore(loop.EmbeddedStatement));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusAfter(loop.EmbeddedStatement));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusBefore(loop.Iterators.Single()));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusAfter(loop.Iterators.Single()));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusAfter(loop));
			
			da.Analyze("j");
			Assert.AreEqual(0, da.UnassignedVariableUses.Count);
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(loop));
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(loop.Initializers.Single()));
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusAfter(loop.Initializers.Single()));
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBeforeLoopCondition(loop));
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusBefore(loop.EmbeddedStatement));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusAfter(loop.EmbeddedStatement));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusBefore(loop.Iterators.Single()));
			Assert.AreEqual(DefiniteAssignmentStatus.DefinitelyAssigned, da.GetStatusAfter(loop.Iterators.Single()));
			Assert.AreEqual(DefiniteAssignmentStatus.PotentiallyAssigned, da.GetStatusAfter(loop));
		}
示例#22
0
 IEnumerable <Syntax> IAstVisitor <ILTranslationContext, IEnumerable <Syntax> > .VisitForStatement(ForStatement forStatement, ILTranslationContext data)
 => OnVisiting(data, forStatement, VisitingForStatement)
 ?? OnVisited(data, forStatement, VisitedForStatement, TranslateForStatement(forStatement, data));
示例#23
0
 private void GenerateForTuple(ForStatement f, List<Exp> ids)
 {
     var localVar = GenSymLocalTuple();
     var v = f.tests.Accept(xlat);
     gen.Foreach(localVar, v, () =>
     {
         EmitTupleFieldAssignments(ids, localVar);
         f.Body.Accept(this);
     });
 }
示例#24
0
 public override bool Walk(ForStatement node) => SaveStmt(node, base.Walk(node));
 // ForStatement
 public virtual bool Walk(ForStatement node) { return true; }
示例#26
0
 public override DefiniteAssignmentStatus VisitForStatement(ForStatement forStatement, DefiniteAssignmentStatus data)
 {
     return(data);                // condition is handled by special condition CFG node; initializer and iterator statements are handled by CFG
 }
示例#27
0
			void AddStatementOrList(ForStatement forStatement, Mono.CSharp.Statement init, Role<Statement> role)
			{
				if (init == null)
					return;
				var stmtList = init as StatementList;
				if (stmtList != null) {
					foreach (var stmt in stmtList.Statements) {
						forStatement.AddChild((Statement)stmt.Accept(this), role);
					}
				} else if (init is Mono.CSharp.EmptyStatement) {
					
				} else {
					forStatement.AddChild((Statement)init.Accept(this), role);
				}
			}
示例#28
0
 public SymbolTable VisitFor(ForStatement f)
 {
     throw new NotImplementedException();
 }
示例#29
0
			public override object Visit (For forStatement)
			{
				var result = new ForStatement ();
				
				var location = LocationsBag.GetLocations (forStatement);
				
				result.AddChild (new CSharpTokenNode (Convert (forStatement.loc), "for".Length), ForStatement.Roles.Keyword);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), ForStatement.Roles.LPar);
				if (forStatement.InitStatement != null)
					result.AddChild ((INode)forStatement.InitStatement.Accept (this), ForStatement.Roles.Initializer);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), ForStatement.Roles.Semicolon);
				if (forStatement.Test != null)
					result.AddChild ((INode)forStatement.Test.Accept (this), ForStatement.Roles.Condition);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[2]), 1), ForStatement.Roles.Semicolon);
				if (forStatement.Increment != null)
					result.AddChild ((INode)forStatement.Increment.Accept (this), ForStatement.Roles.Iterator);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location[3]), 1), ForStatement.Roles.RPar);
				
				result.AddChild ((INode)forStatement.Statement.Accept (this), ForStatement.Roles.EmbeddedStatement);
				
				return result;
			}
示例#30
0
 public void VisitFor(ForStatement f)
 {
     w.Write("for");
     w.Write(" ");
     f.exprs.Write(writer);
     w.Write(" ");
     w.Write("in");
     w.Write(" ");
     f.tests.Write(writer);
     w.WriteLine(":");
     ++w.IndentLevel;
     f.Body.Accept(this);
     --w.IndentLevel;
 }
示例#31
0
 /// <summary>
 /// Visit operation called for for statements.
 ///
 /// <param name="stmt">a for statement</param>
 /// </summary>
 public virtual void visit_for_statement(ForStatement stmt)
 {
 }
 /**
  * Call back method that must be called when the given <code>ForStatement
  * </code> will become the next <i>traverse candidate</i>.
  *
  * @param pForStatement  The <code>ForStatement</code> object that will
  *                       become the next <i>traverse candidate</i>.
  */
 public void performAction(
      ForStatement pForStatement)
 {
     // Nothing to do.
 }
示例#33
0
 public void Visit(ForStatement node)
 {
     ReportError(node);
 }
示例#34
0
 private List <Inferred> InferForStatement(ForStatement node, Scope scope)
 {
     Debug.Print("Not implemented: InferForStatementIn");
     return(null);
 }
		public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			bool hasIndexAccess;
			var foreachStatement = GetForeachStatement(context, out hasIndexAccess);
			if (foreachStatement == null || foreachStatement.EmbeddedStatement == null)
				yield break;
			var state = context.GetResolverStateBefore (foreachStatement.EmbeddedStatement);
			string name = GetName(state, VariableNames);
			if (name == null) // very unlikely, but just in case ...
				yield break;

			yield return new CodeAction(context.TranslateString("Convert 'foreach' loop to 'for'"), script => {
				var result = context.Resolve(foreachStatement.InExpression);
				var countProperty = GetCountProperty(result.Type);
				var inExpression = foreachStatement.InExpression;

				var initializer = hasIndexAccess ? new VariableDeclarationStatement(new PrimitiveType("int"), name, new PrimitiveExpression(0)) :
				                  new VariableDeclarationStatement(new SimpleType("var"), name, new InvocationExpression(new MemberReferenceExpression (inExpression.Clone (), "GetEnumerator")));
				var id1 = new IdentifierExpression(name);
				var id2 = id1.Clone();
				var id3 = id1.Clone();
				Statement declarationStatement = null;
				if (inExpression is ObjectCreateExpression || inExpression is ArrayCreateExpression) {
					string listName = GetName(state, CollectionNames) ?? "col";
					declarationStatement = new VariableDeclarationStatement (
						new PrimitiveType ("var"),
						listName,
						inExpression.Clone ()
					);
					inExpression = new IdentifierExpression (listName);
				}

				var variableDeclarationStatement = new VariableDeclarationStatement(
					foreachStatement.VariableType.Clone(),
					foreachStatement.VariableName,
					hasIndexAccess ? (Expression)new IndexerExpression(inExpression.Clone(), id3) : new MemberReferenceExpression(id1, "Current")
				);

				var forStatement = new ForStatement {
					Initializers = { initializer },
					Condition = hasIndexAccess ? (Expression)new BinaryOperatorExpression (id1, BinaryOperatorType.LessThan, new MemberReferenceExpression (inExpression.Clone (), countProperty)) :
					            new InvocationExpression(new MemberReferenceExpression (id2, "MoveNext")),
					EmbeddedStatement = new BlockStatement {
						variableDeclarationStatement
					}
				};

				if (hasIndexAccess)
					forStatement.Iterators.Add(new UnaryOperatorExpression (UnaryOperatorType.PostIncrement, id2));

				if (foreachStatement.EmbeddedStatement is BlockStatement) {
					variableDeclarationStatement.Remove();
					var oldBlock = (BlockStatement)foreachStatement.EmbeddedStatement.Clone();
					if (oldBlock.Statements.Any()) {
						oldBlock.Statements.InsertBefore(oldBlock.Statements.First(), variableDeclarationStatement);
					} else {
						oldBlock.Statements.Add(variableDeclarationStatement);
					}
					forStatement.EmbeddedStatement = oldBlock;
				} else {
					forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
				}
				if (declarationStatement != null)
					script.InsertBefore (foreachStatement, declarationStatement);
				script.Replace (foreachStatement, forStatement);
				if (hasIndexAccess) {
					script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
				} else {
					script.Link (initializer.Variables.First ().NameToken, id1, id2);
				}
			}, foreachStatement);

			if (!hasIndexAccess)
				yield break;
			yield return new CodeAction(context.TranslateString("Convert 'foreach' loop to optimized 'for'"), script => {
				var result = context.Resolve(foreachStatement.InExpression);
				var countProperty = GetCountProperty(result.Type);

				var initializer = new VariableDeclarationStatement(new PrimitiveType("int"), name, new PrimitiveExpression(0));
				var id1 = new IdentifierExpression(name);
				var id2 = id1.Clone();
				var id3 = id1.Clone();
				var inExpression = foreachStatement.InExpression;
				Statement declarationStatement = null;
				if (inExpression is ObjectCreateExpression || inExpression is ArrayCreateExpression) {
					string listName = GetName(state, CollectionNames) ?? "col";
					declarationStatement = new VariableDeclarationStatement (
						new PrimitiveType ("var"),
						listName,
						inExpression.Clone ()
						);
					inExpression = new IdentifierExpression (listName);
				}

				var variableDeclarationStatement = new VariableDeclarationStatement(
					foreachStatement.VariableType.Clone(),
					foreachStatement.VariableName,
					new IndexerExpression(inExpression.Clone(), id3)
					);

				string optimizedUpperBound = GetBoundName(inExpression) + countProperty;
				initializer.Variables.Add(new VariableInitializer(optimizedUpperBound, new MemberReferenceExpression (inExpression.Clone (), countProperty)));
				var forStatement = new ForStatement {
					Initializers = { initializer },
					Condition = new BinaryOperatorExpression (id1, BinaryOperatorType.LessThan, new IdentifierExpression(optimizedUpperBound)),
					Iterators = { new UnaryOperatorExpression (UnaryOperatorType.PostIncrement, id2) },
					EmbeddedStatement = new BlockStatement {
						variableDeclarationStatement
					}
				};

				if (foreachStatement.EmbeddedStatement is BlockStatement) {
					variableDeclarationStatement.Remove();
					var oldBlock = (BlockStatement)foreachStatement.EmbeddedStatement.Clone();
					if (oldBlock.Statements.Any()) {
						oldBlock.Statements.InsertBefore(oldBlock.Statements.First(), variableDeclarationStatement);
					} else {
						oldBlock.Statements.Add(variableDeclarationStatement);
					}
					forStatement.EmbeddedStatement = oldBlock;
				} else {
					forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
				}
				if (declarationStatement != null)
					script.InsertBefore (foreachStatement, declarationStatement);
				script.Replace (foreachStatement, forStatement);
				script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
			}, foreachStatement);
		}
 public override void VisitForStatement(ForStatement node)
 {
     return;
 }
示例#37
0
		public override void VisitForStatement(ForStatement forStatement)
		{
			foreach (AstNode node in forStatement.Children) {
				if (node.Role == Roles.Semicolon) {
					if (node.NextSibling is CSharpTokenNode || node.NextSibling is EmptyStatement) {
						continue;
					}
					ForceSpacesBefore(node, policy.SpaceBeforeForSemicolon);
					ForceSpacesAfter(node, policy.SpaceAfterForSemicolon);
				}
			}

			ForceSpacesBefore(forStatement.LParToken, policy.SpaceBeforeForParentheses);

			ForceSpacesAfter(forStatement.LParToken, policy.SpacesWithinForParentheses);
			ForceSpacesBefore(forStatement.RParToken, policy.SpacesWithinForParentheses);

			FixEmbeddedStatment(policy.StatementBraceStyle, policy.ForBraceForcement, forStatement.EmbeddedStatement);
		}
示例#38
0
 public override bool Walk(ForStatement node)
 {
     UpdateChildRanges(node);
     return(base.Walk(node));
 }
 /**
  * Call back method that must be called as soon as the given <code>
  * ForStatement</code> object has been traversed.
  *
  * @param pForStatement  The <code>ForStatement</code> object that has just
  *                       been traversed.
  */
 public void actionPerformed(
      ForStatement pForStatement)
 {
     // Nothing to do.
 }
示例#40
0
 // ForStatement
 public virtual bool Walk(ForStatement node)
 {
     return(true);
 }
 public virtual void VisitForStatement(ForStatement forStatement)
 {
     if (this.ThrowException)
     {
         throw (Exception)this.CreateException(forStatement);
     }
 }
示例#42
0
 public virtual void PostWalk(ForStatement node)
 {
 }
示例#43
0
 public ForBlock(IEmitter emitter, ForStatement forStatement)
     : base(emitter, forStatement) {
     this.Emitter = emitter;
     this.ForStatement = forStatement;
 }
示例#44
0
 // ForStatement
 public override bool Walk(ForStatement node)
 {
     return(false);
 }
示例#45
0
 public void VisitFor(ForStatement f)
 {
     if (f.exprs is Identifier)
     {
         var exp = f.exprs.Accept(xlat);
         var v = f.tests.Accept(xlat);
         gen.Foreach(exp, v, () => f.Body.Accept(this));
         return;
     }
     var expList = f.exprs as ExpList;
     if (expList != null)
     {
         GenerateForTuple(f, expList.Expressions);
         return;
     }
     var tuple = f.exprs as PyTuple;
     if (tuple != null)
     {
         GenerateForTuple(f, tuple.values);
         return;
     }
     throw new NotImplementedException();
 }
示例#46
0
 public override void PostWalk(ForStatement node)
 {
 }
示例#47
0
        public override StringBuilder VisitForStatement(ForStatement forStatement, int data)
        {
            var result = new StringBuilder("for (");

            var initializers = forStatement.Initializers.ToList();
            var initializerCount = initializers.Count;
            for (var i = 0; i < initializerCount; i++)
            {
                var initializer = initializers[i];
                result.Append(initializer.AcceptVisitor(this, data));

                if (i != initializerCount - 1)
                    result.Append(", ");
            }

            result.Append(";");

            var condition = forStatement.Condition;
            if (condition != null)
            {
                result.Append(" ");
                result.Append(condition.AcceptVisitor(this, data));
            }

            result.Append(";");

            var iterators = forStatement.Iterators.ToList();
            var iteratorCount = iterators.Count;

            if (iteratorCount != 0)
                result.Append(" ");

            for (var i = 0; i < iteratorCount; i++)
            {
                var iterator = iterators[i];
                result.Append(iterator.AcceptVisitor(this, data));

                if (i != iteratorCount - 1)
                    result.Append(", ");
            }

            result.Append(")");

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

            return result;
        }
        void DeclareVariableInBlock(DefiniteAssignmentAnalysis daa, BlockStatement block, AstType type, string variableName, ILVariable v, bool allowPassIntoLoops)
        {
            // declarationPoint: The point where the variable would be declared, if we decide to declare it in this block
            Statement declarationPoint = null;
            // Check whether we can move down the variable into the sub-blocks
            bool canMoveVariableIntoSubBlocks = FindDeclarationPoint(daa, variableName, allowPassIntoLoops, block, out declarationPoint);

            if (declarationPoint == null)
            {
                // The variable isn't used at all
                return;
            }
            if (canMoveVariableIntoSubBlocks)
            {
                // Declare the variable within the sub-blocks
                foreach (Statement stmt in block.Statements)
                {
                    ForStatement forStmt = stmt as ForStatement;
                    if (forStmt != null && forStmt.Initializers.Count == 1)
                    {
                        // handle the special case of moving a variable into the for initializer
                        if (TryConvertAssignmentExpressionIntoVariableDeclaration(forStmt.Initializers.Single(), type, variableName))
                        {
                            continue;
                        }
                    }
                    UsingStatement usingStmt = stmt as UsingStatement;
                    if (usingStmt != null && usingStmt.ResourceAcquisition is AssignmentExpression)
                    {
                        // handle the special case of moving a variable into a using statement
                        if (TryConvertAssignmentExpressionIntoVariableDeclaration((Expression)usingStmt.ResourceAcquisition, type, variableName))
                        {
                            continue;
                        }
                    }
                    foreach (AstNode child in stmt.Children)
                    {
                        BlockStatement subBlock = child as BlockStatement;
                        if (subBlock != null)
                        {
                            DeclareVariableInBlock(daa, subBlock, type, variableName, v, allowPassIntoLoops);
                        }
                        else if (HasNestedBlocks(child))
                        {
                            foreach (BlockStatement nestedSubBlock in child.Children.OfType <BlockStatement>())
                            {
                                DeclareVariableInBlock(daa, nestedSubBlock, type, variableName, v, allowPassIntoLoops);
                            }
                        }
                    }
                }
            }
            else
            {
                // Try converting an assignment expression into a VariableDeclarationStatement
                if (!TryConvertAssignmentExpressionIntoVariableDeclaration(declarationPoint, type, variableName))
                {
                    // Declare the variable in front of declarationPoint
                    variablesToDeclare.Add(new VariableToDeclare {
                        Type = type, Name = variableName, ILVariable = v, InsertionPoint = declarationPoint
                    });
                }
            }
        }
		public virtual void Visit(ForStatement s)
		{
			// Also visits 'Initialize'
			VisitChildren(s);

			if (s.Test != null)
				s.Test.Accept(this);
			if (s.Increment != null)
				s.Increment.Accept(this);
		}
        static bool CanMoveVariableUseIntoSubBlock(Statement stmt, string variableName, bool allowPassIntoLoops)
        {
            if (!allowPassIntoLoops && (stmt is ForStatement || stmt is ForeachStatement || stmt is DoWhileStatement || stmt is WhileStatement))
            {
                return(false);
            }

            ForStatement forStatement = stmt as ForStatement;

            if (forStatement != null && forStatement.Initializers.Count == 1)
            {
                // for-statement is special case: we can move variable declarations into the initializer
                ExpressionStatement es = forStatement.Initializers.Single() as ExpressionStatement;
                if (es != null)
                {
                    AssignmentExpression ae = es.Expression as AssignmentExpression;
                    if (ae != null && ae.Operator == AssignmentOperatorType.Assign)
                    {
                        IdentifierExpression ident = ae.Left as IdentifierExpression;
                        if (ident != null && ident.Identifier == variableName)
                        {
                            return(!UsesVariable(ae.Right, variableName));
                        }
                    }
                }
            }

            UsingStatement usingStatement = stmt as UsingStatement;

            if (usingStatement != null)
            {
                // using-statement is special case: we can move variable declarations into the initializer
                AssignmentExpression ae = usingStatement.ResourceAcquisition as AssignmentExpression;
                if (ae != null && ae.Operator == AssignmentOperatorType.Assign)
                {
                    IdentifierExpression ident = ae.Left as IdentifierExpression;
                    if (ident != null && ident.Identifier == variableName)
                    {
                        return(!UsesVariable(ae.Right, variableName));
                    }
                }
            }

            // We can move the variable into a sub-block only if the variable is used in only that sub-block (and not in expressions such as the loop condition)
            for (AstNode child = stmt.FirstChild; child != null; child = child.NextSibling)
            {
                if (!(child is BlockStatement) && UsesVariable(child, variableName))
                {
                    if (HasNestedBlocks(child))
                    {
                        // catch clauses/switch sections can contain nested blocks
                        for (AstNode grandchild = child.FirstChild; grandchild != null; grandchild = grandchild.NextSibling)
                        {
                            if (!(grandchild is BlockStatement) && UsesVariable(grandchild, variableName))
                            {
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
 public virtual void PostWalk(ForStatement node) { }
示例#52
0
 public virtual void Accept(ForStatement forStmt)
 {
 }
 public override void PostWalk(ForStatement node) { }
示例#54
0
 public EV3Variable FindVariable(ForStatement forStatement)
 {
     return(variables.FindVariable(forStatement));
 }
示例#55
0
			public override object Visit(For forStatement)
			{
				var result = new ForStatement();
				
				var location = LocationsBag.GetLocations(forStatement);
				
				result.AddChild(new CSharpTokenNode(Convert(forStatement.loc), ForStatement.ForKeywordRole), ForStatement.ForKeywordRole);
				if (location != null)
					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
				
				AddStatementOrList(result, forStatement.Initializer, ForStatement.InitializerRole);
				
				if (location != null && location.Count > 1)
					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Semicolon), Roles.Semicolon);
				if (forStatement.Condition != null)
					result.AddChild((Expression)forStatement.Condition.Accept(this), Roles.Condition);
				if (location != null && location.Count >= 3)
					result.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.Semicolon), Roles.Semicolon);
				
				AddStatementOrList(result, forStatement.Iterator, ForStatement.IteratorRole);
				
				if (location != null && location.Count >= 4)
					result.AddChild(new CSharpTokenNode(Convert(location [3]), Roles.RPar), Roles.RPar);
				
				if (forStatement.Statement != null)
					result.AddChild((Statement)forStatement.Statement.Accept(this), Roles.EmbeddedStatement);
				
				return result;
			}
示例#56
0
        public override Object Visit(ForStatement node, Object obj)
        {
            Object aux = null;

            this.map.SetScope();
            for (int i = 0; i < node.InitializerCount; i++)
            {
                node.GetInitializerElement(i).Accept(this, false);
            }
            SSAMap map1 = this.map.Clone();

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

            node.Statements.Accept(this, obj);
            SSAMap map3 = this.map.Clone();

            for (int i = 0; i < node.IteratorCount; i++)
            {
                node.GetIteratorElement(i).Accept(this, false);
            }
            // map4 = this.map

            List <MoveStatement> mvSt = map1.GetMoveStatements(this.map, node.Location.FileName, node.Location.Line);

            if (mvSt.Count != 0)
            {
                node.AfterInit = mvSt;
            }

            List <ThetaStatement> thSt = map1.GetThetaStatements(map2, ref this.map, node.Location.FileName, node.Location.Line);

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

            mvSt = map1.GetMoveStatements(map2, this.map, node.Location.FileName, node.Location.Line);
            if (mvSt.Count != 0)
            {
                node.AfterCondition = mvSt;
            }

            SSAInfo info = new SSAInfo(null, null, map1, this.map);

            node.Condition.Accept(new VisitorSSA2(), info);

            info = new SSAInfo(this.map, null, map1, this.map);
            node.Statements.Accept(new VisitorSSA2(), info);

            info = new SSAInfo(this.map, null, map1, this.map);
            for (int i = 0; i < node.IteratorCount; i++)
            {
                node.GetIteratorElement(i).Accept(new VisitorSSA2(), info);
            }

            this.addLocalVariable(this.map.ResetScope(), node.AuxInitializer);
            node.UpdateInitializer();

            return(null);
        }
        public void VisitForStatement(ForStatement forStmt)
        {
            int tmp_counter = scope_counter;
            DecendScope();
            scope_counter = 0;

            forStmt.Left.AcceptWalker(this);
            forStmt.Target.AcceptWalker(this);
            forStmt.Body.AcceptWalker(this);

            AscendScope();
            scope_counter = tmp_counter + 1;
        }
示例#58
0
        /// <summary>
        /// Parse un Statement suivi de son block.
        /// En général, on obtient :
        /// Statement + Operand + BlockGroup.
        /// Le statement if pouvant être composé différemment (avec else et elsif), il n'est pas traité
        /// dans cette fonction.
        /// </summary>
        /// <param name="tokens"></param>
        /// <returns></returns>
        public static Instruction ParseBlockStatement(TokenList tokens, GlobalContext mainContext)
        {
            // Patch
            if (tokens.Count == 4 && tokens.First().Type == TokenType.Statement)
            {
                PatchInstruction patchInstruction = new PatchInstruction();

                InfoToken itoken = (InfoToken)tokens.First();
                if (itoken.Content != "patch")
                {
                    throw new Exception("Invalid statement format");
                }
                patchInstruction.FuncName = ((InfoToken)((OperandToken)tokens[1]).Tokens[0]).Content;
                InfoToken keyToken = (InfoToken)((OperandToken)(((PrefixedOperatorToken)tokens[2]).Operand)).Tokens.First();
                patchInstruction.Key          = keyToken.Content;
                patchInstruction.Instructions = ParseBlock(((BlockGroupToken)tokens[3]).Tokens).Instructions;
                return(patchInstruction);
            }

            if (tokens.Count != 3)
            {
                throw new Exception("Invalid instruction format.");
            }

            // On récupère les jetons.
            InfoToken       statementToken = tokens[0] as InfoToken;
            Token           exprToken      = tokens[1];
            BlockGroupToken blockToken     = tokens[2] as BlockGroupToken;

            if (statementToken == null || blockToken == null || statementToken.Type != TokenType.Statement)
            {
                throw new Exception("Invalid instruction format.");
            }

            Block block = ParseBlock(blockToken.Tokens, mainContext);

            switch (statementToken.Content)
            {
            case "return":
                throw new Exception();

            case "function":
                throw new Exception();

                /*TokenList exprTokens = ((OperandToken)exprToken).Tokens;
                 * FunctionDeclarationInstruction declaration = new FunctionDeclarationInstruction();
                 * TokenList nameTokens = ((ParenthesisGroupToken)exprTokens[1]).Tokens;
                 *
                 * // Ici on parcours les jetons de exprToken (qui doit être un OperandToken)
                 * // afin de trouver les noms des arguments.
                 *
                 * // Liste contenant les noms des arguments
                 * List<string> argsNamesLists = new List<string>();
                 * string funName = ((InfoToken)(exprTokens[0])).Content;
                 *
                 * // Indique si le prochain jeton doit être une virgule
                 * bool needComa = false;
                 * foreach (Token tok in nameTokens)
                 * {
                 *  if (needComa && tok.Type != TokenType.Separator)
                 *      throw new Exception("Expected ',' token in function declaration");
                 *  else
                 *      needComa = false;
                 *  // Si c'est un nom :
                 *  if (tok.Type == TokenType.OperandTokens && ((OperandToken)tok).Tokens.First().Type == TokenType.Noun)
                 *  {
                 *      argsNamesLists.Add(((InfoToken)((OperandToken)tok).Tokens.First()).Content);
                 *      needComa = true;
                 *  }
                 * }
                 * // Setup de la déclaration de fonction.
                 * declaration.Function = new Function();
                 * declaration.Function.ArgumentNames = argsNamesLists;
                 * declaration.Function.Body = block;
                 * declaration.FunctionName = funName;
                 *
                 * return declaration;*/
                break;

            case "while":
                IGettable expr = ParseExpression(exprToken, mainContext);
                block = ParseBlock(blockToken.Tokens, mainContext);
                WhileStatement statement = new WhileStatement();
                statement.Block     = block;
                statement.Condition = expr;
                return(statement);

            case "for":
                // Dans le cas d'une boucle for, expr est une opérande, contenant
                // une instruction, une expression, et une autre instruction.
                // (bizarre, certes)
                TokenList initializationInstruction = new TokenList();
                TokenList stepInstruction           = new TokenList();
                TokenList conditionExpr             = new TokenList();
                int       step = 0;
                foreach (Token tok in ((OperandToken)exprToken).Tokens)
                {
                    if (tok.Type == TokenType.EndOfInstruction)
                    {
                        step++;
                    }
                    else
                    {
                        switch (step)
                        {
                        case 0:
                            initializationInstruction.Add(tok);
                            break;

                        case 1:
                            conditionExpr.Add(tok);
                            break;

                        case 2:
                            stepInstruction.Add(tok);
                            break;
                        }
                    }
                }
                // On vérifie qu'on ait bien le bon nombre.
                if (step != 2)
                {
                    throw new Exception("Incorrect for statement.");
                }

                // On crée et on retourne le for.
                ForStatement forStatement = new ForStatement();
                forStatement.Initialisation = ParseInstruction(initializationInstruction, mainContext);
                forStatement.Condition      = ParseExpression(new OperandToken(conditionExpr), mainContext);
                forStatement.Update         = ParseInstruction(stepInstruction, mainContext);
                forStatement.Block          = block;

                return(forStatement);

            default:
                throw new NotImplementedException("Not implemented statement");
            }
        }
示例#59
0
		public void VisitForStatement(ForStatement forStatement)
		{
			StartNode(forStatement);
			WriteKeyword(ForStatement.ForKeywordRole);
			Space(policy.SpaceBeforeForParentheses);
			LPar();
			Space(policy.SpacesWithinForParentheses);
			
			WriteCommaSeparatedList(forStatement.Initializers);
			Space(policy.SpaceBeforeForSemicolon);
			WriteToken(Roles.Semicolon);
			Space(policy.SpaceAfterForSemicolon);
			
			forStatement.Condition.AcceptVisitor(this);
			Space(policy.SpaceBeforeForSemicolon);
			WriteToken(Roles.Semicolon);
			if (forStatement.Iterators.Any()) {
				Space(policy.SpaceAfterForSemicolon);
				WriteCommaSeparatedList(forStatement.Iterators);
			}
			
			Space(policy.SpacesWithinForParentheses);
			RPar();
			WriteEmbeddedStatement(forStatement.EmbeddedStatement);
			EndNode(forStatement);
		}
示例#60
0
 public void VisitForStatement(ForStatement forStatement)
 {
     throw new NotImplementedException();
 }