void ConvertInterfaceImplementation(MethodDeclaration member)
		{
			// members without modifiers are already C# explicit interface implementations, do not convert them
			if (member.Modifier == Modifiers.None)
				return;
			while (member.InterfaceImplementations.Count > 0) {
				InterfaceImplementation impl = member.InterfaceImplementations[0];
				member.InterfaceImplementations.RemoveAt(0);
				if (member.Name != impl.MemberName) {
					MethodDeclaration newMember = new MethodDeclaration {
						Name = impl.MemberName,
						TypeReference = member.TypeReference,
						Parameters = member.Parameters,
						Body = new BlockStatement()
					};
					InvocationExpression callExpression = new InvocationExpression(new IdentifierExpression(member.Name));
					foreach (ParameterDeclarationExpression decl in member.Parameters) {
						callExpression.Arguments.Add(new IdentifierExpression(decl.ParameterName));
					}
					if (member.TypeReference.Type == "System.Void") {
						newMember.Body.AddChild(new ExpressionStatement(callExpression));
					} else {
						newMember.Body.AddChild(new ReturnStatement(callExpression));
					}
					newMember.InterfaceImplementations.Add(impl);
					InsertAfterSibling(member, newMember);
				}
			}
		}
        protected override bool VerifyMethodCondition(TypeDeclaration typeDeclaration, MethodDeclaration methodDeclaration)
        {
            IList methods = AstUtil.GetChildrenWithType(typeDeclaration, typeof(MethodDeclaration));
            string name = methodDeclaration.Name.Substring(3);

            if (Contains(methods, methodDeclaration))
            {
                IList innerTypes = AstUtil.GetChildrenWithType(typeDeclaration, typeof(TypeDeclaration));
                foreach (TypeDeclaration innerType in innerTypes)
                {
                    if (innerType.Name == name)
                        return true;
                }
                IList constructors = AstUtil.GetChildrenWithType(typeDeclaration, typeof(ConstructorDeclaration));
                foreach (ConstructorDeclaration constructorDeclaration in constructors)
                {
                    if (constructorDeclaration.Name == name)
                        return true;
                }
                foreach (MethodDeclaration method in methods)
                {
                    if (method.Name == name || char.ToUpper(method.Name[0]) + method.Name.Substring(1) == name)
                        return true;
                }
            }
            else
            {
                IList properties = AstUtil.GetChildrenWithType(typeDeclaration, typeof(PropertyDeclaration));
                return Contains(properties, name);
            }
            return false;
        }
Exemplo n.º 3
0
        protected bool IsMethodInExternalTypes(TypeDeclaration typeDeclaration, MethodDeclaration methodDeclaration)
        {
            bool found = false;
            foreach (TypeReference baseType in typeDeclaration.BaseTypes)
            {
                string fullName = GetFullName(baseType);
                if (!found && CodeBase.Types.Contains(fullName))
                {
                    TypeDeclaration baseTypeDeclaration = (TypeDeclaration) CodeBase.Types[fullName];

                    if (IsInExternalLibraries(fullName) || fullName.StartsWith("Helpers."))
                    {
                        IList methods = AstUtil.GetChildrenWithType(baseTypeDeclaration, typeof(MethodDeclaration));
                        if (ContainsMethod(methods, methodDeclaration))
                            found = true;
                        else
                            found = IsMethodInExternalTypes(baseTypeDeclaration, methodDeclaration);
                    }
                    else
                        found = IsMethodInExternalTypes(baseTypeDeclaration, methodDeclaration);
                    if (found)
                        break;
                }
            }
            return found;
        }
        public override object VisitMethodDeclaration(MethodDeclaration declaration, object data)
        {
            if (!HasContainerType(declaration, ClassType.Interface) && declaration.InterfaceImplementations.Count == 0) 
                MakePublic(declaration);

            return base.VisitMethodDeclaration(declaration, data);
        }
        public override object TrackedVisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
        {
            if (IsDerivedFrom(typeDeclaration, "Comparator"))
            {
                IList methods = AstUtil.GetChildrenWithType(typeDeclaration, typeof(MethodDeclaration));

                MethodDeclaration equalsMethod = new MethodDeclaration("equals",
                                                                       Modifiers.Public, AstUtil.GetTypeReference("bool", typeDeclaration), new List<ParameterDeclarationExpression>(), null);
                equalsMethod.Parent = typeDeclaration;

                TypeReference argTypeReference = AstUtil.GetTypeReference("java.lang.Object", equalsMethod);
                argTypeReference.RankSpecifier = new int[] {};
                equalsMethod.Parameters.Add(new ParameterDeclarationExpression(argTypeReference, "obj"));

                if (Contains(methods, equalsMethod))
                {
                    int index = IndexOf(methods, equalsMethod);
                    MethodDeclaration method = (MethodDeclaration) methods[index];
                    AstUtil.RemoveModifierFrom(method, Modifiers.Abstract);
                    method.TypeReference.Type = "bool";
                    CreateMethodImplementation(method);
                }
                else
                {
                    CreateMethodImplementation(equalsMethod);
                    typeDeclaration.Children.Add(equalsMethod);
                    equalsMethod.Parent = typeDeclaration;
                }
            }
            return base.TrackedVisitTypeDeclaration(typeDeclaration, data);
        }
        public override object TrackedVisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
        {
            if (IsAbstractClass(typeDeclaration))
            {
                IList currentClassMethods = AstUtil.GetChildrenWithType(typeDeclaration, typeof(MethodDeclaration));
                currentClassMethods = GetMethodsInParents(typeDeclaration, currentClassMethods, true);
                IList methodsInParents = new ArrayList();
                methodsInParents = GetMethodsInParents(typeDeclaration, methodsInParents, false);
                methodsInParents = FilterImplementedMethods(methodsInParents);
                IList abstractMethods = GetDiffList(currentClassMethods, methodsInParents);

                if (abstractMethods.Count > 0)
                {
                    TypeDeclaration replacedTypeDeclaration = typeDeclaration;
                    foreach (MethodDeclaration method in abstractMethods)
                    {
                        MethodDeclaration newMethod;
                        newMethod = new MethodDeclaration(method.Name,
                                                          Modifiers.Public | Modifiers.Abstract,
                                                          method.TypeReference,
                                                          method.Parameters,
                                                          method.Attributes);
                        newMethod.Parent = replacedTypeDeclaration;
                        replacedTypeDeclaration.Children.Add(newMethod);
                    }
                    ReplaceCurrentNode(replacedTypeDeclaration);
                }
            }
            return base.TrackedVisitTypeDeclaration(typeDeclaration, data);
        }
Exemplo n.º 7
0
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                if (methodDeclaration.Modifier.HasFlag(Modifiers.Abstract))
                    UnlockWith(methodDeclaration);

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
        public override object VisitMethodDeclaration(AST.MethodDeclaration methodDeclaration, object data)
        {
            DomRegion    region     = GetRegion(methodDeclaration.StartLocation, methodDeclaration.EndLocation);
            DomRegion    bodyRegion = GetRegion(methodDeclaration.EndLocation, methodDeclaration.Body != null ? methodDeclaration.Body.EndLocation : RefParser.Location.Empty);
            DefaultClass c          = GetCurrentClass();

            DefaultMethod method = new DefaultMethod(methodDeclaration.Name, null, ConvertModifier(methodDeclaration.Modifier), region, bodyRegion, GetCurrentClass());

            method.Documentation = GetDocumentation(region.BeginLine, methodDeclaration.Attributes);
            ConvertTemplates(methodDeclaration.Templates, method);
            method.ReturnType = CreateReturnType(methodDeclaration.TypeReference, method);
            ConvertAttributes(methodDeclaration, method);
            if (methodDeclaration.Parameters != null && methodDeclaration.Parameters.Count > 0)
            {
                foreach (AST.ParameterDeclarationExpression par in methodDeclaration.Parameters)
                {
                    method.Parameters.Add(CreateParameter(par, method));
                }
            }
            else
            {
                method.Parameters = DefaultParameter.EmptyParameterList;
            }
            c.Methods.Add(method);
            return(null);
        }
        public static MethodDeclaration add_Method(this TypeDeclaration typeDeclaration, string methodName, Dictionary<string, object> invocationParameters, BlockStatement body)
        {
            var newMethod = new MethodDeclaration
            {
                Name = methodName,
                //Modifier = Modifiers.None | Modifiers.Public | Modifiers.Static,
                Modifier = Modifiers.None | Modifiers.Public,
                Body = body
            };
            newMethod.setReturnType();
            if (invocationParameters != null)

                foreach (var invocationParameter in invocationParameters)
                {
                    var parameterType = new TypeReference(
                        (invocationParameter.Value != null && invocationParameter.Key != "returnData")
                        ? invocationParameter.Value.typeFullName()
                        : "System.Object", true);
                    var parameter = new ParameterDeclarationExpression(parameterType, invocationParameter.Key);
                    newMethod.Parameters.Add(parameter);

                }
            typeDeclaration.AddChild(newMethod);
            return newMethod;
        }
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                if (methodDeclaration.Name.ToLower().Equals("main") && !methodDeclaration.Modifier.HasFlag(Modifiers.Constructors))
                {
                    if (!methodDeclaration.IsExtensionMethod && !methodDeclaration.Modifier.HasFlag(Modifiers.Abstract))
                    {
                        if (methodDeclaration.Parameters.Count==1)
                        {
                            ParameterDeclarationExpression param = methodDeclaration.Parameters[0];

                            if(param.ParameterName.Equals("args") && param.TypeReference.ToString().Equals("System.String[]"))
                            {
                                //now check if body uses argsparam
                                //This is waaaaay to naive....
                                if(methodDeclaration.Body.ToString().Contains("args"))
                                {
                                    UnlockWith(methodDeclaration);
                                }

                            }
                        }
                    }
                }

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
		public override void GenerateCode(List<AbstractNode> nodes, IList items)
		{
			TypeReference stringReference = new TypeReference("System.String");
			MethodDeclaration method = new MethodDeclaration("ToString",
			                                                 Modifiers.Public | Modifiers.Override,
			                                                 stringReference,
			                                                 null, null);
			method.Body = new BlockStatement();
			Expression target = new FieldReferenceExpression(new TypeReferenceExpression(stringReference),
			                                                 "Format");
			InvocationExpression methodCall = new InvocationExpression(target);
			StringBuilder formatString = new StringBuilder();
			formatString.Append('[');
			formatString.Append(currentClass.Name);
			for (int i = 0; i < items.Count; i++) {
				formatString.Append(' ');
				formatString.Append(codeGen.GetPropertyName(((FieldWrapper)items[i]).Field.Name));
				formatString.Append("={");
				formatString.Append(i);
				formatString.Append('}');
			}
			formatString.Append(']');
			methodCall.Arguments.Add(new PrimitiveExpression(formatString.ToString(), formatString.ToString()));
			foreach (FieldWrapper w in items) {
				methodCall.Arguments.Add(new FieldReferenceExpression(new ThisReferenceExpression(), w.Field.Name));
			}
			method.Body.AddChild(new ReturnStatement(methodCall));
			nodes.Add(method);
		}
		public object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
		{
			B.Method m = new B.Method(GetLexicalInfo(methodDeclaration));
			m.Name = methodDeclaration.Name;
			m.Modifiers = ConvertModifier(methodDeclaration, B.TypeMemberModifiers.Private);
			ConvertAttributes(methodDeclaration.Attributes, m.Attributes);
			if (currentType != null) currentType.Members.Add(m);
			if (methodDeclaration.HandlesClause.Count > 0) {
				// TODO: Convert handles clauses to [Handles] attribute
				AddError(methodDeclaration, "Handles-clause is not supported.");
			}
			m.ExplicitInfo = ConvertInterfaceImplementations(methodDeclaration.InterfaceImplementations, methodDeclaration, m);
			if (methodDeclaration.Templates.Count > 0) {
				AddError(methodDeclaration, "Declaring generic methods is not supported.");
			}
			ConvertParameters(methodDeclaration.Parameters, m.Parameters);
			m.EndSourceLocation = GetEndLocation((INode)methodDeclaration.Body ?? methodDeclaration);
			m.ReturnType = ConvertTypeReference(methodDeclaration.TypeReference);
			m.Body = ConvertMethodBlock(methodDeclaration.Body);
			if (m.Name == "Main" && m.IsStatic && m.Parameters.Count <= 1 &&
			    (methodDeclaration.TypeReference.Type == "System.Void" || methodDeclaration.TypeReference.Type == "System.Int32"))
			{
				entryPointMethod = m;
			}
			return m;
		}
Exemplo n.º 13
0
 public override object TrackedVisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
 {
     TypeDeclaration typeDeclaration = (TypeDeclaration) methodDeclaration.Parent;
     if (methodDeclaration.Name.Length > 3)
     {
         if (IsAccessor(methodDeclaration, fields)
             || IsInterfaceOrAbstract(typeDeclaration) && ImplementInheritors(typeDeclaration, methodDeclaration)
             || ImplementSiblings(typeDeclaration, methodDeclaration))
         {
             string name = GetPropertyName(methodDeclaration);
             TypeReference typeReference = GetAccessorTypeReference(methodDeclaration);
             IList properties = AstUtil.GetChildrenWithType(typeDeclaration, typeof(PropertyDeclaration));
             PropertyDeclaration propertyDeclaration = GetProperty(properties, name, methodDeclaration.Modifier, typeReference);
             if (methodDeclaration.Name.StartsWith("set"))
                 AddSetSection(propertyDeclaration, methodDeclaration, fields);
             else if (methodDeclaration.Name.StartsWith("get"))
                 AddGetSection(propertyDeclaration, methodDeclaration, fields);
             AddToReferences(typeDeclaration, methodDeclaration.Name, propertyDeclaration.Name);
             if (!HasProperty(properties, name))
                 ReplaceCurrentNode(propertyDeclaration);
             else
                 RemoveCurrentNode();
         }
     }
     return base.TrackedVisitMethodDeclaration(methodDeclaration, data);
 }
		public override object VisitMethodDeclaration(MethodDeclaration md, object data)
		{
			Push();
			object result = base.VisitMethodDeclaration(md, data);
			Pop();
			return result;
		}
        public override object TrackedVisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
        {
            TypeDeclaration typeDeclaration = (TypeDeclaration) methodDeclaration.Parent;
            CheckForOverriding(typeDeclaration, methodDeclaration);

            return null;
        }
        public IEnumerable<MethodDeclaration> FindCandidatesViaRefactoringPermutations(TargetInfo left, MethodDeclaration right)
        {
            right = right.DeepCopy();
            /*
             * Steps to change one to match the other.
             *      Get the lookup table for left.
             *      Get the lookup table for right.
             *      Loop through left, renaming the corresponding right var as you go (don't worry about collisions yet).
             * Compare.
             *
             * This is essentially a normalization of one to the other.
             */
            Dictionary<string, List<LocalLookupVariable>> left_table = left.GetLookupTableWithParams();
            Dictionary<string, List<LocalLookupVariable>> right_table = right.GetLookupTableWithParams();

            if (left_table.Keys.Count == right_table.Keys.Count)
            {
                IDictionary<string, string> renames = new Dictionary<string, string>();

                for (int i = 0; i < left_table.Count; i++)
                {
                    var left_var_name = left_table.Keys.ToArray()[i];
                    var right_var_name = right_table.Keys.ToArray()[i];

                    // current name => new name
                    renames.Add(right_var_name, left_var_name);
                }

                RenameLocalVariableRefactoring r = new RenameLocalVariableRefactoring(renames);
                right.AcceptVisitor(r, null);

                yield return right;
            }
        }
        public void Equals()
        {
            string program = TestUtil.TypeMemberParse("public string Sentence(string title , string text);");
            CompilationUnit cu = TestUtil.ParseProgram(program);

            NamespaceDeclaration ns = (NamespaceDeclaration) cu.Children[0];
            TypeDeclaration ty = (TypeDeclaration) ns.Children[0];
            MethodDeclaration pgMethod = (MethodDeclaration) ty.Children[0];
            ParameterDeclarationExpression p1 = new ParameterDeclarationExpression(new TypeReference("string"), "title");
            p1.TypeReference.RankSpecifier = new int[] {};
            ParameterDeclarationExpression p2 = new ParameterDeclarationExpression(new TypeReference("string"), "text");
            p2.TypeReference.RankSpecifier = new int[] {};
            List<ParameterDeclarationExpression> argList = new List<ParameterDeclarationExpression>();
            argList.Add(p1);
            argList.Add(p2);
            MethodDeclaration exMethod = new MethodDeclaration("Sentence",
                                                               Modifiers.Public,
                                                               new TypeReference("string"),
                                                               argList, null);

            Assert.IsTrue(Equals(exMethod, pgMethod));

            string program2 = TestUtil.TypeMemberParse("public string Sentence(string title , string[] text);");
            cu = TestUtil.ParseProgram(program2);

            ns = (NamespaceDeclaration) cu.Children[0];
            ty = (TypeDeclaration) ns.Children[0];
            pgMethod = (MethodDeclaration) ty.Children[0];
            Assert.IsFalse(Equals(exMethod, pgMethod));
        }
        public void HasReturnValue_HasNone()
        {
            var methodToTest = new MethodDeclaration();
            var victim = new TestableMethodTemplate(methodToTest, null);

            Assert.IsFalse(victim.HasReturnValue);
        }
Exemplo n.º 19
0
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                if (methodDeclaration.IsExtensionMethod)
                    UnlockWith(methodDeclaration);

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
        public bool Equals(MethodDeclaration firstMethod, MethodDeclaration secondMethod)
        {
            if (firstMethod.Name == secondMethod.Name)
            {
                if (firstMethod.Parameters.Count == secondMethod.Parameters.Count)
                {
                    int index = 0;
                    foreach (ParameterDeclarationExpression parameter in firstMethod.Parameters)
                    {
                        TypeReference parameterTypeReference = ((ParameterDeclarationExpression) secondMethod.Parameters[index]).TypeReference;
                        string firstMethodParam = parameter.TypeReference.Type;
                        if (firstMethodParam.IndexOf('.') != -1)
                            firstMethodParam = firstMethodParam.Substring(firstMethodParam.LastIndexOf('.') + 1);
                        string secondMethodParam = parameterTypeReference.Type;
                        if (secondMethodParam.IndexOf('.') != -1)
                            secondMethodParam = secondMethodParam.Substring(secondMethodParam.LastIndexOf('.') + 1);

                        if ((firstMethodParam == secondMethodParam || AreEqualTypes(parameter.TypeReference, parameterTypeReference)) &&
                            parameter.TypeReference.RankSpecifier.Length == parameterTypeReference.RankSpecifier.Length)
                            index++;
                        else
                            return false;
                    }
                    return true;
                }
            }
            return false;
        }
Exemplo n.º 21
0
 public override object TrackedVisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
 {
     if (ShouldStubMember(methodDeclaration.Name))
         return base.TrackedVisitMethodDeclaration(methodDeclaration, data);
     else
         return null;
 }
		public FindJumpInstructionsVisitor(MethodDeclaration method, ISelection selection)
		{
			this.method = method;
			this.selection = selection;
			this.labels = new List<LabelStatement>();
			this.cases = new List<CaseLabel>();
		}
        public int CountAllExtractedMethods(MethodDeclaration right, int targetChildCount)
        {
            List<INode> children = right.Body.Children;

            var windows = AstMatchHelper.OscillateWindows(children.Count);

            return ProcessChildren(right, children, windows, targetChildCount);
        }
Exemplo n.º 24
0
 public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
 {
     collectingUsedLabels = true;
     base.VisitMethodDeclaration(methodDeclaration, data);
     collectingUsedLabels = false;
     base.VisitMethodDeclaration(methodDeclaration, data);
     return null;
 }
        public IEnumerable<CloneDesc> GetAllPossibleExtractedMethods(MethodDeclaration right, int targetChildCount)
        {
            List<INode> children = right.Body.Children;

            var windows = AstMatchHelper.OscillateWindows(children.Count);

            return ProcessChildren(right, children, windows, targetChildCount);
        }
 public void GetTypeReference_Method()
 {
     var cut = AbstractMethodTemplate.CreateClassUnderTest();
     var method = new MethodDeclaration
         { Name = "DoStuff", TypeReference = AbstractMethodTemplate.StringTypeReference };
     var actual = Parent.RefactoryExtensions.GetTypeReference(method, cut);
     Assert.AreEqual(AbstractMethodTemplate.StringTypeReference, actual);
 }
 /// <summary>
 /// Shows that the other two parameters are not necessary to this object.  Exposed for testing.
 /// </summary>
 /// <param name="right"></param>
 /// <returns></returns>
 public IEnumerable<CloneDesc> FindCandidatesViaRefactoringPermutations(MethodDeclaration right)
 {
     var md = FindCandidates(right, -1);
     foreach (Holder h in md)
     {
         yield return new CloneDesc(h.md, Window.Null, new List<INode>());
     }
 }
        public void HasReturnValue_HasOne()
        {
            var methodToTest = new MethodDeclaration();
            var retval = new TypeReference("string", new[] { 0 });
            methodToTest.TypeReference = retval;
            var victim = new TestableMethodTemplate(methodToTest, null);

            Assert.IsTrue(victim.HasReturnValue);
        }
        public void HasReturnValue_HasVoid()
        {
            var methodToTest = new MethodDeclaration();
            var retval = new TypeReference("void");
            methodToTest.TypeReference = retval;
            var victim = new TestableMethodTemplate(methodToTest, null);

            Assert.IsFalse(victim.HasReturnValue);
        }
 public bool Contains(IList methodsList, MethodDeclaration method)
 {
     foreach (MethodDeclaration methodDeclaration in methodsList)
     {
         if (Equals(methodDeclaration, method))
             return true;
     }
     return false;
 }
Exemplo n.º 31
0
		public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
		{
			if ((methodDeclaration.Body.StartLocation < new Location(startColumn + 1, startLine + 1)) &&
			    (methodDeclaration.Body.EndLocation > new Location(endColumn + 1, endLine + 1))) {
				this.member = methodDeclaration;
			}
			
			return base.VisitMethodDeclaration(methodDeclaration, data);
		}
        public override object VisitMethodDeclaration(AST.MethodDeclaration methodDeclaration, object data)
        {
            DomRegion    region       = GetRegion(methodDeclaration.StartLocation, methodDeclaration.EndLocation);
            DomRegion    bodyRegion   = GetRegion(methodDeclaration.EndLocation, methodDeclaration.Body != null ? methodDeclaration.Body.EndLocation : RefParser.Location.Empty);
            DefaultClass currentClass = GetCurrentClass();

            DefaultMethod method = new DefaultMethod(methodDeclaration.Name, null, ConvertModifier(methodDeclaration.Modifier), region, bodyRegion, currentClass);

            method.Documentation = GetDocumentation(region.BeginLine, methodDeclaration.Attributes);
            ConvertTemplates(methodDeclaration.Templates, method);
            method.ReturnType = CreateReturnType(methodDeclaration.TypeReference, method, TypeVisitor.ReturnTypeOptions.None);
            ConvertAttributes(methodDeclaration, method);
            method.IsExtensionMethod = methodDeclaration.IsExtensionMethod ||
                                       method.Attributes.Any(att => att.AttributeType != null && att.AttributeType.FullyQualifiedName == "System.Runtime.CompilerServices.ExtensionAttribute");
            if (methodDeclaration.Parameters.Count > 0)
            {
                foreach (AST.ParameterDeclarationExpression par in methodDeclaration.Parameters)
                {
                    method.Parameters.Add(CreateParameter(par, method));
                }
            }
            else
            {
                method.Parameters = DefaultParameter.EmptyParameterList;
            }
            if (methodDeclaration.HandlesClause.Count > 0)
            {
                foreach (string handlesClause in methodDeclaration.HandlesClause)
                {
                    if (handlesClause.ToLowerInvariant().StartsWith("me."))
                    {
                        method.HandlesClauses.Add(handlesClause.Substring(3));
                    }
                    else if (handlesClause.ToLowerInvariant().StartsWith("mybase."))
                    {
                        method.HandlesClauses.Add(handlesClause.Substring(7));
                    }
                    else
                    {
                        method.HandlesClauses.Add(handlesClause);
                    }
                }
            }
            else
            {
                method.HandlesClauses = EmptyList <string> .Instance;
            }

            AddInterfaceImplementations(method, methodDeclaration);

            currentClass.Methods.Add(method);
            return(null);
        }
Exemplo n.º 33
0
 public override object VisitMethodDeclaration(NR.MethodDeclaration methodDeclaration, object data)
 {
     this.VisitParametrizedNode(methodDeclaration, false);
     return(base.VisitMethodDeclaration(methodDeclaration, data));
 }
Exemplo n.º 34
0
        internal void ExecuteIntroduceMethod(UnknownMethodResolveResult rr, Ast.Expression invocationExpr, ITextEditor editor, bool isNew, object result)
        {
            IClass targetClass = IsEqualClass(rr.CallingClass, rr.Target.GetUnderlyingClass()) ? rr.CallingClass
                                : rr.Target.GetUnderlyingClass();

            CodeGenerator gen      = targetClass.ProjectContent.Language.CodeGenerator;
            IAmbience     ambience = targetClass.ProjectContent.Language.GetAmbience();

            ClassFinder finder = new ClassFinder(rr.CallingMember);

            ModifierEnum modifiers = ModifierEnum.None;

            bool isExtension = !targetClass.IsUserCode();

            if (IsEqualClass(rr.CallingClass, targetClass))
            {
                if (rr.CallingMember != null)
                {
                    modifiers |= (rr.CallingMember.Modifiers & ModifierEnum.Static);
                }
            }
            else
            {
                if (isExtension)
                {
                    if (isNew)
                    {
                        targetClass = rr.CallingClass;
                    }
                    else
                    {
                        targetClass = result as IClass;
                    }
                }
                // exclude in Unit Test mode
                if (WorkbenchSingleton.Workbench != null)
                {
                    editor = (FileService.OpenFile(targetClass.CompilationUnit.FileName) as ITextEditorProvider).TextEditor;
                }
                if (targetClass.ClassType != ClassType.Interface)
                {
                    modifiers |= ModifierEnum.Public;
                }
                if (rr.IsStaticContext)
                {
                    modifiers |= ModifierEnum.Static;
                }
            }

            NRefactoryResolver resolver = Extensions.CreateResolverForContext(targetClass.ProjectContent.Language, editor);

            IReturnType type = resolver.GetExpectedTypeFromContext(invocationExpr);

            Ast.TypeReference typeRef = CodeGenerator.ConvertType(type, finder);

            if (typeRef.IsNull)
            {
                if (invocationExpr.Parent is Ast.ExpressionStatement)
                {
                    typeRef = new Ast.TypeReference("void", true);
                }
                else
                {
                    typeRef = new Ast.TypeReference("object", true);
                }
            }

            Ast.MethodDeclaration method = new Ast.MethodDeclaration {
                Name          = rr.CallName,
                Modifier      = CodeGenerator.ConvertModifier(modifiers, finder),
                TypeReference = typeRef,
                Parameters    = CreateParameters(rr, finder, invocationExpr as Ast.InvocationExpression).ToList(),
            };

            if (targetClass.ClassType != ClassType.Interface)
            {
                method.Body = CodeGenerator.CreateNotImplementedBlock();
            }

            RefactoringDocumentAdapter documentWrapper = new RefactoringDocumentAdapter(editor.Document);

            if (isExtension)
            {
                method.Parameters.Insert(0, new Ast.ParameterDeclarationExpression(CodeGenerator.ConvertType(rr.Target, finder), "thisInstance"));
                method.IsExtensionMethod = true;
                method.Modifier         |= Ast.Modifiers.Static;
            }

            if (isNew)
            {
                Ast.TypeDeclaration newType = new Ast.TypeDeclaration(isExtension ? Ast.Modifiers.Static : Ast.Modifiers.None, null);
                newType.Name = result as string;
                newType.AddChild(method);
                gen.InsertCodeAfter(targetClass, documentWrapper, newType);
            }
            else
            {
                if (IsEqualClass(rr.CallingClass, targetClass))
                {
                    gen.InsertCodeAfter(rr.CallingMember, documentWrapper, method);
                }
                else
                {
                    gen.InsertCodeAtEnd(targetClass.BodyRegion, documentWrapper, method);
                }
            }

            if (targetClass.ClassType == ClassType.Interface)
            {
                return;
            }

            ParseInformation info = ParserService.ParseFile(targetClass.CompilationUnit.FileName);

            if (info != null)
            {
                IMember newMember;

                if (isNew)
                {
                    targetClass = info.CompilationUnit.Classes.FirstOrDefault(c => c.DotNetName == c.Namespace + "." + (result as string));
                }
                else
                {
                    targetClass = info.CompilationUnit.Classes.Flatten(c => c.InnerClasses).FirstOrDefault(c => c.DotNetName == targetClass.DotNetName);
                }

                if (targetClass == null)
                {
                    return;
                }

                if (IsEqualClass(rr.CallingClass, targetClass))
                {
                    newMember = targetClass.GetInnermostMember(editor.Caret.Line, editor.Caret.Column);
                    newMember = targetClass.AllMembers
                                .OrderBy(m => m.BodyRegion.BeginLine)
                                .ThenBy(m2 => m2.BodyRegion.BeginColumn)
                                .First(m3 => m3.BodyRegion.BeginLine > newMember.BodyRegion.BeginLine);
                }
                else
                {
                    newMember = targetClass.Methods.Last();
                }

                IDocumentLine line         = editor.Document.GetLine(newMember.BodyRegion.BeginLine + 2);
                int           indentLength = DocumentUtilitites.GetWhitespaceAfter(editor.Document, line.Offset).Length;
                editor.Select(line.Offset + indentLength, "throw new NotImplementedException();".Length);
            }
        }
 //DC
 public void mapMethod(NRefactoryAST.MethodDeclaration methodDeclaration, IMethod iMethod)
 {
     MethodDeclarationToIMethod.Add(methodDeclaration, iMethod);
     IMethodToMethodDeclaration.Add(iMethod, methodDeclaration);
 }