public static void RenameConflicting(ParametrizedNode method)
        {
            // variable name => case sensitive variable name
            // value is null if there are multiple casings for the variable -> the variable is conflicting
            Dictionary <string, string> caseInsensitive = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            LookupTableVisitor ltv = new LookupTableVisitor(SupportedLanguage.CSharp);

            method.AcceptVisitor(ltv, null);

            // add method name to caseInsensitive
            AddVariableToDict(caseInsensitive, method.Name, true);

            // add method parameters to caseInsensitive
            foreach (ParameterDeclarationExpression pde in method.Parameters)
            {
                AddVariableToDict(caseInsensitive, pde.ParameterName, true);
            }

            // add local variables to caseInsensitive
            foreach (KeyValuePair <string, List <LocalLookupVariable> > var in ltv.Variables)
            {
                AddVariableToDict(caseInsensitive, var.Key, true);
            }

            // add used identifiers to caseInsensitive
            FindIdentifiersVisitor fvv = new FindIdentifiersVisitor();

            method.AcceptVisitor(fvv, null);

            foreach (KeyValuePair <string, string> pair in fvv.usedIdentifiers)
            {
                AddVariableToDict(caseInsensitive, pair.Key, false);
            }

            int index = 0;

            foreach (ParameterDeclarationExpression pde in method.Parameters)
            {
                if (caseInsensitive[pde.ParameterName] == null)
                {
                    RenameVariable(method, pde.ParameterName, ref index);
                }
            }
            foreach (KeyValuePair <string, List <LocalLookupVariable> > var in ltv.Variables)
            {
                if (caseInsensitive[var.Key] == null)
                {
                    RenameVariable(method, var.Key, ref index);
                }
            }
        }
Ejemplo n.º 2
0
        void RunLookupTableVisitor(string fileContent)
        {
            lookupTableVisitor = new LookupTableVisitor(languageProperties.NameComparer);

            if (callingMember != null)
            {
                CompilationUnit cu = ParseCurrentMemberAsCompilationUnit(fileContent);
                if (cu != null)
                {
                    lookupTableVisitor.VisitCompilationUnit(cu, null);
                }
            }
        }
Ejemplo n.º 3
0
			protected override IEnumerable<IBaseMember> GetValidMembers ()
			{
				if (Options.EnclosingType == null || Options.EnclosingMember == null)
					yield break;
				
				// add local variables
				LookupTableVisitor visitor = new LookupTableVisitor (ICSharpCode.NRefactory.SupportedLanguage.CSharp);
				Location location = new Location (Options.Document.Editor.Caret.Line, Options.Document.Editor.Caret.Column);
				INRefactoryASTProvider provider = Options.GetASTProvider ();
				var result = provider.ParseFile (Options.Document.Editor.Text);
				result.AcceptVisitor (visitor, null);
				foreach (var list in visitor.Variables.Values) {
					foreach (LocalLookupVariable varDescr in list) {
						if (varDescr.StartPos <= location && location <= varDescr.EndPos)
							yield return new LocalVariable (Options.EnclosingMember, varDescr.Name, varDescr.TypeRef.ConvertToReturnType (), DomRegion.Empty);
					}
				}
				
				// add parameters
				IMethod method = Options.EnclosingMember as IMethod;
				if (method != null) {
					foreach (IParameter param in method.Parameters)
						yield return param;
				}
				
				IProperty p = Options.EnclosingMember as IProperty;
				if (p != null) {
					foreach (IParameter param in p.Parameters)
						yield return param;
				}
				
				// add type members
				foreach (IField field in Options.EnclosingType.Fields) {
					if (field.IsSpecialName)
						continue;
					yield return field;
				}

				foreach (IProperty property in Options.EnclosingType.Properties) {
					if (property.IsSpecialName)
						continue;
					if (property.HasGet)
						yield return property;
				}
			}
		public static void RenameConflicting(ParametrizedNode method)
		{
			// variable name => case sensitive variable name
			// value is null if there are multiple casings for the variable -> the variable is conflicting
			Dictionary<string, string> caseInsensitive = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			
			LookupTableVisitor ltv = new LookupTableVisitor(SupportedLanguage.CSharp);
			method.AcceptVisitor(ltv, null);
			
			// add method name to caseInsensitive
			AddVariableToDict(caseInsensitive, method.Name, true);
			
			// add method parameters to caseInsensitive
			foreach (ParameterDeclarationExpression pde in method.Parameters) {
				AddVariableToDict(caseInsensitive, pde.ParameterName, true);
			}
			
			// add local variables to caseInsensitive
			foreach (KeyValuePair<string, List<LocalLookupVariable>> var in ltv.Variables) {
				AddVariableToDict(caseInsensitive, var.Key, true);
			}
			
			// add used identifiers to caseInsensitive
			FindIdentifiersVisitor fvv = new FindIdentifiersVisitor();
			method.AcceptVisitor(fvv, null);
			
			foreach (KeyValuePair<string, string> pair in fvv.usedIdentifiers) {
				AddVariableToDict(caseInsensitive, pair.Key, false);
			}
			
			int index = 0;
			foreach (ParameterDeclarationExpression pde in method.Parameters) {
				if (caseInsensitive[pde.ParameterName] == null) {
					RenameVariable(method, pde.ParameterName, ref index);
				}
			}
			foreach (KeyValuePair<string, List<LocalLookupVariable>> var in ltv.Variables) {
				if (caseInsensitive[var.Key] == null) {
					RenameVariable(method, var.Key, ref index);
				}
			}
		}
Ejemplo n.º 5
0
 public void RunLookupTableVisitor(INode currentMemberNode)
 {
     lookupTableVisitor = new LookupTableVisitor(languageProperties.NameComparer);
     currentMemberNode.AcceptVisitor(lookupTableVisitor, null);
 }
Ejemplo n.º 6
0
        public ArrayList CtrlSpace(int caretLine, int caretColumn, string fileName, string fileContent, ExpressionContext context)
        {
            ArrayList result = new ArrayList();

            if (language == NR.SupportedLanguage.VBNet)
            {
                foreach (KeyValuePair <string, string> pair in TypeReference.PrimitiveTypesVB)
                {
                    if ("System." + pair.Key != pair.Value)
                    {
                        result.Add(GetPrimitiveClass(pair.Value, pair.Key));
                    }
                }
                result.Add("Global");
                result.Add("New");
            }
            else
            {
                foreach (KeyValuePair <string, string> pair in TypeReference.PrimitiveTypesCSharp)
                {
                    result.Add(GetPrimitiveClass(pair.Value, pair.Key));
                }
            }
            ParseInformation parseInfo = HostCallback.GetParseInformation(fileName);

            if (parseInfo == null)
            {
                return(null);
            }

            this.caretLine   = caretLine;
            this.caretColumn = caretColumn;

            lookupTableVisitor = new LookupTableVisitor(languageProperties.NameComparer);

            cu = parseInfo.MostRecentCompilationUnit;

            if (cu != null)
            {
                callingClass = cu.GetInnermostClass(caretLine, caretColumn);
            }

            callingMember = GetCurrentMember();
            if (callingMember != null)
            {
                CompilationUnit parsedCu = ParseCurrentMemberAsCompilationUnit(fileContent);
                if (parsedCu != null)
                {
                    lookupTableVisitor.VisitCompilationUnit(parsedCu, null);
                }
            }

            CtrlSpaceResolveHelper.AddContentsFromCalling(result, callingClass, callingMember);

            foreach (KeyValuePair <string, List <LocalLookupVariable> > pair in lookupTableVisitor.Variables)
            {
                if (pair.Value != null && pair.Value.Count > 0)
                {
                    foreach (LocalLookupVariable v in pair.Value)
                    {
                        if (IsInside(new NR.Location(caretColumn, caretLine), v.StartPos, v.EndPos))
                        {
                            // convert to a field for display
                            result.Add(CreateLocalVariableField(v, pair.Key));
                            break;
                        }
                    }
                }
            }
            CtrlSpaceResolveHelper.AddImportedNamespaceContents(result, cu, callingClass);
            return(result);
        }
Ejemplo n.º 7
0
		public override bool Extract()
		{
			using (var parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader("class Tmp { void Test() {\n " + this.textEditor.SelectedText + "\n}}"))) {
				parser.Parse();
				
				if (parser.Errors.Count > 0) {
					MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ParseErrors}");
					
					return false;
				}
				
				this.specialsList = parser.Lexer.SpecialTracker.RetrieveSpecials();
			}
			
			this.currentProjectContent = ParserService.GetProjectContent(ProjectService.CurrentProject);
			
			MethodDeclaration newMethod = new MethodDeclaration();
			List<VariableDeclaration> possibleReturnValues = new List<VariableDeclaration>();
			List<VariableDeclaration> otherReturnValues = new List<VariableDeclaration>();
			
			// Initialise new method
			newMethod.Body = GetBlock(this.textEditor.SelectedText);
			newMethod.Body.StartLocation = new Location(0,0);
			
			this.parentNode = GetParentMember(start, end);
			
			Dom.IMember member = GetParentMember(textEditor, textEditor.Caret.Line, textEditor.Caret.Column);
			
			if (parentNode == null || member == null) {
				MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.InvalidSelection}");
				return false;
			}
			
			this.currentClass = member.DeclaringType;
			
			ErrorKind kind = CheckForJumpInstructions(newMethod);
			if (kind != ErrorKind.None) {
				switch (kind) {
					case ErrorKind.ContainsBreak:
						MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsBreakError}");
						break;
					case ErrorKind.ContainsContinue:
						MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsContinueError}");
						break;
					case ErrorKind.ContainsGoto:
						MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsGotoError}");
						break;
				}
				return false;
			}
			
			newMethod.Modifier = parentNode.Modifier;
			
			newMethod.Modifier &= ~(Modifiers.Internal | Modifiers.Protected | Modifiers.Private | Modifiers.Public | Modifiers.Override);
			
			LookupTableVisitor ltv = new LookupTableVisitor(SupportedLanguage.CSharp);
			
			parentNode.AcceptVisitor(ltv, null);
			
			var variablesList = (from list in ltv.Variables.Values from item in list select new Variable(item))
				.Where(v => !(v.StartPos > end || v.EndPos < start) &&
				       (HasReferencesInSelection(newMethod, v) || 
				        HasOccurrencesAfter(CSharpNameComparer, this.parentNode, end, v.Name, v.StartPos, v.EndPos)))
				.Union(FromParameters(newMethod))
				.Select(va => ResolveVariable(va));
			
			foreach (var variable in variablesList) {
				LoggingService.Debug(variable);
				
				bool hasOccurrencesAfter = HasOccurrencesAfter(CSharpNameComparer, this.parentNode, end, variable.Name, variable.StartPos, variable.EndPos);
				bool isInitialized = (variable.Initializer != null) ? !variable.Initializer.IsNull : false;
				bool hasAssignment = HasAssignment(newMethod, variable);
				
				if (IsInCurrentSelection(variable.StartPos) && hasOccurrencesAfter) {
					possibleReturnValues.Add(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type));
					otherReturnValues.Add(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type));
				}
				
				if (!(IsInCurrentSelection(variable.StartPos) || IsInCurrentSelection(variable.EndPos))) {
					ParameterDeclarationExpression newParam = null;

					if ((hasOccurrencesAfter && isInitialized) || variable.WasRefParam)
						newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.Ref);
					else {
						if ((hasOccurrencesAfter && hasAssignment) || variable.WasOutParam)
							newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.Out);
						else {
							if (!hasOccurrencesAfter)
								newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.None);
							else {
								if (!hasOccurrencesAfter && !isInitialized)
									newMethod.Body.Children.Insert(0, new LocalVariableDeclaration(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type)));
								else
									newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.In);
							}
						}
					}
					if (newParam != null)
						newMethod.Parameters.Add(newParam);
				}
			}
			
			List<VariableDeclaration> paramsAsVarDecls = new List<VariableDeclaration>();
			this.beforeCallDeclarations = new List<LocalVariableDeclaration>();
			
			for (int i = 0; i < otherReturnValues.Count - 1; i++) {
				VariableDeclaration varDecl = otherReturnValues[i];
				paramsAsVarDecls.Add(varDecl);
				ParameterDeclarationExpression p = new ParameterDeclarationExpression(varDecl.TypeReference, varDecl.Name);
				p.ParamModifier = ParameterModifiers.Out;
				if (!newMethod.Parameters.Contains(p)) {
					newMethod.Parameters.Add(p);
				} else {
					this.beforeCallDeclarations.Add(new LocalVariableDeclaration(varDecl));
				}
			}
			
			CreateReturnStatement(newMethod, possibleReturnValues);
			
			newMethod.Name = "NewMethod";
			
			this.extractedMethod = newMethod;
			
			return true;
		}
Ejemplo n.º 8
0
        public NRefactoryResolver(ProjectDom dom, ICompilationUnit unit, SupportedLanguage lang, MonoDevelop.Ide.Gui.TextEditor editor, string fileName)
        {
            if (dom == null)
                throw new ArgumentNullException ("dom");
            this.unit = unit;

            this.dom = dom;
            this.lang   = lang;
            this.editor = editor;
            this.fileName = fileName;
            this.lookupTableVisitor = new LookupTableVisitor (lang);
        }
        // public override bool Extract(MethodDeclaration md, Window window, List<INode> children)
        public bool Extract(ParametrizedNode parentNode, Window window, List<INode> children)
        {
            this.currentSelection = new MySelection(children.GetRange(window.Top, window.Size));

            //            this.start = new Location(this.currentSelection.StartPosition.Column + 1, this.currentSelection.StartPosition.Line + 1);
            //            this.end = new Location(this.currentSelection.EndPosition.Column + 1, this.currentSelection.EndPosition.Line + 1);
            this.start = this.currentSelection.StartPosition;
            this.end = this.currentSelection.EndPosition;

            this.parentNode = parentNode;

            MethodDeclaration newMethod = new MethodDeclaration();

            // Initialise new method
            newMethod.Body = GetBlock(currentSelection.Nodes);
            newMethod.Body.StartLocation = new Location(0,0);

            List<VariableDeclaration> possibleReturnValues = new List<VariableDeclaration>();
            List<VariableDeclaration> otherReturnValues = new List<VariableDeclaration>();

            if (!CheckForJumpInstructions(newMethod, this.currentSelection))
                return false;
            newMethod.Modifier = parentNode.Modifier;
            newMethod.Modifier &= ~(Modifiers.Internal | Modifiers.Protected | Modifiers.Private | Modifiers.Public | Modifiers.Override);
            LookupTableVisitor ltv = new LookupTableVisitor(SupportedLanguage.CSharp);
            parentNode.AcceptVisitor(ltv, null);
            var variablesList = (from list in ltv.Variables.Values
                                 from item in list
                                 select new Variable(item)).Where(v => !(v.StartPos > end || v.EndPos < start) && HasReferencesInSelection(currentSelection, v)).Union(FromParameters(newMethod)).Select(va => ResolveVariable(va));
            foreach (var variable in variablesList) {

                bool hasOccurrencesAfter = HasOccurrencesAfter(CSharpNameComparer, this.parentNode, end, variable.Name, variable.StartPos, variable.EndPos);
                bool isInitialized = (variable.Initializer != null) ? !variable.Initializer.IsNull : false;
                bool hasAssignment = HasAssignment(newMethod, variable);
                if (IsInSel(variable.StartPos, this.currentSelection) && hasOccurrencesAfter) {
                    possibleReturnValues.Add(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type));
                    otherReturnValues.Add(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type));
                }
                if (!(IsInSel(variable.StartPos, this.currentSelection) || IsInSel(variable.EndPos, this.currentSelection))) {
                    ParameterDeclarationExpression newParam = null;
                    if ((hasOccurrencesAfter && isInitialized) || variable.WasRefParam)
                        newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.Ref);
                    else {
                        if ((hasOccurrencesAfter && hasAssignment) || variable.WasOutParam)
                            newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.Out);
                        else {
                            if (!hasOccurrencesAfter)
                                newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.None);
                            else {
                                if (!hasOccurrencesAfter && !isInitialized)
                                    newMethod.Body.Children.Insert(0, new LocalVariableDeclaration(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type)));
                                else
                                    newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.In);
                            }
                        }
                    }
                    if (newParam != null)
                        newMethod.Parameters.Add(newParam);
                }
            }

            List<VariableDeclaration> paramsAsVarDecls = new List<VariableDeclaration>();
            this.beforeCallDeclarations = new List<LocalVariableDeclaration>();

            for (int i = 0; i < otherReturnValues.Count - 1; i++) {
                VariableDeclaration varDecl = otherReturnValues[i];
                paramsAsVarDecls.Add(varDecl);
                ParameterDeclarationExpression p = new ParameterDeclarationExpression(varDecl.TypeReference, varDecl.Name);
                p.ParamModifier = ParameterModifiers.Out;
                if (!newMethod.Parameters.Contains(p)) {
                    newMethod.Parameters.Add(p);
                } else {
                    this.beforeCallDeclarations.Add(new LocalVariableDeclaration(varDecl));
                }
            }

            CreateReturnStatement(newMethod, possibleReturnValues);

            newMethod.Name = "NewMethod";

            this.extractedMethod = newMethod;

            return true;
        }