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);
			}
		}
		public void Run(AstNode node)
		{
			Run(node, null);
			// Declare all the variables at the end, after all the logic has run.
			// This is done so that definite assignment analysis can work on a single representation and doesn't have to be updated
			// when we change the AST.
			foreach (var v in variablesToDeclare) {
				if (v.ReplacedAssignment == null) {
					BlockStatement block = (BlockStatement)v.InsertionPoint.Parent;
					block.Statements.InsertBefore(
						v.InsertionPoint,
						new VariableDeclarationStatement((AstType)v.Type.Clone(), v.Name));
				}
			}
			// First do all the insertions, then do all the replacements. This is necessary because a replacement might remove our reference point from the AST.
			foreach (var v in variablesToDeclare) {
				if (v.ReplacedAssignment != null) {
					// We clone the right expression so that it doesn't get removed from the old ExpressionStatement,
					// which might be still in use by the definite assignment graph.
					VariableDeclarationStatement varDecl = new VariableDeclarationStatement {
						Type = (AstType)v.Type.Clone(),
						Variables = { new VariableInitializer(v.Name, v.ReplacedAssignment.Right.Detach()).CopyAnnotationsFrom(v.ReplacedAssignment) }
					};
					ExpressionStatement es = v.ReplacedAssignment.Parent as ExpressionStatement;
					if (es != null) {
						// Note: if this crashes with 'Cannot replace the root node', check whether two variables were assigned the same name
						es.ReplaceWith(varDecl.CopyAnnotationsFrom(es));
					} else {
						v.ReplacedAssignment.ReplaceWith(varDecl);
					}
				}
			}
			variablesToDeclare = null;
		}
		public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) {
			foreach (var varNode in variableDeclarationStatement.Variables) {
				AddVariable(varNode, varNode.Name);
			}

			base.VisitVariableDeclarationStatement(variableDeclarationStatement);
		}
Beispiel #4
0
        public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
        {
            Guard.AgainstNullArgument("methodDeclaration", methodDeclaration);

            IEnumerable<ParameterDeclaration> parameters = methodDeclaration
                .GetChildrenByRole(Roles.Parameter)
                .Select(x => (ParameterDeclaration)x.Clone());

            var isVoid = false;
            var isAsync = methodDeclaration.Modifiers.HasFlag(Modifiers.Async);
            AstType returnType = methodDeclaration.GetChildByRole(Roles.Type).Clone();
            var type = returnType as PrimitiveType;
            if (type != null)
            {
                isVoid = string.Compare(
                    type.Keyword, "void", StringComparison.OrdinalIgnoreCase) == 0;
            }

            var methodType = new SimpleType(Identifier.Create(isVoid ? "Action" : "Func"));

            IEnumerable<AstType> types = parameters.Select(
                x => x.GetChildByRole(Roles.Type).Clone());

            methodType
                .TypeArguments
                .AddRange(types);

            if (!isVoid)
            {
                methodType.TypeArguments.Add(returnType);
            }
            var methodName = GetIdentifierName(methodDeclaration);

            var methodBody = methodDeclaration
                .GetChildrenByRole(Roles.Body)
                .FirstOrDefault();
            if (methodBody == null)
            {
                throw new NullReferenceException(string.Format("Method '{0}' has no method body", methodName));
            }
            methodBody = (BlockStatement)methodBody.Clone();

            var prototype = new VariableDeclarationStatement { Type = methodType };
            prototype.Variables.Add(new VariableInitializer(methodName));

            var anonymousMethod = new AnonymousMethodExpression(methodBody, parameters) { IsAsync = isAsync };
            var expression = new ExpressionStatement
            {
                Expression = new AssignmentExpression(
                    new IdentifierExpression(methodName), 
                    anonymousMethod)
            };

            _methods.Add(new MethodVisitorResult
            {
                MethodDefinition = methodDeclaration,
                MethodPrototype = prototype,
                MethodExpression = expression
            });
        }
		void HandleVisitorVariableDeclarationStatementVisited (VariableDeclarationStatement node, InspectionData data)
		{
			foreach (var rule in policy.Rules) {
				if (rule.CheckVariableDeclaration (node, data))
					return;
			}
		}
 public override void VisitVariableDeclarationStatement(VariableDeclarationStatement varDecl)
 {
     //			if (CanBeSimplified(varDecl)) {
     //				varDecl.Type = new SimpleType("var");
     //			}
     // recurse into the statement (there might be a lambda with additional variable declaration statements inside there)
     base.VisitVariableDeclarationStatement(varDecl);
 }
            public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
            {
                if ((variableDeclarationStatement.Modifiers & Modifiers.Const) == Modifiers.Const)
                {
                    UnlockWith(variableDeclarationStatement);
                }

                return base.VisitVariableDeclarationStatement(variableDeclarationStatement, data);
            }
            public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
            {
                var anonInitializer = variableDeclarationStatement.Variables.FirstOrDefault(a => a.Initializer is AnonymousTypeCreateExpression);
                if (anonInitializer != null)
                {
                    UnlockWith(anonInitializer.Initializer);
                }

                return base.VisitVariableDeclarationStatement(variableDeclarationStatement, data);
            }
Beispiel #9
0
 public override void Visit(VariableDeclarationStatement expression)
 {
     if (expression.Expression != null)
     {
         outStream.Write("var {0} = {1}(", expression.Identifier, printFuncName);
         expression.Expression.Accept(this);
         outStream.Write(", \"{0}\")", TempName);
     }
     else
         outStream.Write("var {0}", expression.Identifier);
 }
			static VariableInitializer GetControlVariable(VariableDeclarationStatement variableDecl,
														  UnaryOperatorExpression condition)
			{
				var controlVariables = variableDecl.Variables.Where (
					v =>
					{
						var identifier = new IdentifierExpression (v.Name);
						return condition.Expression.Match (identifier).Success;
					}).ToList ();
				return controlVariables.Count == 1 ? controlVariables [0] : null;
			}
		void HandleVisitiorVariableDeclarationStatementVisited (VariableDeclarationStatement node, InspectionData data)
		{
			if (node.Type is PrimitiveType)
				return;
			if (node.Type is SimpleType && ((SimpleType)node.Type).Identifier == "var") 
				return;
			var severity = base.node.GetSeverity ();
			if (severity == MonoDevelop.SourceEditor.QuickTaskSeverity.None)
				return;
			//only checks for cases where the type would be obvious - assignment of new, cast, etc.
			//also check the type actually matches else the user might want to assign different subclasses later
			foreach (var v in node.Variables) {
				if (v.Initializer.IsNull)
					return;
				
				var arrCreate = v.Initializer as ArrayCreateExpression;
				if (arrCreate != null) {
					var n = node.Type as ComposedType;
					//FIXME: check the specifier compatibility
					if (n != null && n.ArraySpecifiers.Any () && n.BaseType.IsMatch (arrCreate.Type))
						continue;
					return;
				}
				var objCreate = v.Initializer as ObjectCreateExpression;
				if (objCreate != null) {
					if (objCreate.Type.IsMatch (node.Type))
						continue;
					return;
				}
				var asCast = v.Initializer as AsExpression;
				if (asCast != null) {
					if (asCast.Type.IsMatch (node.Type))
						continue;
					return;
				}
				var cast = v.Initializer as CastExpression;
				if (cast != null) {
					if (cast.Type.IsMatch (node.Type))
						continue;
					return;
				}
				return;
			}
			
			data.Add (new Result (
					new DomRegion (node.Type.StartLocation.Line, node.Type.StartLocation.Column, node.Type.EndLocation.Line, node.Type.EndLocation.Column),
					GettextCatalog.GetString ("Use implicitly typed local variable decaration"),
					severity,
					ResultCertainty.High, 
					ResultImportance.Medium,
					severity != MonoDevelop.SourceEditor.QuickTaskSeverity.Suggestion)
				);
		}
		public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
		{
			base.VisitVariableDeclarationStatement(variableDeclarationStatement);
			foreach (var varDecl in variableDeclarationStatement.Variables) {
				if (startLocation.IsEmpty || startLocation <= varDecl.StartLocation && varDecl.EndLocation <= endLocation) {
					var result = context.Resolve(varDecl);
					var local = result as LocalResolveResult;
					if (local != null && !UsedVariables.Contains(local.Variable))
						UsedVariables.Add(local.Variable);
				}
			}
		}
			public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
			{
				base.VisitVariableDeclarationStatement(variableDeclarationStatement);

				if (!(variableDeclarationStatement.Parent is BlockStatement))
					// We are somewhere weird, like a the ResourceAquisition of a using statement
					return;

				if (variableDeclarationStatement.Variables.Count > 1)
					return;

				// Start at the parent node. Presumably this is a BlockStatement
				var rootNode = variableDeclarationStatement.Parent;
				var variableInitializer = variableDeclarationStatement.Variables.First();
				var identifiers = GetIdentifiers(rootNode.Descendants, variableInitializer.Name).ToList();

				if (identifiers.Count == 0)
					// variable is not used
					return;

				AstNode deepestCommonAncestor = GetDeepestCommonAncestor(rootNode, identifiers);
				var path = GetPath(rootNode, deepestCommonAncestor);

				// Restrict path to only those where the initializer has not changed
				var firstInitializerChange = GetFirstInitializerChange(variableDeclarationStatement, path, variableInitializer.Initializer);
				if (firstInitializerChange != null) {
					path = GetPath(rootNode, firstInitializerChange);
				}

				// Restict to locations outside of blacklisted node types
				var firstBlackListedNode = (from node in path
				                            where moveTargetBlacklist.Contains(node.GetType())
				                            select node).FirstOrDefault();
				if (firstBlackListedNode != null) {
					path = GetPath(rootNode, firstBlackListedNode);
				}

				// Get the most nested possible target for the move
				Statement mostNestedFollowingStatement = null;
				for (int i = path.Count - 1; i >= 0; i--) {
					var statement = path[i] as Statement;
					if (statement != null && (IsScopeContainer(statement.Parent) || IsScopeContainer(statement))) {
						mostNestedFollowingStatement = statement;
						break;
					}
				}

				if (mostNestedFollowingStatement != null && mostNestedFollowingStatement != rootNode && mostNestedFollowingStatement.Parent != rootNode) {
					AddIssue(variableDeclarationStatement, context.TranslateString("Variable could be moved to a nested scope"),
					         GetActions(variableDeclarationStatement, mostNestedFollowingStatement));
				}
			}
 bool CanBeSimplified(VariableDeclarationStatement varDecl)
 {
     if (varDecl.Variables.Count != 1)
         return false;
     if (varDecl.Modifiers != Modifiers.None) // this line was "forgotten" in the article
         return false;
     VariableInitializer v = varDecl.Variables.Single();
     ObjectCreateExpression oce = v.Initializer as ObjectCreateExpression;
     if (oce == null)
         return false;
     //return ?AreEqualTypes?(varDecl.Type, oce.Type);
     return varDecl.Type.IsMatch(oce.Type);
 }
		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var pexpr = context.GetNode<PrimitiveExpression>();
			if (pexpr == null)
				yield break;
			var statement = context.GetNode<Statement>();
			if (statement == null) {
				yield break;
			}

			var resolveResult = context.Resolve(pexpr);

			yield return new CodeAction(context.TranslateString("Create local constant"), script => {
				string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
				var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
				if (service != null)
					name = service.CheckName(context, name, AffectedEntity.LocalConstant);

				var initializer = new VariableInitializer(name, pexpr.Clone());
				var decl = new VariableDeclarationStatement() {
					Type = context.CreateShortType(resolveResult.Type),
					Modifiers = Modifiers.Const,
					Variables = { initializer }
				};

				script.InsertBefore(statement, decl);
				var variableUsage = new IdentifierExpression(name);
				script.Replace(pexpr, variableUsage);
				script.Link(initializer.NameToken, variableUsage);
			});

			yield return new CodeAction(context.TranslateString("Create constant field"), script => {
				string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
				var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
				if (service != null)
					name = service.CheckName(context, name, AffectedEntity.ConstantField);

				var initializer = new VariableInitializer(name, pexpr.Clone());

				var decl = new FieldDeclaration() {
					ReturnType = context.CreateShortType(resolveResult.Type),
					Modifiers = Modifiers.Const,
					Variables = { initializer }
				};

				var variableUsage = new IdentifierExpression(name);
				script.Replace(pexpr, variableUsage);
//				script.Link(initializer.NameToken, variableUsage);
				script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
			});
		}
        protected override IEnumerable<CodeAction> GetFixes(BaseSemanticModel context, Node env,
                                                             string variableName)
        {
            var containingStatement = env.ContainingStatement;

            // we don't give a fix for these cases since the general fix may not work
            // lambda in while/do-while/for condition
            if (containingStatement is WhileStatement || containingStatement is DoWhileStatement ||
                containingStatement is ForStatement)
                yield break;
            // lambda in for initializer/iterator
            if (containingStatement.Parent is ForStatement &&
                ((ForStatement)containingStatement.Parent).EmbeddedStatement != containingStatement)
                yield break;

            Action<Script> action = script =>
            {
                var newName = LocalVariableNamePicker.PickSafeName(
                    containingStatement.GetParent<EntityDeclaration>(),
                    Enumerable.Range(1, 100).Select(i => variableName + i));

                var variableDecl = new VariableDeclarationStatement(new SimpleType("var"), newName,
                                                                     new IdentifierExpression(variableName));

                if (containingStatement.Parent is BlockStatement || containingStatement.Parent is SwitchSection)
                {
                    script.InsertBefore(containingStatement, variableDecl);
                }
                else
                {
                    var offset = script.GetCurrentOffset(containingStatement.StartLocation);
                    script.InsertBefore(containingStatement, variableDecl);
                    script.InsertText(offset, "{");
                    script.InsertText(script.GetCurrentOffset(containingStatement.EndLocation), "}");
                    script.FormatText(containingStatement.Parent);
                }

                var textNodes = new List<AstNode>();
                textNodes.Add(variableDecl.Variables.First().NameToken);

                foreach (var reference in env.GetAllReferences())
                {
                    var identifier = new IdentifierExpression(newName);
                    script.Replace(reference.AstNode, identifier);
                    textNodes.Add(identifier);
                }
                script.Link(textNodes.ToArray());
            };
            yield return new CodeAction(context.TranslateString("Copy to local variable"), action, env.AstNode);
        }
Beispiel #17
0
		static CodeAction MoveDeclarationAction(RefactoringContext context, AstNode insertAnchor,
		                                        VariableDeclarationStatement declarationStatement, VariableInitializer initializer)
		{
			var type = declarationStatement.Type.Clone();
			var name = initializer.Name;
			
			return new CodeAction(context.TranslateString("Move declaration to outer scope"), script =>  {
				script.InsertBefore(declarationStatement, new ExpressionStatement() {
					Expression = new AssignmentExpression(new IdentifierExpression(name), initializer.Initializer.Clone())
				});
				script.Remove(declarationStatement);
				script.InsertBefore(insertAnchor, new VariableDeclarationStatement(type, name, Expression.Null));
			});
		}
Beispiel #18
0
		static CodeAction MoveInitializerAction(RefactoringContext context, AstNode insertAnchor,
		                                        VariableDeclarationStatement declaration, VariableInitializer initializer)
		{
			var type = declaration.Type.Clone();
			var name = initializer.Name;
			return new CodeAction(context.TranslateString("Move initializer to outer scope"), script =>  {
				if (declaration.Variables.Count != 1) {
					var innerDeclaration = RemoveInitializer(declaration, initializer);
					script.InsertBefore(declaration, innerDeclaration);
				}
				script.Remove(declaration);
				var outerDeclaration = new VariableDeclarationStatement(type, name, initializer.Initializer.Clone());
				script.InsertBefore(insertAnchor, outerDeclaration);
			});
		}
 /// <summary>
 /// Declares a variable in the smallest required scope.
 /// </summary>
 /// <param name="node">The root of the subtree being searched for the best insertion position</param>
 /// <param name="type">The type of the new variable</param>
 /// <param name="name">The name of the new variable</param>
 /// <param name="allowPassIntoLoops">Whether the variable is allowed to be placed inside a loop</param>
 public static VariableDeclarationStatement DeclareVariable(AstNode node, AstType type, string name, bool allowPassIntoLoops = true)
 {
     VariableDeclarationStatement result = null;
     AstNode pos = FindInsertPos(node, name, allowPassIntoLoops);
     if (pos != null) {
         Match m = assignmentPattern.Match(pos);
         if (m != null && m.Get<IdentifierExpression>("ident").Single().Identifier == name) {
             result = new VariableDeclarationStatement(type, name, m.Get<Expression>("init").Single().Detach());
             pos.ReplaceWith(result);
         } else {
             result = new VariableDeclarationStatement(type, name);
             pos.Parent.InsertChildBefore(pos, result, BlockStatement.StatementRole);
         }
     }
     return result;
 }
		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);
			});
		}
            private int curseCount = 0; //This is where it should be

            #endregion Fields

            #region Methods

            public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
            {
                var foulwords = new[]
                {
                    "f**k", "shit", "crap", "bollocks"
                };

                foreach (var foulword in foulwords)
                {
                    foreach (var variable in variableDeclarationStatement.Variables)
                    {
                        if (Regex.Matches(variable.Name, foulword).Count > 0)
                            curseCount++;
                    }
                }

                if (curseCount > 5)
                    UnlockWith(variableDeclarationStatement);

                return base.VisitVariableDeclarationStatement(variableDeclarationStatement, data);
            }
Beispiel #22
0
            public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
            {
                var foulwords = new[]
                {
                    "meh","blah", "pft", "rrrr","blib","blab", "blub","lol","uhu","aaah"
                };

                foreach (var foulword in foulwords)
                {
                    foreach (var variable in variableDeclarationStatement.Variables)
                    {
                        if (Regex.Matches(variable.Name, foulword).Count > 0)
                            _curseCount++;
                    }
                }

                if (_curseCount > 5)
                    UnlockWith(variableDeclarationStatement);

                return base.VisitVariableDeclarationStatement(variableDeclarationStatement, data);
            }
        public override void VisitVariableDeclarationStatement(
            VariableDeclarationStatement variableDeclarationStatement)
        {
            base.VisitVariableDeclarationStatement(variableDeclarationStatement);

            if (variableDeclarationStatement.Variables.Count != 1)
                return;

            var variable = variableDeclarationStatement.Variables.First();
            switch (variable.Name)
            {
                case "__cx":
                case "__cy":
                case "__cz":
                case "__cwidth":
                case "__cheight":
                case "__cdepth":
                    this.m_CInitializers[variable.Name] = variable.Initializer;
                    variableDeclarationStatement.Remove();
                    break;
            }
        }
        public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
        {
            var identifier = context.GetNode<IdentifierExpression>();
            if (identifier == null) {
                yield break;
            }
            if (CreateFieldAction.IsInvocationTarget(identifier)) {
                yield break;
            }
            var statement = context.GetNode<Statement>();
            if (statement == null) {
                yield break;
            }

            if (!(context.Resolve(identifier).IsError)) {
                yield break;
            }
            var guessedType = CreateFieldAction.GuessAstType(context, identifier);
            if (guessedType == null) {
                yield break;
            }

            yield return new CodeAction(context.TranslateString("Create local variable"), script => {
                var initializer = new VariableInitializer(identifier.Identifier);
                var decl = new VariableDeclarationStatement() {
                    Type = guessedType,
                    Variables = { initializer }
                };
                if (identifier.Parent is AssignmentExpression && ((AssignmentExpression)identifier.Parent).Left == identifier) {
                    initializer.Initializer = ((AssignmentExpression)identifier.Parent).Right.Clone();
                    if (!context.UseExplicitTypes)
                        decl.Type = new SimpleType("var");
                    script.Replace(statement, decl);
                } else {
                    script.InsertBefore(statement, decl);
                }
            }, identifier);
        }
Beispiel #25
0
			public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
			{
				base.VisitVariableDeclarationStatement(variableDeclarationStatement);
				if (variableDeclarationStatement.Type is PrimitiveType) {
					return;
				}
				if (variableDeclarationStatement.Type is SimpleType && ((SimpleType)variableDeclarationStatement.Type).Identifier == "var") { 
					return;
				}
				if (variableDeclarationStatement.Variables.Count != 1) {
					return;
				}
				
				//only checks for cases where the type would be obvious - assignment of new, cast, etc.
				//also check the type actually matches else the user might want to assign different subclasses later
				var v = variableDeclarationStatement.Variables.Single();
				
				var arrCreate = v.Initializer as ArrayCreateExpression;
				if (arrCreate != null) {
					var n = variableDeclarationStatement.Type as ComposedType;
					//FIXME: check the specifier compatibility
					if (n != null && n.ArraySpecifiers.Any() && n.BaseType.IsMatch(arrCreate.Type)) {
						AddIssue(variableDeclarationStatement);
					}
				}
				var objCreate = v.Initializer as ObjectCreateExpression;
				if (objCreate != null && objCreate.Type.IsMatch(variableDeclarationStatement.Type)) {
					AddIssue(variableDeclarationStatement);
				}
				var asCast = v.Initializer as AsExpression;
				if (asCast != null && asCast.Type.IsMatch(variableDeclarationStatement.Type)) {
					AddIssue(variableDeclarationStatement);
				}
				var cast = v.Initializer as CastExpression;
				if (cast != null && cast.Type.IsMatch(variableDeclarationStatement.Type)) {
					AddIssue(variableDeclarationStatement);
				}
			}
            public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
            {
                foreach(var variable in variableDeclarationStatement.Variables)
                {
                    var objectCreation = variable.Initializer as ObjectCreateExpression;
                    if(objectCreation != null)
                    {
                        var simpleType = objectCreation.Type as SimpleType;
                        if(simpleType != null && simpleType.Identifier == "Thread")
                        {
                            UnlockWith(simpleType);
                            break;
                        }

                        var memberType = objectCreation.Type as MemberType;
                        var fullNamespace = memberType.GetFullName();
                        if(fullNamespace == "System.Threading.Thread")
                        {
                            UnlockWith(memberType);
                        }
                    }
                }
                return base.VisitVariableDeclarationStatement(variableDeclarationStatement, data);
            }
Beispiel #27
0
 IEnumerable <Syntax> IAstVisitor <ILTranslationContext, IEnumerable <Syntax> > .VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, ILTranslationContext data)
 => OnVisiting(data, variableDeclarationStatement, VisitingVariableDeclarationStatement)
 ?? OnVisited(data, variableDeclarationStatement, VisitedVariableDeclarationStatement, TranslateVariableDeclarationStatement(variableDeclarationStatement, data));
        //-------------------------------------------------------------------------------------------------------------------------------------------------

        public override void VisitVariableDeclaraitonStatement(VariableDeclarationStatement statement)
        {
            base.VisitVariableDeclaraitonStatement(statement);
            AddReferencedType(statement.Variable?.Type);
        }
        public void NestedArray()
        {
            VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement <VariableDeclarationStatement>("DateTime[,][] a;");

            Assert.IsTrue(new VariableDeclarationStatement(new SimpleType("DateTime").MakeArrayType(1).MakeArrayType(2), "a").IsMatch(lvd));
        }
Beispiel #30
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            if (!context.IsSomethingSelected)
            {
                yield break;
            }
            var selected = new List <AstNode>(context.GetSelectedNodes());

            if (selected.Count != 1 || !(selected [0] is Expression))
            {
                yield break;
            }
            var expr    = selected [0] as Expression;
            var visitor = new SearchNodeVisitior(expr);

            var node = context.GetNode <BlockStatement>();

            if (node != null)
            {
                node.AcceptVisitor(visitor);
            }

            yield return(new CodeAction(context.TranslateString("Declare local variable"), script =>
            {
                var resolveResult = context.Resolve(expr);
                var guessedType = resolveResult.Type;
                if (resolveResult is MethodGroupResolveResult)
                {
                    guessedType = GetDelegateType(context, ((MethodGroupResolveResult)resolveResult).Methods.First(), expr);
                }
                var name = CreateMethodDeclarationAction.CreateBaseName(expr, guessedType);
                var type = context.UseExplicitTypes ? context.CreateShortType(guessedType) : new SimpleType("var");
                var varDecl = new VariableDeclarationStatement(type, name, expr.Clone());
                if (expr.Parent is ExpressionStatement)
                {
                    script.Replace(expr.Parent, varDecl);
                    script.Select(varDecl.Variables.First().NameToken);
                }
                else
                {
                    var containing = expr.Parent;
                    while (!(containing.Parent is BlockStatement))
                    {
                        containing = containing.Parent;
                    }

                    script.InsertBefore(containing, varDecl);
                    var identifierExpression = new IdentifierExpression(name);
                    script.Replace(expr, identifierExpression);
                    script.Link(varDecl.Variables.First().NameToken, identifierExpression);
                }
            }));

            if (visitor.Matches.Count > 1)
            {
                yield return(new CodeAction(string.Format(context.TranslateString("Declare local variable (replace '{0}' occurrences)"), visitor.Matches.Count), script =>
                {
                    var resolveResult = context.Resolve(expr);
                    var guessedType = resolveResult.Type;
                    if (resolveResult is MethodGroupResolveResult)
                    {
                        guessedType = GetDelegateType(context, ((MethodGroupResolveResult)resolveResult).Methods.First(), expr);
                    }
                    var linkedNodes = new List <AstNode>();
                    var name = CreateMethodDeclarationAction.CreateBaseName(expr, guessedType);
                    var type = context.UseExplicitTypes ? context.CreateShortType(guessedType) : new SimpleType("var");
                    var varDecl = new VariableDeclarationStatement(type, name, expr.Clone());
                    linkedNodes.Add(varDecl.Variables.First().NameToken);
                    var first = visitor.Matches [0];
                    if (first.Parent is ExpressionStatement)
                    {
                        script.Replace(first.Parent, varDecl);
                    }
                    else
                    {
                        var containing = first.Parent;
                        while (!(containing.Parent is BlockStatement))
                        {
                            containing = containing.Parent;
                        }

                        script.InsertBefore(containing, varDecl);
                        var identifierExpression = new IdentifierExpression(name);
                        linkedNodes.Add(identifierExpression);
                        script.Replace(first, identifierExpression);
                    }
                    for (int i = 1; i < visitor.Matches.Count; i++)
                    {
                        var identifierExpression = new IdentifierExpression(name);
                        linkedNodes.Add(identifierExpression);
                        script.Replace(visitor.Matches [i], identifierExpression);
                    }
                    script.Link(linkedNodes.ToArray());
                }));
            }
        }
        public void ArrayOfNullables()
        {
            VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement <VariableDeclarationStatement>("DateTime?[] a;");

            Assert.IsTrue(new VariableDeclarationStatement(new SimpleType("DateTime").MakeNullableType().MakeArrayType(), "a").IsMatch(lvd));
        }
        public void VoidPointerVariableDeclarationTest()
        {
            VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement <VariableDeclarationStatement>("void *a;");

            Assert.IsTrue(new VariableDeclarationStatement(new PrimitiveType("void").MakePointerType(), "a").IsMatch(lvd));
        }
Beispiel #33
0
 public void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
 {
     throw new NotImplementedException();
 }
Beispiel #34
0
        public override AstNode VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, ICecilArgumentsResolver argumentsResolver)
        {
            variableDeclarationStatement.Type.AcceptVisitor(this, argumentsResolver);

            return(variableDeclarationStatement);
        }
Beispiel #35
0
        static bool UsesVariable(AstNode node, string variableName)
        {
            IdentifierExpression ie = node as IdentifierExpression;

            if (ie != null && ie.Identifier == variableName)
            {
                return(true);
            }

            FixedStatement fixedStatement = node as FixedStatement;

            if (fixedStatement != null)
            {
                foreach (VariableInitializer v in fixedStatement.Variables)
                {
                    if (v.Name == variableName)
                    {
                        return(false);                        // no need to introduce the variable here
                    }
                }
            }

            ForeachStatement foreachStatement = node as ForeachStatement;

            if (foreachStatement != null)
            {
                if (foreachStatement.VariableName == variableName)
                {
                    return(false);                    // no need to introduce the variable here
                }
            }

            UsingStatement usingStatement = node as UsingStatement;

            if (usingStatement != null)
            {
                VariableDeclarationStatement varDecl = usingStatement.ResourceAcquisition as VariableDeclarationStatement;
                if (varDecl != null)
                {
                    foreach (VariableInitializer v in varDecl.Variables)
                    {
                        if (v.Name == variableName)
                        {
                            return(false);                            // no need to introduce the variable here
                        }
                    }
                }
            }

            CatchClause catchClause = node as CatchClause;

            if (catchClause != null && catchClause.VariableName == variableName)
            {
                return(false);                // no need to introduce the variable here
            }

            for (AstNode child = node.FirstChild; child != null; child = child.NextSibling)
            {
                if (UsesVariable(child, variableName))
                {
                    return(true);
                }
            }
            return(false);
        }
        public void NullableVariableDeclarationStatementTest1()
        {
            VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement <VariableDeclarationStatement>("int? a;");

            Assert.IsTrue(new VariableDeclarationStatement(new PrimitiveType("int").MakeNullableType(), "a").IsMatch(lvd));
        }
		CodeAction CreateFromStatements(RefactoringContext context, List<AstNode> statements)
		{
			if (!(statements [0].Parent is Statement))
				return null;
			
			return new CodeAction(context.TranslateString("Extract method"), script => {
				string methodName = "NewMethod";
				var method = new MethodDeclaration() {
					ReturnType = new PrimitiveType("void"),
					Name = methodName,
					Body = new BlockStatement()
				};
				bool usesNonStaticMember = false;
				foreach (var node in statements) {
					usesNonStaticMember |= StaticVisitor.UsesNotStaticMember(context, node);
					if (node is Statement) {
						method.Body.Add((Statement)node.Clone());
					} else {
						method.Body.AddChildUnsafe (node.Clone (), node.Role);
					}
				}
				if (!usesNonStaticMember)
					method.Modifiers |= Modifiers.Static;
				
				var target = new IdentifierExpression(methodName);
				var invocation = new InvocationExpression(target);
				
				var usedVariables = VariableLookupVisitor.Analyze(context, statements);
				
				var inExtractedRegion = new VariableUsageAnalyzation (context, usedVariables);
				var lastStatement = statements [statements.Count - 1];
				
				var stmt = statements [0].GetParent<BlockStatement>();
				while (stmt.GetParent<BlockStatement> () != null) {
					stmt = stmt.GetParent<BlockStatement>();
				}
				
				inExtractedRegion.SetAnalyzedRange(statements [0], lastStatement);
				stmt.AcceptVisitor (inExtractedRegion);
				
				var beforeExtractedRegion = new VariableUsageAnalyzation (context, usedVariables);
				beforeExtractedRegion.SetAnalyzedRange(statements [0].Parent, statements [0], true, false);
				stmt.AcceptVisitor (beforeExtractedRegion);
				
				var afterExtractedRegion = new VariableUsageAnalyzation (context, usedVariables);
				afterExtractedRegion.SetAnalyzedRange(lastStatement, stmt.Statements.Last(), false, true);
				stmt.AcceptVisitor (afterExtractedRegion);
				usedVariables.Sort ((l, r) => l.Region.Begin.CompareTo (r.Region.Begin));

				IVariable generatedReturnVariable = null;
				foreach (var variable in usedVariables) {
					if ((variable is IParameter) || beforeExtractedRegion.Has (variable) || !afterExtractedRegion.Has (variable))
						continue;
					generatedReturnVariable = variable;
					method.ReturnType = context.CreateShortType (variable.Type);
					method.Body.Add (new ReturnStatement (new IdentifierExpression (variable.Name)));
					break;
				}

				int parameterOutCount = 0;
				foreach (var variable in usedVariables) {
					if (!(variable is IParameter) && !beforeExtractedRegion.Has (variable) && !afterExtractedRegion.Has (variable))
						continue;
					if (variable == generatedReturnVariable)
						continue;
					Expression argumentExpression = new IdentifierExpression(variable.Name); 
					
					ParameterModifier mod = ParameterModifier.None;
					if (inExtractedRegion.GetStatus (variable) == VariableState.Changed) {
						if (beforeExtractedRegion.GetStatus (variable) == VariableState.None) {
							mod = ParameterModifier.Out;
							argumentExpression = new DirectionExpression(FieldDirection.Out, argumentExpression);
							parameterOutCount++;
						} else {
							mod = ParameterModifier.Ref;
							argumentExpression = new DirectionExpression(FieldDirection.Ref, argumentExpression);
						}
					}
					
					method.Parameters.Add(new ParameterDeclaration(context.CreateShortType(variable.Type), variable.Name, mod));
					invocation.Arguments.Add(argumentExpression);
				}

				ParameterDeclaration parameterToTransform = null;
				bool transformParameterToReturn = method.ReturnType is PrimitiveType && 
				                                  ((PrimitiveType)method.ReturnType).Keyword == "void" &&
				                                  parameterOutCount == 1;
				if(transformParameterToReturn) {
					parameterToTransform = method.Parameters.First(p => p.ParameterModifier == ParameterModifier.Out);
					parameterToTransform.Remove();
					var argumentExpression = invocation.Arguments.OfType<DirectionExpression>().First(a => a.FieldDirection == FieldDirection.Out);
					argumentExpression.Remove();
					method.ReturnType = parameterToTransform.Type.Clone();
					var argumentDecl = new VariableDeclarationStatement(parameterToTransform.Type.Clone(),parameterToTransform.Name);
					method.Body.InsertChildBefore(method.Body.First(),argumentDecl,BlockStatement.StatementRole);
					method.Body.Add(new ReturnStatement (new IdentifierExpression (parameterToTransform.Name)));
				}

				script
					.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method)
					.ContinueScript(delegate {
						foreach (var node in statements.Skip (1)) {
							if (node is NewLineNode)
								continue;
							script.Remove(node);
						}
						foreach (var variable in usedVariables) {
							if ((variable is IParameter) || beforeExtractedRegion.Has (variable) || !afterExtractedRegion.Has (variable))
								continue;
							if (variable == generatedReturnVariable)
								continue;
							script.InsertBefore (statements [0], new VariableDeclarationStatement (context.CreateShortType(variable.Type), variable.Name));
						}
						Statement invocationStatement;

						if (generatedReturnVariable != null) {
							invocationStatement = new VariableDeclarationStatement (new SimpleType ("var"), generatedReturnVariable.Name, invocation);
						} else if(transformParameterToReturn) {
							invocationStatement = new AssignmentExpression(new IdentifierExpression(parameterToTransform.Name), invocation);
						} else {
							invocationStatement = invocation;
						}

						script.Replace(statements [0], invocationStatement);


						script.Link(target, method.NameToken);
					});
			}, statements.First ().StartLocation, statements.Last ().EndLocation);
		}
Beispiel #38
0
			VariableDeclarationStatement CreateVariableDeclaration (LocalInfo info)
			{
				VariableDeclarationStatement result = new VariableDeclarationStatement ();
				result.AddChild ((INode)info.Type.Accept (this), CatchClause.Roles.ReturnType);
				VariableInitializer variable = new VariableInitializer ();
				variable.AddChild (new Identifier (info.Name, Convert (info.Location)), AbstractNode.Roles.Identifier);
				result.AddChild (variable, AbstractNode.Roles.Initializer);
				
				result.AddChild (new Identifier (info.Name, Convert (info.Location)), CatchClause.Roles.ReturnType);
				return result;
			}
Beispiel #39
0
        CodeAction CreateFromStatements(RefactoringContext context, List <AstNode> statements)
        {
            if (!(statements [0].Parent is Statement))
            {
                return(null);
            }

            return(new CodeAction(context.TranslateString("Extract method"), script => {
                string methodName = "NewMethod";
                var method = new MethodDeclaration()
                {
                    ReturnType = new PrimitiveType("void"),
                    Name = methodName,
                    Body = new BlockStatement()
                };
                bool usesNonStaticMember = false;
                foreach (var node in statements)
                {
                    usesNonStaticMember |= StaticVisitor.UsesNotStaticMember(context, node);
                    if (node is Statement)
                    {
                        method.Body.Add((Statement)node.Clone());
                    }
                    else
                    {
                        method.Body.AddChildUnsafe(node.Clone(), node.Role);
                    }
                }
                if (!usesNonStaticMember)
                {
                    method.Modifiers |= Modifiers.Static;
                }

                var target = new IdentifierExpression(methodName);
                var invocation = new InvocationExpression(target);

                var usedVariables = VariableLookupVisitor.Analyze(context, statements);

                var inExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                var lastStatement = statements [statements.Count - 1];

                var stmt = statements [0].GetParent <BlockStatement>();
                while (stmt.GetParent <BlockStatement> () != null)
                {
                    stmt = stmt.GetParent <BlockStatement>();
                }

                inExtractedRegion.SetAnalyzedRange(statements [0], lastStatement);
                stmt.AcceptVisitor(inExtractedRegion);

                var beforeExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                beforeExtractedRegion.SetAnalyzedRange(statements [0].Parent, statements [0], true, false);
                stmt.AcceptVisitor(beforeExtractedRegion);

                var afterExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                afterExtractedRegion.SetAnalyzedRange(lastStatement, stmt.Statements.Last(), false, true);
                stmt.AcceptVisitor(afterExtractedRegion);
                usedVariables.Sort((l, r) => l.Region.Begin.CompareTo(r.Region.Begin));

                IVariable generatedReturnVariable = null;
                foreach (var variable in usedVariables)
                {
                    if ((variable is IParameter) || beforeExtractedRegion.Has(variable) || !afterExtractedRegion.Has(variable))
                    {
                        continue;
                    }
                    generatedReturnVariable = variable;
                    method.ReturnType = context.CreateShortType(variable.Type);
                    method.Body.Add(new ReturnStatement(new IdentifierExpression(variable.Name)));
                    break;
                }

                foreach (var variable in usedVariables)
                {
                    if (!(variable is IParameter) && !beforeExtractedRegion.Has(variable) && !afterExtractedRegion.Has(variable))
                    {
                        continue;
                    }
                    if (variable == generatedReturnVariable)
                    {
                        continue;
                    }
                    Expression argumentExpression = new IdentifierExpression(variable.Name);

                    ParameterModifier mod = ParameterModifier.None;
                    if (inExtractedRegion.GetStatus(variable) == VariableState.Changed)
                    {
                        if (beforeExtractedRegion.GetStatus(variable) == VariableState.None)
                        {
                            mod = ParameterModifier.Out;
                            argumentExpression = new DirectionExpression(FieldDirection.Out, argumentExpression);
                        }
                        else
                        {
                            mod = ParameterModifier.Ref;
                            argumentExpression = new DirectionExpression(FieldDirection.Ref, argumentExpression);
                        }
                    }

                    method.Parameters.Add(new ParameterDeclaration(context.CreateShortType(variable.Type), variable.Name, mod));
                    invocation.Arguments.Add(argumentExpression);
                }
                var task = script.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method);
                Action <Task> replaceStatements = delegate {
                    foreach (var node in statements.Skip(1))
                    {
                        if (node is NewLineNode)
                        {
                            continue;
                        }
                        script.Remove(node);
                    }
                    foreach (var variable in usedVariables)
                    {
                        if ((variable is IParameter) || beforeExtractedRegion.Has(variable) || !afterExtractedRegion.Has(variable))
                        {
                            continue;
                        }
                        if (variable == generatedReturnVariable)
                        {
                            continue;
                        }
                        script.InsertBefore(statements [0], new VariableDeclarationStatement(context.CreateShortType(variable.Type), variable.Name));
                    }
                    AstNode invocationStatement;

                    if (generatedReturnVariable != null)
                    {
                        invocationStatement = new VariableDeclarationStatement(new SimpleType("var"), generatedReturnVariable.Name, invocation);
                    }
                    else
                    {
                        invocationStatement = new ExpressionStatement(invocation);
                    }
                    script.Replace(statements [0], invocationStatement);


                    script.Link(target, method.NameToken);
                };

                if (task.IsCompleted)
                {
                    replaceStatements(null);
                }
                else
                {
                    task.ContinueWith(replaceStatements, TaskScheduler.FromCurrentSynchronizationContext());
                }
            }, statements.First().StartLocation, statements.Last().EndLocation));
        }
Beispiel #40
0
 public virtual bool Visit(VariableDeclarationStatement node)
 {
     return(CommonVisit(node));
 }
Beispiel #41
0
 public override void Visit(VariableDeclarationStatement node)
 {
     VisitNodes(node.Declarations);
     Visit((Statement)node);
     WriteEdges(node, node.Declarations, "declaration");
 }
 void AddTo(IfElseStatement ifElseStatement, VariableDeclarationStatement varDeclaration, Expression expr)
 {
 }
 public virtual Node VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
 {
     throw new System.NotImplementedException();
 }
Beispiel #44
0
        public override object VisitBlockStatement(BlockStatement blockStatement, object data)
        {
            int numberOfVariablesOutsideBlock = currentlyUsedVariableNames.Count;

            base.VisitBlockStatement(blockStatement, data);
            foreach (ExpressionStatement stmt in blockStatement.Statements.OfType <ExpressionStatement>().ToArray())
            {
                Match displayClassAssignmentMatch = displayClassAssignmentPattern.Match(stmt);
                if (!displayClassAssignmentMatch.Success)
                {
                    continue;
                }

                ILVariable variable = displayClassAssignmentMatch.Get <AstNode>("variable").Single().Annotation <ILVariable>();
                if (variable == null)
                {
                    continue;
                }
                TypeDefinition type = variable.Type.ResolveWithinSameModule();
                if (!IsPotentialClosure(context, type))
                {
                    continue;
                }
                if (displayClassAssignmentMatch.Get <AstType>("type").Single().Annotation <TypeReference>().ResolveWithinSameModule() != type)
                {
                    continue;
                }

                // Looks like we found a display class creation. Now let's verify that the variable is used only for field accesses:
                bool ok = true;
                foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>())
                {
                    if (identExpr.Identifier == variable.Name && identExpr != displayClassAssignmentMatch.Get("variable").Single())
                    {
                        if (!(identExpr.Parent is MemberReferenceExpression && identExpr.Parent.Annotation <FieldReference>() != null))
                        {
                            ok = false;
                        }
                    }
                }
                if (!ok)
                {
                    continue;
                }
                Dictionary <FieldReference, AstNode> dict = new Dictionary <FieldReference, AstNode>();

                // Delete the variable declaration statement:
                VariableDeclarationStatement displayClassVarDecl = PatternStatementTransform.FindVariableDeclaration(stmt, variable.Name);
                if (displayClassVarDecl != null)
                {
                    displayClassVarDecl.Remove();
                }

                // Delete the assignment statement:
                AstNode cur = stmt.NextSibling;
                stmt.Remove();

                // Delete any following statements as long as they assign parameters to the display class
                BlockStatement    rootBlock            = blockStatement.Ancestors.OfType <BlockStatement>().LastOrDefault() ?? blockStatement;
                List <ILVariable> parameterOccurrances = rootBlock.Descendants.OfType <IdentifierExpression>()
                                                         .Select(n => n.Annotation <ILVariable>()).Where(p => p != null && p.IsParameter).ToList();
                AstNode next;
                for (; cur != null; cur = next)
                {
                    next = cur.NextSibling;

                    // Test for the pattern:
                    // "variableName.MemberName = right;"
                    ExpressionStatement closureFieldAssignmentPattern = new ExpressionStatement(
                        new AssignmentExpression(
                            new NamedNode("left", new MemberReferenceExpression {
                        Target = new IdentifierExpression(variable.Name)
                    }),
                            new AnyNode("right")
                            )
                        );
                    Match m = closureFieldAssignmentPattern.Match(cur);
                    if (m.Success)
                    {
                        FieldDefinition fieldDef    = m.Get <MemberReferenceExpression>("left").Single().Annotation <FieldReference>().ResolveWithinSameModule();
                        AstNode         right       = m.Get <AstNode>("right").Single();
                        bool            isParameter = false;
                        bool            isDisplayClassParentPointerAssignment = false;
                        if (right is ThisReferenceExpression)
                        {
                            isParameter = true;
                        }
                        else if (right is IdentifierExpression)
                        {
                            // handle parameters only if the whole method contains no other occurrence except for 'right'
                            ILVariable v = right.Annotation <ILVariable>();
                            isParameter = v.IsParameter && parameterOccurrances.Count(c => c == v) == 1;
                            if (!isParameter && IsPotentialClosure(context, v.Type.ResolveWithinSameModule()))
                            {
                                // parent display class within the same method
                                // (closure2.localsX = closure1;)
                                isDisplayClassParentPointerAssignment = true;
                            }
                        }
                        else if (right is MemberReferenceExpression)
                        {
                            // copy of parent display class reference from an outer lambda
                            // closure2.localsX = this.localsY
                            MemberReferenceExpression mre = m.Get <MemberReferenceExpression>("right").Single();
                            do
                            {
                                // descend into the targets of the mre as long as the field types are closures
                                FieldDefinition fieldDef2 = mre.Annotation <FieldReference>().ResolveWithinSameModule();
                                if (fieldDef2 == null || !IsPotentialClosure(context, fieldDef2.FieldType.ResolveWithinSameModule()))
                                {
                                    break;
                                }
                                // if we finally get to a this reference, it's copying a display class parent pointer
                                if (mre.Target is ThisReferenceExpression)
                                {
                                    isDisplayClassParentPointerAssignment = true;
                                }
                                mre = mre.Target as MemberReferenceExpression;
                            } while (mre != null);
                        }
                        if (isParameter || isDisplayClassParentPointerAssignment)
                        {
                            dict[fieldDef] = right;
                            cur.Remove();
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                // Now create variables for all fields of the display class (except for those that we already handled as parameters)
                List <Tuple <AstType, string> > variablesToDeclare = new List <Tuple <AstType, string> >();
                foreach (FieldDefinition field in type.Fields)
                {
                    if (field.IsStatic)
                    {
                        continue;                         // skip static fields
                    }
                    if (dict.ContainsKey(field))          // skip field if it already was handled as parameter
                    {
                        continue;
                    }
                    EnsureVariableNameIsAvailable(blockStatement, field.Name);
                    currentlyUsedVariableNames.Add(field.Name);
                    variablesToDeclare.Add(Tuple.Create(AstBuilder.ConvertType(field.FieldType, field), field.Name));
                    dict[field] = new IdentifierExpression(field.Name);
                }

                // Now figure out where the closure was accessed and use the simpler replacement expression there:
                foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>())
                {
                    if (identExpr.Identifier == variable.Name)
                    {
                        MemberReferenceExpression mre = (MemberReferenceExpression)identExpr.Parent;
                        AstNode replacement;
                        if (dict.TryGetValue(mre.Annotation <FieldReference>().ResolveWithinSameModule(), out replacement))
                        {
                            mre.ReplaceWith(replacement.Clone());
                        }
                    }
                }
                // Now insert the variable declarations (we can do this after the replacements only so that the scope detection works):
                Statement insertionPoint = blockStatement.Statements.FirstOrDefault();
                foreach (var tuple in variablesToDeclare)
                {
                    var newVarDecl = new VariableDeclarationStatement(tuple.Item1, tuple.Item2);
                    newVarDecl.Variables.Single().AddAnnotation(new CapturedVariableAnnotation());
                    blockStatement.Statements.InsertBefore(insertionPoint, newVarDecl);
                }
            }
            currentlyUsedVariableNames.RemoveRange(numberOfVariablesOutsideBlock, currentlyUsedVariableNames.Count - numberOfVariablesOutsideBlock);
            return(null);
        }
Beispiel #45
0
 public NotificationChain basicSetVariableDeclarationStatement(VariableDeclarationStatement newobj, NotificationChain msgs)
 {
     msgs = eBasicSetContainer((InternalEObject)newobj, Java_PackageImpl.MODIFIER_VARIABLEDECLARATIONSTATEMENT, msgs);
     return(msgs);
 }
Beispiel #46
0
 public override IEnumerable <Expression> VisitVariableDeclarationStatement(
     VariableDeclarationStatement variableDeclarationStatement)
 {
     return(variableDeclarationStatement.Variables.Select(v => v.Initializer));
 }
Beispiel #47
0
 public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
 {
     new VariableBlock(this, variableDeclarationStatement).Emit();
 }
Beispiel #48
0
        protected virtual Statement EmitUsing(UsingStatement usingStatement, AstNode expression, IEnumerable <AstNode> inner, VariableDeclarationStatement varStat)
        {
            string         name    = null;
            BlockStatement wrapper = null;

            var varInit = expression as VariableInitializer;

            if (varInit != null)
            {
                name    = varInit.Name;
                wrapper = new BlockStatement();
                wrapper.Statements.Add(new VariableDeclarationStatement(varStat != null ? varStat.Type.Clone() : AstType.Null, varInit.Name, varInit.Initializer.Clone()));
            }
            else if (expression is IdentifierExpression)
            {
                name = ((IdentifierExpression)expression).Identifier;
            }
            else
            {
                name    = this.GetTempVarName();
                wrapper = new BlockStatement();
                wrapper.Statements.Add(new VariableDeclarationStatement(varStat != null ? varStat.Type.Clone() : AstType.Null, name, expression.Clone() as Expression));
            }

            var tryCatchStatement = new TryCatchStatement();

            if (wrapper != null)
            {
                wrapper.Statements.Add(tryCatchStatement);
            }

            if (inner != null && inner.Any())
            {
                var block = new BlockStatement();
                block.Statements.Add(this.EmitUsing(usingStatement, inner.First(), inner.Skip(1), varStat));
                tryCatchStatement.TryBlock = block;
            }
            else
            {
                var block = usingStatement.EmbeddedStatement as BlockStatement;

                if (block == null)
                {
                    block = new BlockStatement();
                    block.Add(usingStatement.EmbeddedStatement.Clone());
                }
                else
                {
                    block = (BlockStatement)block.Clone();
                }

                tryCatchStatement.TryBlock = block;
            }

            var finallyBlock = new BlockStatement();
            var dispose      = new InvocationExpression(
                new MemberReferenceExpression(
                    new MemberReferenceExpression(new TypeReferenceExpression(new MemberType(new SimpleType("global"), CS.NS.BRIDGE)
            {
                IsDoubleColon = true
            }), "Script"), "Write"),
                new PrimitiveExpression(
                    string.Format("if (" + JS.Funcs.BRIDGE_HASVALUE + "({0})) {0}." + JS.Funcs.DISPOSE + "();", name))
                );

            finallyBlock.Statements.Add(dispose);

            tryCatchStatement.FinallyBlock = finallyBlock;
            return(wrapper ?? (Statement)tryCatchStatement);
        }
        public void NestedPointers()
        {
            VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement <VariableDeclarationStatement>("DateTime*** a;");

            Assert.IsTrue(new VariableDeclarationStatement(new SimpleType("DateTime").MakePointerType().MakePointerType().MakePointerType(), "a").IsMatch(lvd));
        }
Beispiel #50
0
            void TransformBody(List <InvocationExpression> validInvocations, bool isVoid, bool isParameterizedTask, InvocationExpression returnedContinuation, string taskCompletionSourceIdentifier, BlockStatement blockStatement)
            {
                if (!isVoid)
                {
                    if (returnedContinuation == null)
                    {
                        //Is TaskCompletionSource-based
                        blockStatement.Statements.First().Remove();                        //Remove task completion source declaration
                        blockStatement.Statements.Last().Remove();                         //Remove final return
                    }

                    //We use ToList() because we will be modifying the original collection
                    foreach (var expressionStatement in blockStatement.Descendants.OfType <ExpressionStatement>().ToList())
                    {
                        var invocationExpression = expressionStatement.Expression as InvocationExpression;
                        if (invocationExpression == null || invocationExpression.Arguments.Count != 1)
                        {
                            continue;
                        }

                        var target = invocationExpression.Target as MemberReferenceExpression;
                        if (target == null || target.MemberName != "SetResult")
                        {
                            continue;
                        }
                        var targetExpression = target.Target as IdentifierExpression;
                        if (targetExpression == null || targetExpression.Identifier != taskCompletionSourceIdentifier)
                        {
                            continue;
                        }

                        var returnedExpression = invocationExpression.Arguments.Single();
                        returnedExpression.Remove();

                        var originalInvocation         = (InvocationExpression)invocationExpression.Annotation <OriginalNodeAnnotation>().sourceNode;
                        var originalReturnedExpression = originalInvocation.Arguments.Single();
                        var argumentType = ctx.Resolve(originalReturnedExpression).Type;

                        if (!isParameterizedTask)
                        {
                            var parent           = expressionStatement.Parent;
                            var resultIdentifier = CreateVariableName(blockStatement, "result");

                            var blockParent           = parent as BlockStatement;
                            var resultDeclarationType = argumentType == SpecialType.NullType ? new PrimitiveType("object") : CreateShortType(originalInvocation, argumentType);
                            var declaration           = new VariableDeclarationStatement(resultDeclarationType, resultIdentifier, returnedExpression);
                            if (blockParent == null)
                            {
                                var newStatement = new BlockStatement();
                                newStatement.Add(declaration);
                                newStatement.Add(new ReturnStatement());
                                expressionStatement.ReplaceWith(newStatement);
                            }
                            else
                            {
                                blockParent.Statements.InsertAfter(expressionStatement, new ReturnStatement());
                                expressionStatement.ReplaceWith(declaration);
                            }
                        }
                        else
                        {
                            var newStatement = new ReturnStatement(returnedExpression);
                            expressionStatement.ReplaceWith(newStatement);
                        }
                    }
                }

                //Find all instances of ContinueWith to replace and associated
                var continuations = new List <Tuple <InvocationExpression, InvocationExpression, string> >();

                foreach (var invocation in blockStatement.Descendants.OfType <InvocationExpression>())
                {
                    if (invocation.Arguments.Count != 1)
                    {
                        continue;
                    }

                    var originalInvocation = (InvocationExpression)invocation.Annotation <OriginalNodeAnnotation>().sourceNode;
                    if (!validInvocations.Contains(originalInvocation))
                    {
                        continue;
                    }

                    var lambda = invocation.Arguments.Single();

                    string associatedTaskName = null;

                    var lambdaParameters        = lambda.GetChildrenByRole(Roles.Parameter).Select(p => p.Name).ToList();
                    var lambdaTaskParameterName = lambdaParameters.FirstOrDefault();
                    if (lambdaTaskParameterName != null)
                    {
                        associatedTaskName = lambdaTaskParameterName;
                    }

                    continuations.Add(Tuple.Create(invocation, originalInvocation, associatedTaskName));
                }

                foreach (var continuationTuple in continuations)
                {
                    string taskName           = continuationTuple.Item3 ?? "task";
                    string effectiveTaskName  = CreateVariableName(blockStatement, taskName);
                    string resultName         = CreateVariableName(blockStatement, taskName + "Result");
                    var    continuation       = continuationTuple.Item1;
                    var    originalInvocation = continuationTuple.Item2;

                    var target            = continuation.Target.GetChildByRole(Roles.TargetExpression).Detach();
                    var awaitedExpression = new UnaryOperatorExpression(UnaryOperatorType.Await, target);
                    var replacements      = new List <Statement>();
                    var lambdaExpression  = originalInvocation.Arguments.First();
                    var continuationLambdaResolveResult = (LambdaResolveResult)ctx.Resolve(lambdaExpression);

                    if (!continuationLambdaResolveResult.HasParameterList)
                    {
                        //Lambda has no parameter, so creating a variable for the argument is not needed
                        // (since you can't use an argument that doesn't exist).
                        replacements.Add(new ExpressionStatement(awaitedExpression));
                    }
                    else
                    {
                        //Lambda has a parameter, which can either be a Task or a Task<T>.

                        var  lambdaParameter      = continuationLambdaResolveResult.Parameters[0];
                        bool isTaskIdentifierUsed = lambdaExpression.Descendants.OfType <IdentifierExpression>().Any(identifier => {
                            if (identifier.Identifier != lambdaParameter.Name)
                            {
                                return(false);
                            }
                            var identifierMre = identifier.Parent as MemberReferenceExpression;
                            return(identifierMre == null || identifierMre.MemberName != "Result");
                        });

                        var precedentTaskType = lambdaParameter.Type;

                        //We might need to separate the task creation and awaiting
                        if (isTaskIdentifierUsed)
                        {
                            //Create new task variable
                            var taskExpression = awaitedExpression.Expression;
                            taskExpression.Detach();
                            replacements.Add(new VariableDeclarationStatement(CreateShortType(lambdaExpression, precedentTaskType),
                                                                              effectiveTaskName,
                                                                              taskExpression));
                            awaitedExpression.Expression = new IdentifierExpression(effectiveTaskName);
                        }

                        if (precedentTaskType.IsParameterized)
                        {
                            //precedent is Task<T>
                            var precedentResultType = precedentTaskType.TypeArguments.First();
                            replacements.Add(new VariableDeclarationStatement(CreateShortType(originalInvocation, precedentResultType), resultName, awaitedExpression));
                        }
                        else
                        {
                            //precedent is Task
                            replacements.Add(awaitedExpression);
                        }
                    }

                    var parentStatement      = continuation.GetParent <Statement>();
                    var grandParentStatement = parentStatement.Parent;
                    var block = grandParentStatement as BlockStatement;
                    if (block == null)
                    {
                        block = new BlockStatement();
                        block.Statements.AddRange(replacements);
                        parentStatement.ReplaceWith(block);
                    }
                    else
                    {
                        foreach (var replacement in replacements)
                        {
                            block.Statements.InsertBefore(parentStatement, replacement);
                        }
                        parentStatement.Remove();
                    }

                    var       lambdaOrDelegate = continuation.Arguments.Single();
                    Statement lambdaContent;
                    if (lambdaOrDelegate is LambdaExpression)
                    {
                        lambdaContent = (Statement)lambdaOrDelegate.GetChildByRole(LambdaExpression.BodyRole);
                    }
                    else
                    {
                        lambdaContent = lambdaOrDelegate.GetChildByRole(Roles.Body);
                    }

                    foreach (var identifierExpression in lambdaContent.Descendants.OfType <IdentifierExpression>())
                    {
                        if (continuationTuple.Item3 != identifierExpression.Identifier)
                        {
                            continue;
                        }

                        var memberReference = identifierExpression.Parent as MemberReferenceExpression;

                        if (memberReference == null || memberReference.MemberName != "Result")
                        {
                            identifierExpression.ReplaceWith(new IdentifierExpression(effectiveTaskName));
                            continue;
                        }

                        memberReference.ReplaceWith(new IdentifierExpression(resultName));
                    }

                    if (lambdaContent is BlockStatement)
                    {
                        Statement previousStatement = replacements.Last();
                        foreach (var statementInContinuation in lambdaContent.GetChildrenByRole(BlockStatement.StatementRole))
                        {
                            statementInContinuation.Detach();
                            block.Statements.InsertAfter(previousStatement, statementInContinuation);
                            previousStatement = statementInContinuation;
                        }
                    }
                    else
                    {
                        lambdaContent.Detach();
                        block.Statements.InsertAfter(replacements.Last(), lambdaContent);
                    }
                }
            }
Beispiel #51
0
 public VariableBlock(IEmitter emitter, VariableDeclarationStatement variableDeclarationStatement)
     : base(emitter, variableDeclarationStatement)
 {
     this.Emitter = emitter;
     this.VariableDeclarationStatement = variableDeclarationStatement;
 }
Beispiel #52
0
 public virtual void EndVisit(VariableDeclarationStatement node)
 {
     CommonEndVisit(node);
 }
Beispiel #53
0
 public override ControlFlowNode VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, ControlFlowNode data)
 {
     return(CreateConnectedEndNode(variableDeclarationStatement, data));
 }
Beispiel #54
0
 public virtual void VisitVariableDeclarationStatement(VariableDeclarationStatement node) => DefaultVisit(node);
 public virtual void Visit(VariableDeclarationStatement expression)
 {
     logVisit(expression);
 }
Beispiel #56
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var pexpr = context.GetNode <PrimitiveExpression>();

            if (pexpr == null)
            {
                yield break;
            }
            var statement = context.GetNode <Statement>();

            if (statement == null)
            {
                yield break;
            }

            var visitor = new DeclareLocalVariableAction.SearchNodeVisitior(pexpr);

            var node = context.GetNode <BlockStatement>();

            if (node != null)
            {
                node.AcceptVisitor(visitor);
            }

            var resolveResult = context.Resolve(pexpr);

            yield return(new CodeAction(context.TranslateString("Create local constant"), script => {
                string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                if (service != null)
                {
                    name = service.CheckName(context, name, AffectedEntity.LocalConstant);
                }

                var initializer = new VariableInitializer(name, pexpr.Clone());
                var decl = new VariableDeclarationStatement()
                {
                    Type = context.CreateShortType(resolveResult.Type),
                    Modifiers = Modifiers.Const,
                    Variables = { initializer }
                };

                script.InsertBefore(statement, decl);
                var variableUsage = new IdentifierExpression(name);
                script.Replace(pexpr, variableUsage);
                script.Link(initializer.NameToken, variableUsage);
            }, pexpr));

            yield return(new CodeAction(context.TranslateString("Create constant field"), script => {
                string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                if (service != null)
                {
                    name = service.CheckName(context, name, AffectedEntity.ConstantField);
                }

                var initializer = new VariableInitializer(name, pexpr.Clone());

                var decl = new FieldDeclaration()
                {
                    ReturnType = context.CreateShortType(resolveResult.Type),
                    Modifiers = Modifiers.Const,
                    Variables = { initializer }
                };

                var variableUsage = new IdentifierExpression(name);
                script.Replace(pexpr, variableUsage);
                //				script.Link(initializer.NameToken, variableUsage);
                script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
            }, pexpr));

            if (visitor.Matches.Count > 1)
            {
                yield return(new CodeAction(string.Format(context.TranslateString("Create local constant (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
                    string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                    var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                    if (service != null)
                    {
                        name = service.CheckName(context, name, AffectedEntity.LocalConstant);
                    }

                    var initializer = new VariableInitializer(name, pexpr.Clone());
                    var decl = new VariableDeclarationStatement()
                    {
                        Type = context.CreateShortType(resolveResult.Type),
                        Modifiers = Modifiers.Const,
                        Variables = { initializer }
                    };

                    script.InsertBefore(statement, decl);

                    var linkedNodes = new List <AstNode>();
                    linkedNodes.Add(initializer.NameToken);
                    for (int i = 0; i < visitor.Matches.Count; i++)
                    {
                        var identifierExpression = new IdentifierExpression(name);
                        linkedNodes.Add(identifierExpression);
                        script.Replace(visitor.Matches [i], identifierExpression);
                    }
                    script.Link(linkedNodes.ToArray());
                }, pexpr));

                yield return(new CodeAction(string.Format(context.TranslateString("Create constant field (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
                    string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                    var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                    if (service != null)
                    {
                        name = service.CheckName(context, name, AffectedEntity.ConstantField);
                    }

                    var initializer = new VariableInitializer(name, pexpr.Clone());

                    var decl = new FieldDeclaration()
                    {
                        ReturnType = context.CreateShortType(resolveResult.Type),
                        Modifiers = Modifiers.Const,
                        Variables = { initializer }
                    };

                    var linkedNodes = new List <AstNode>();
                    linkedNodes.Add(initializer.NameToken);
                    for (int i = 0; i < visitor.Matches.Count; i++)
                    {
                        var identifierExpression = new IdentifierExpression(name);
                        linkedNodes.Add(identifierExpression);
                        script.Replace(visitor.Matches [i], identifierExpression);
                    }
                    script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
                }, pexpr));
            }
        }
Beispiel #57
0
		public void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
		{
			StartNode(variableDeclarationStatement);
			WriteModifiers(variableDeclarationStatement.GetChildrenByRole(VariableDeclarationStatement.ModifierRole));
			variableDeclarationStatement.Type.AcceptVisitor(this);
			Space();
			WriteCommaSeparatedList(variableDeclarationStatement.Variables);
			Semicolon();
			EndNode(variableDeclarationStatement);
		}
Beispiel #58
0
 public override void Visit(VariableDeclarationStatement node)
 {
     PushLocation(node);
     VisitNodes(node.Declarations);
     PopLocation();
 }
Beispiel #59
0
 public VariableBlock(IEmitter emitter, VariableDeclarationStatement variableDeclarationStatement)
     : base(emitter, variableDeclarationStatement)
 {
     this.Emitter = emitter;
     this.VariableDeclarationStatement = variableDeclarationStatement;
 }
Beispiel #60
0
 public override object VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, object data)
 {
     FixStatementIndentation(variableDeclarationStatement.StartLocation);
     return(null);
 }