public override object VisitOperatorDeclaration (ICSharpCode.NRefactory.Ast.OperatorDeclaration operatorDeclaration, object data)
			{
				DomMethod method = new DomMethod ();
				method.Name = GetOperatorName (operatorDeclaration);
				method.Documentation = RetrieveDocumentation (operatorDeclaration.StartLocation.Line);
				method.Location = ConvertLocation (operatorDeclaration.StartLocation);
				method.BodyRegion = ConvertRegion (operatorDeclaration.EndLocation, operatorDeclaration.Body != null ? operatorDeclaration.Body.EndLocation : new ICSharpCode.NRefactory.Location (-1, -1));
				method.Modifiers = ConvertModifiers (operatorDeclaration.Modifier) | Modifiers.SpecialName;
				if (operatorDeclaration.IsExtensionMethod)
					method.MethodModifier |= MethodModifier.IsExtension;
				method.ReturnType = ConvertReturnType (operatorDeclaration.TypeReference);
				AddAttributes (method, operatorDeclaration.Attributes);
				method.Add (ConvertParameterList (method, operatorDeclaration.Parameters));
				AddExplicitInterfaces (method, operatorDeclaration.InterfaceImplementations);

				if (operatorDeclaration.Templates != null && operatorDeclaration.Templates.Count > 0) {
					foreach (ICSharpCode.NRefactory.Ast.TemplateDefinition td in operatorDeclaration.Templates) {
						method.AddTypeParameter (ConvertTemplateDefinition (td));
					}
				}
				method.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (method);

				return null;
			}
Exemple #2
0
        public void ExtensionMethodPreserveParameterTest()
        {
            // build "T MyMethod<T, S> (T a, S b)"
            DomMethod method = new DomMethod();

            method.Name       = "MyMethod";
            method.ReturnType = new DomReturnType("T");
            method.AddTypeParameter(new TypeParameter("T"));
            method.AddTypeParameter(new TypeParameter("S"));

            method.Add(new DomParameter(method, "a", new DomReturnType("T")));
            method.Add(new DomParameter(method, "b", new DomReturnType("S")));

            // extend method
            List <IReturnType> genArgs = new List <IReturnType> ();
            List <IReturnType> args    = new List <IReturnType> ();
            DomType            extType = new DomType("MyType");

            ExtensionMethod extMethod = new ExtensionMethod(extType, method, genArgs, args);

            // check for MyType MyMethod<S> (S b)
            Assert.AreEqual("MyType", extMethod.ReturnType.FullName);
            Assert.AreEqual("S", extMethod.Parameters[0].ReturnType.FullName);
            Assert.AreEqual(1, extMethod.TypeParameters.Count);
            Assert.AreEqual("S", extMethod.TypeParameters[0].Name);
        }
Exemple #3
0
		public void InstantiatedMethodByParameterTest ()
		{
			// build "T MyMethod<T> (T[] a)"
			DomMethod method = new DomMethod ();
			method.Name = "MyMethod";
			method.ReturnType = new DomReturnType ("T");
			method.AddTypeParameter (new TypeParameter ("T"));
			DomReturnType returnType = new DomReturnType ("T");
			returnType.ArrayDimensions = 1;
			method.Add (new DomParameter (method, "a", returnType));
			
			// give int[] as param type.
			List<IReturnType> genArgs = new List<IReturnType> ();
			List<IReturnType> args    = new List<IReturnType> ();
			returnType = new DomReturnType (DomReturnType.Int32.FullName);
			returnType.ArrayDimensions = 1;
			args.Add (returnType);
			
			IMethod instMethod = DomMethod.CreateInstantiatedGenericMethod (method, genArgs, args);
			
			// check (note that return type should be int and not int[])
			Assert.AreEqual (DomReturnType.Int32.FullName, instMethod.ReturnType.FullName);
			Assert.AreEqual (0, instMethod.ReturnType.ArrayDimensions);
			Assert.AreEqual (DomReturnType.Int32.FullName, instMethod.Parameters[0].ReturnType.FullName);
		}
Exemple #4
0
        public void InstantiatedMethodByParameterTest()
        {
            // build "T MyMethod<T> (T[] a)"
            DomMethod method = new DomMethod();

            method.Name       = "MyMethod";
            method.ReturnType = new DomReturnType("T");
            method.AddTypeParameter(new TypeParameter("T"));
            DomReturnType returnType = new DomReturnType("T");

            returnType.ArrayDimensions = 1;
            method.Add(new DomParameter(method, "a", returnType));

            // give int[] as param type.
            List <IReturnType> genArgs = new List <IReturnType> ();
            List <IReturnType> args    = new List <IReturnType> ();

            returnType = new DomReturnType(DomReturnType.Int32.FullName);
            returnType.ArrayDimensions = 1;
            args.Add(returnType);

            IMethod instMethod = DomMethod.CreateInstantiatedGenericMethod(method, genArgs, args);

            // check (note that return type should be int and not int[])
            Assert.AreEqual(DomReturnType.Int32.FullName, instMethod.ReturnType.FullName);
            Assert.AreEqual(0, instMethod.ReturnType.ArrayDimensions);
            Assert.AreEqual(DomReturnType.Int32.FullName, instMethod.Parameters[0].ReturnType.FullName);
        }
        public static DomMethod ReadMethod(BinaryReader reader, INameDecoder nameTable)
        {
            DomMethod result = new DomMethod();

            ReadMemberInformation(reader, nameTable, result);
            uint explicitInterfaces = ReadUInt(reader, 500);

            while (explicitInterfaces-- > 0)
            {
                result.AddExplicitInterface(ReadReturnType(reader, nameTable));
            }

            result.BodyRegion     = ReadRegion(reader, nameTable);
            result.ReturnType     = ReadReturnType(reader, nameTable);
            result.MethodModifier = (MethodModifier)reader.ReadInt32();

            uint arguments = ReadUInt(reader, 5000);

            while (arguments-- > 0)
            {
                result.Add(ReadParameter(reader, nameTable));
            }
            arguments = ReadUInt(reader, 500);
            while (arguments-- > 0)
            {
                result.AddTypeParameter(ReadTypeParameter(reader, nameTable));
            }
            return(result);
        }
Exemple #6
0
        public void InstantiatedMethodByArgumentTest_Complex()
        {
            // build "T MyMethod<T,S> (S b, KeyValuePair<S, T> a)"
            DomMethod method = new DomMethod();

            method.Name       = "MyMethod";
            method.ReturnType = new DomReturnType("T");
            method.AddTypeParameter(new TypeParameter("T"));
            method.AddTypeParameter(new TypeParameter("S"));
            method.Add(new DomParameter(method, "b", new DomReturnType("S")));

            DomReturnType returnType = new DomReturnType("KeyValuePair");

            returnType.AddTypeParameter(new DomReturnType("T"));
            returnType.AddTypeParameter(new DomReturnType("S"));
            method.Add(new DomParameter(method, "a", returnType));

            // give int, object as param type
            List <IReturnType> genArgs = new List <IReturnType> ();
            List <IReturnType> args    = new List <IReturnType> ();

            genArgs.Add(DomReturnType.Int32);
            genArgs.Add(DomReturnType.Object);

            IMethod instMethod = DomMethod.CreateInstantiatedGenericMethod(method, genArgs, args);

            // check
            Assert.AreEqual(DomReturnType.Int32.FullName, instMethod.ReturnType.FullName);
            Assert.AreEqual(DomReturnType.Object.FullName, instMethod.Parameters[0].ReturnType.FullName);

            Assert.AreEqual(DomReturnType.Int32.FullName, instMethod.Parameters[1].ReturnType.GenericArguments[0].FullName);
            Assert.AreEqual(DomReturnType.Object.FullName, instMethod.Parameters[1].ReturnType.GenericArguments[1].FullName);
        }
Exemple #7
0
        IMethod ConstructMethodFromInvocation(RefactoringOptions options)
        {
            var resolver = options.GetResolver();
            var data     = options.GetTextEditorData();

            DomMethod result = new DomMethod(methodName, modifiers, MethodModifier.None, DomLocation.Empty, DomRegion.Empty, returnType);

            result.DeclaringType = new DomType("GeneratedType")
            {
                ClassType = declaringType.ClassType
            };
            int i = 1;

            foreach (var curArg in invocation.Arguments)
            {
                var          argument = curArg;
                DomParameter arg      = new DomParameter();
                if (argument is DirectionExpression)
                {
                    var de = (DirectionExpression)argument;
                    arg.ParameterModifiers = de.FieldDirection == FieldDirection.Out ? ParameterModifiers.Out : ParameterModifiers.Ref;
                    argument = de.Expression;
                }

                string argExpression = data.GetTextBetween(argument.StartLocation.Line, argument.StartLocation.Column, argument.EndLocation.Line, argument.EndLocation.Column);
                var    resolveResult = resolver.Resolve(new ExpressionResult(argExpression), resolvePosition);

                if (argument is MemberReferenceExpression)
                {
                    arg.Name = ((MemberReferenceExpression)argument).MemberName;
                }
                else if (argument is IdentifierExpression)
                {
                    arg.Name = ((IdentifierExpression)argument).Identifier;
                    int idx = arg.Name.LastIndexOf('.');
                    if (idx >= 0)
                    {
                        arg.Name = arg.Name.Substring(idx + 1);
                    }
                }
                else
                {
                    arg.Name = "par" + i++;
                }

                arg.Name = char.ToLower(arg.Name[0]) + arg.Name.Substring(1);

                if (resolveResult != null && resolveResult.ResolvedType != null && !string.IsNullOrEmpty(resolveResult.ResolvedType.FullName))
                {
                    arg.ReturnType = resolveResult.ResolvedType;
                }
                else
                {
                    arg.ReturnType = DomReturnType.Object;
                }

                result.Add(arg);
            }
            return(result);
        }
			public override object VisitEventDeclaration (ICSharpCode.NRefactory.Ast.EventDeclaration eventDeclaration, object data)
			{
				DomEvent evt = new DomEvent ();
				evt.Name = eventDeclaration.Name;
				evt.Documentation = RetrieveDocumentation (eventDeclaration.StartLocation.Line);
				evt.Location = ConvertLocation (eventDeclaration.StartLocation);
				evt.Modifiers = ConvertModifiers (eventDeclaration.Modifier);
				evt.ReturnType = ConvertReturnType (eventDeclaration.TypeReference);
				evt.BodyRegion = ConvertRegion (eventDeclaration.BodyStart, eventDeclaration.BodyEnd);
				if (eventDeclaration.AddRegion != null && !eventDeclaration.AddRegion.IsNull) {
					DomMethod addMethod = new DomMethod ();
					addMethod.Name = "add";
					addMethod.BodyRegion = ConvertRegion (eventDeclaration.AddRegion.StartLocation, eventDeclaration.AddRegion.EndLocation);
					evt.AddMethod = addMethod;
				}
				if (eventDeclaration.RemoveRegion != null && !eventDeclaration.RemoveRegion.IsNull) {
					DomMethod removeMethod = new DomMethod ();
					removeMethod.Name = "remove";
					removeMethod.BodyRegion = ConvertRegion (eventDeclaration.RemoveRegion.StartLocation, eventDeclaration.RemoveRegion.EndLocation);
					evt.RemoveMethod = removeMethod;
				}
				AddAttributes (evt, eventDeclaration.Attributes);
				AddExplicitInterfaces (evt, eventDeclaration.InterfaceImplementations);
				evt.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (evt);
				return null;
			}
        void BuildFunction(XmlElement element)
        {
            var compUnit = this.CompilationUnit as PythonCompilationUnit;

            Console.WriteLine("Function({0})", element.GetAttribute("name"));

            var name = element.GetAttribute("name");
            var mod  = Modifiers.None;

            if (name.StartsWith("_"))
            {
                mod |= Modifiers.Private;
            }
            else
            {
                mod |= Modifiers.Public;
            }

            var start  = GetDomLocation(element);
            var region = GetDomRegion(element);
            var func   = new DomMethod(name, mod, MethodModifier.None,
                                       start, region);

            compUnit.Add(func);
        }
Exemple #10
0
        public void InstantiatedMethodByArgumentTestComplex2()
        {
            // build "T MyMethod<T> (MyType<T> a)"
            DomMethod method = new DomMethod();

            method.Name       = "MyMethod";
            method.ReturnType = new DomReturnType("T");
            method.AddTypeParameter(new TypeParameter("T"));

            DomReturnType returnType = new DomReturnType("MyType");

            returnType.AddTypeParameter(new DomReturnType("T"));
            method.Add(new DomParameter(method, "a", returnType));

            // give int as param type
            List <IReturnType> genArgs = new List <IReturnType> ();
            List <IReturnType> args    = new List <IReturnType> ();

            returnType = new DomReturnType("MyType");
            returnType.AddTypeParameter(DomReturnType.Int32);
            args.Add(returnType);
            IMethod instMethod = DomMethod.CreateInstantiatedGenericMethod(method, genArgs, args);

            // check
            Assert.AreEqual(DomReturnType.Int32.FullName, instMethod.ReturnType.FullName);
        }
Exemple #11
0
        //TODO: handle generics
        public static IMethod CodeDomToMDDomMethod(CodeMemberMethod method)
        {
            DomMethod meth = new DomMethod();

            meth.Name       = method.Name;
            meth.ReturnType = new DomReturnType(method.ReturnType.BaseType);
            meth.Modifiers  = CodeDomModifiersToMDDom(method.Attributes);

            foreach (CodeParameterDeclarationExpression dec in method.Parameters)
            {
                DomParameter par = new DomParameter(meth, dec.Name, new DomReturnType(dec.Type.BaseType));
                if (dec.Direction == FieldDirection.Ref)
                {
                    par.ParameterModifiers &= ParameterModifiers.Ref;
                }
                else if (dec.Direction == FieldDirection.Out)
                {
                    par.ParameterModifiers &= ParameterModifiers.Out;
                }
                else
                {
                    par.ParameterModifiers &= ParameterModifiers.In;
                }
                meth.Add(par);
            }

            return(meth);
        }
Exemple #12
0
        // used for constructor completion
        public NRefactoryParameterDataProvider(MonoDevelop.Ide.Gui.TextEditor editor, NRefactoryResolver resolver, IType type)
        {
            this.editor = editor;

            if (type != null)
            {
                if (type.ClassType == ClassType.Delegate)
                {
                    IMethod invokeMethod = ExtractInvokeMethod(type);
                    if (type is InstantiatedType)
                    {
                        this.delegateName = ((InstantiatedType)type).UninstantiatedType.Name;
                    }
                    else
                    {
                        this.delegateName = type.Name;
                    }
                    if (invokeMethod != null)
                    {
                        methods.Add(invokeMethod);
                    }
                    else
                    {
                        // no invoke method -> tried to create an abstract delegate
                    }
                    return;
                }
                bool             includeProtected = DomType.IncludeProtected(resolver.Dom, type, resolver.CallingType);
                bool             constructorFound = false;
                HashSet <string> alreadyAdded     = new HashSet <string> ();
                foreach (IMethod method in type.Methods)
                {
                    constructorFound |= method.IsConstructor;
                    string str = ambience.GetString(method, OutputFlags.IncludeParameters);
                    if (alreadyAdded.Contains(str))
                    {
                        continue;
                    }
                    alreadyAdded.Add(str);
                    if ((method.IsConstructor && method.IsAccessibleFrom(resolver.Dom, type, resolver.CallingMember, includeProtected)))
                    {
                        methods.Add(method);
                    }
                }
                // No constructor - generating default
                if (!constructorFound && (type.TypeModifier & TypeModifier.HasOnlyHiddenConstructors) != TypeModifier.HasOnlyHiddenConstructors)
                {
                    DomMethod defaultConstructor = new DomMethod();
                    defaultConstructor.MethodModifier = MethodModifier.IsConstructor;
                    defaultConstructor.DeclaringType  = type;
                    methods.Add(defaultConstructor);
                }
            }
        }
        /// <summary>
        /// Create an IMember from a LanguageItem,
        /// using the source document to locate declaration bounds.
        /// </summary>
        /// <param name="pi">
        /// A <see cref="ProjectInformation"/> for the current project.
        /// </param>
        /// <param name="item">
        /// A <see cref="LanguageItem"/>: The item to convert.
        /// </param>
        /// <param name="contentLines">
        /// A <see cref="System.String[]"/>: The document in which item is defined.
        /// </param>
        static IMember LanguageItemToIMember(ProjectInformation pi, LanguageItem item, string[] contentLines)
        {
            if (item is Class || item is Structure)
            {
                DomType klass = new DomType(new CompilationUnit(item.File), ClassType.Class, item.Name, new DomLocation((int)item.Line, 1), string.Empty, new DomRegion((int)item.Line + 1, FindFunctionEnd(contentLines, (int)item.Line - 1) + 2), new List <IMember> ());

                foreach (LanguageItem li in pi.AllItems())
                {
                    if (klass.Equals(li.Parent) && FilePath.Equals(li.File, item.File))
                    {
                        klass.Add(LanguageItemToIMember(pi, li, contentLines));
                    }
                }
                return(klass);
            }
            if (item is Enumeration)
            {
                return(new DomType(new CompilationUnit(item.File), ClassType.Enum, item.Name, new DomLocation((int)item.Line, 1), string.Empty, new DomRegion((int)item.Line + 1, (int)item.Line + 1), new List <IMember> ()));
            }
            if (item is Function)
            {
                DomMethod         method   = new DomMethod(item.Name, Modifiers.None, MethodModifier.None, new DomLocation((int)item.Line, 1), new DomRegion((int)item.Line + 1, FindFunctionEnd(contentLines, (int)item.Line - 1) + 2), new DomReturnType());
                Function          function = (Function)item;
                Match             match;
                bool              abort      = false;
                List <IParameter> parameters = new List <IParameter> ();

                foreach (string parameter in function.Parameters)
                {
                    match = paramExpression.Match(parameter);
                    if (null == match)
                    {
                        abort = true;
                        break;
                    }
                    DomParameter p = (new DomParameter(method, match.Groups["name"].Value,
                                                       new DomReturnType(string.Format("{0}{1}{2}", match.Groups["type"].Value, match.Groups["subtype"].Value, match.Groups["array"].Value))));
                    parameters.Add(p);
                }
                if (!abort)
                {
                    method.Add(parameters);
                }
                return(method);
            }
            if (item is Member)
            {
                return(new DomField(item.Name, Modifiers.None, new DomLocation((int)item.Line, 1), new DomReturnType()));
            }
            return(null);
        }
			public override object VisitDestructorDeclaration (ICSharpCode.NRefactory.Ast.DestructorDeclaration destructorDeclaration, object data)
			{
				DomMethod destructor = new DomMethod ();
				destructor.Name = ".dtor";
				destructor.Documentation = RetrieveDocumentation (destructorDeclaration.StartLocation.Line);
				destructor.Location = ConvertLocation (destructorDeclaration.StartLocation);
				destructor.BodyRegion = ConvertRegion (destructorDeclaration.EndLocation, destructorDeclaration.Body != null ? destructorDeclaration.Body.EndLocation : new ICSharpCode.NRefactory.Location (-1, -1));
				destructor.Modifiers = ConvertModifiers (destructorDeclaration.Modifier);
				AddAttributes (destructor, destructorDeclaration.Attributes);
				destructor.MethodModifier |= MethodModifier.IsFinalizer;

				destructor.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (destructor);

				return null;
			}
			public override object VisitConstructorDeclaration (ICSharpCode.NRefactory.Ast.ConstructorDeclaration constructorDeclaration, object data)
			{
				DomMethod constructor = new DomMethod ();
				constructor.Documentation = RetrieveDocumentation (constructorDeclaration.StartLocation.Line);
				constructor.Name = ".ctor";
				constructor.MethodModifier |= MethodModifier.IsConstructor;
				constructor.Location = ConvertLocation (constructorDeclaration.StartLocation);
				constructor.BodyRegion = ConvertRegion (constructorDeclaration.EndLocation, constructorDeclaration.Body != null ? constructorDeclaration.Body.EndLocation : new ICSharpCode.NRefactory.Location (-1, -1));
				constructor.Modifiers = ConvertModifiers (constructorDeclaration.Modifier);
				AddAttributes (constructor, constructorDeclaration.Attributes);
				constructor.Add (ConvertParameterList (constructor, constructorDeclaration.Parameters));

				constructor.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (constructor);
				return null;
			}
Exemple #16
0
        IMethod ConstructMethodFromDelegate(RefactoringOptions options)
        {
            DomMethod result = new DomMethod(methodName, modifiers, MethodModifier.None, DomLocation.Empty, DomRegion.Empty, returnType);

            result.DeclaringType = new DomType("GeneratedType")
            {
                ClassType = declaringType.ClassType
            };
            IMethod invocation = (IMethod)delegateType.SearchMember("Invoke", true).First();

            foreach (var arg in invocation.Parameters)
            {
                result.Add(arg);
            }
            result.ReturnType = invocation.ReturnType;
            return(result);
        }
Exemple #17
0
        // if a member is a member of an instantiated class search for the 'real' uninstantiated member
        // ex. List<string> a; a.Count<-;  should search for List<T>.Count instead of List<string>.Count
        static IMember GetUnderlyingMember(IMember member)
        {
            if (member == null)
            {
                return(null);
            }

            if (member.DeclaringType is InstantiatedType && member.ReturnType != null)
            {
                IType uninstantiatedType = ((InstantiatedType)member.DeclaringType).UninstantiatedType;
                foreach (IMember realMember in uninstantiatedType.SearchMember(member.Name, true))
                {
                    if (realMember.ReturnType == null)
                    {
                        continue;
                    }
                    if (realMember.MemberType == member.MemberType)
                    {
                        switch (member.MemberType)
                        {
                        case MemberType.Method:
                            if (((IMethod)member).TypeParameters.Count != ((IMethod)realMember).TypeParameters.Count)
                            {
                                continue;
                            }
                            if (!DomMethod.ParameterListEquals(((IMethod)member).Parameters, ((IMethod)realMember).Parameters))
                            {
                                continue;
                            }
                            break;

                        case MemberType.Property:
                            if (!DomMethod.ParameterListEquals(((IProperty)member).Parameters, ((IProperty)realMember).Parameters))
                            {
                                continue;
                            }
                            break;
                        }
                        return(realMember);
                    }
                }
            }
            return(member);
        }
Exemple #18
0
		public void InstantiatedMethodByArgumentTest ()
		{
			// build "T MyMethod<T> (T a)"
			DomMethod method = new DomMethod ();
			method.Name = "MyMethod";
			method.ReturnType = new DomReturnType ("T");
			method.AddTypeParameter (new TypeParameter ("T"));
			method.Add (new DomParameter (method, "a", new DomReturnType ("T")));
			
			// give int as param type
			List<IReturnType> genArgs = new List<IReturnType> ();
			List<IReturnType> args    = new List<IReturnType> ();
			args.Add (DomReturnType.Int32);
			IMethod instMethod = DomMethod.CreateInstantiatedGenericMethod (method, genArgs, args);
			
			// check 
			Assert.AreEqual (DomReturnType.Int32.FullName, instMethod.ReturnType.FullName);
			Assert.AreEqual (DomReturnType.Int32.FullName, instMethod.Parameters[0].ReturnType.FullName);
		}
Exemple #19
0
        IEnumerable <IMethod> BuildFunctions(IEnumerable <PythonFunction> functions)
        {
            if (functions == null)
            {
                yield break;
            }

            foreach (PythonFunction pyFunc in functions)
            {
                var domFunc = new DomMethod()
                {
                    Name          = pyFunc.Name,
                    Documentation = pyFunc.Documentation,
                    BodyRegion    = pyFunc.Region,
                    Location      = new DomLocation(pyFunc.Region.Start.Line - 1, 0),
                    ReturnType    = new DomReturnType()
                    {
                        Name      = pyFunc.Name,                         // FIXME: Get inferred type
                        Namespace = Module.FullName,
                    },
                };
                m_AllWrapped.Add(domFunc);

                foreach (PythonArgument pyArg in pyFunc.Arguments)
                {
                    var domArg = new DomParameter()
                    {
                        Name       = pyArg.Name,
                        ReturnType = new DomReturnType()
                        {
                            Name      = pyArg.Name,                             // FIXME: Get inferred type
                            Namespace = Module.FullName,
                        },
                    };
                    m_AllWrapped.Add(domArg);
                    domFunc.Add(domArg);
                }

                yield return(domFunc);
            }
        }
Exemple #20
0
        public void ReadWriteMethodTest()
        {
            DomMethod input = new DomMethod();

            input.Name           = "Test";
            input.MethodModifier = MethodModifier.IsConstructor;
            input.Add(new DomParameter(input, "par1", DomReturnType.Void));
            input.AddTypeParameter(new TypeParameter("T"));
            MemoryStream ms     = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(ms);

            DomPersistence.Write(writer, DefaultNameEncoder, input);
            byte[] bytes = ms.ToArray();

            DomMethod result = DomPersistence.ReadMethod(CreateReader(bytes), DefaultNameDecoder, null);

            Assert.AreEqual("Test", result.Name);
            Assert.AreEqual(true, result.IsConstructor);
            Assert.AreEqual("par1", result.Parameters [0].Name);
            Assert.AreEqual("Void", result.Parameters [0].ReturnType.Name);
            Assert.AreEqual(1, result.TypeParameters.Count);
            Assert.AreEqual("T", result.TypeParameters [0].Name);
        }
Exemple #21
0
        public void ExtensionMethodTest()
        {
            // build "T MyMethod<T, S> (this KeyValuePair<T, S> a, S b)"
            DomMethod method = new DomMethod();

            method.Name       = "MyMethod";
            method.ReturnType = new DomReturnType("T");
            method.AddTypeParameter(new TypeParameter("T"));
            method.AddTypeParameter(new TypeParameter("S"));

            DomReturnType returnType = new DomReturnType("KeyValuePair");

            returnType.AddTypeParameter(new DomReturnType("T"));
            returnType.AddTypeParameter(new DomReturnType("S"));
            method.Add(new DomParameter(method, "a", returnType));
            method.Add(new DomParameter(method, "b", new DomReturnType("S")));

            // Build extendet type KeyValuePair<int, object>
            DomType type = new DomType("KeyValuePair");

            type.AddTypeParameter(new TypeParameter("T"));
            type.AddTypeParameter(new TypeParameter("S"));
            IType extType = DomType.CreateInstantiatedGenericTypeInternal(type, new IReturnType[] { DomReturnType.Int32, DomReturnType.Object });

            Console.WriteLine(extType);

            // extend method
            List <IReturnType> genArgs = new List <IReturnType> ();
            List <IReturnType> args    = new List <IReturnType> ();

            ExtensionMethod extMethod = new ExtensionMethod(extType, method, genArgs, args);

            Console.WriteLine(extMethod);
            // check
            Assert.AreEqual(DomReturnType.Int32.FullName, extMethod.ReturnType.FullName);
            Assert.AreEqual(DomReturnType.Object.FullName, extMethod.Parameters[0].ReturnType.FullName);
        }
        static DomMethod GenerateMethodStub(RefactoringOptions options, ExtractMethodParameters param)
        {
            DomMethod result = new DomMethod();

            result.Name       = param.Name;
            result.ReturnType = param.ExpressionType ?? DomReturnType.Void;
            result.Modifiers  = param.Modifiers;
            if (!param.ReferencesMember)
            {
                result.Modifiers |= Modifiers.Static;
            }

            if (param.Parameters == null)
            {
                return(result);
            }
            foreach (var p in param.Parameters)
            {
                if (param.OneChangedVariable && p.UsedAfterCutRegion && !p.UsedInCutRegion)
                {
                    continue;
                }
                var newParameter = new DomParameter();
                newParameter.Name       = p.Name;
                newParameter.ReturnType = p.ReturnType;

                if (!param.OneChangedVariable)
                {
                    if (!p.IsDefinedInsideCutRegion && p.IsChangedInsideCutRegion)
                    {
                        newParameter.ParameterModifiers = p.UsedBeforeCutRegion ? ParameterModifiers.Ref : ParameterModifiers.Out;
                    }
                }
                result.Add(newParameter);
            }
            return(result);
        }
Exemple #23
0
        /// Adds a signal handler to the class
        public void BindSignal(Stetic.Signal signal)
        {
            if (targetObject == null)
            {
                return;
            }

            IType cls = GetClass();

            if (cls == null)
            {
                return;
            }

            if (FindSignalHandler(cls, signal) != null)
            {
                return;
            }

            var met = new DomMethod()
            {
                Name       = signal.Handler,
                Modifiers  = Modifiers.Protected,
                ReturnType = new DomReturnType(signal.SignalDescriptor.HandlerReturnTypeName)
            };

            foreach (Stetic.ParameterDescriptor pinfo in signal.SignalDescriptor.HandlerParameters)
            {
                met.Add(new DomParameter()
                {
                    Name = pinfo.Name, ReturnType = new DomReturnType(pinfo.TypeName)
                });
            }

            CodeGenerationService.AddNewMember(cls, met);
        }
        public override ParsedDocument Parse(ProjectDom dom, string fileName, string content)
        {
            ParsedDocument     doc = new ParsedDocument(fileName);
            ProjectInformation pi  = ProjectInformationManager.Instance.Get((null == dom)? null: dom.Project);

            if (null == doc.CompilationUnit)
            {
                doc.CompilationUnit = new CompilationUnit(fileName);
            }
            CompilationUnit      cu       = (CompilationUnit)doc.CompilationUnit;
            int                  lastLine = 0;
            ICollection <Symbol> classes  = pi.GetClassesForFile(fileName);

            if (null == classes || 0 == classes.Count)
            {
                return(lastGood);
            }

            foreach (Symbol node in classes)
            {
                if (null == node)
                {
                    continue;
                }
                List <IMember> members = new List <IMember> ();
                lastLine = node.SourceReferences[0].LastLine;

                foreach (Symbol child in node.Children)
                {
                    if (1 > child.SourceReferences.Count ||
                        child.SourceReferences[0].File != node.SourceReferences[0].File)
                    {
                        continue;
                    }
                    lastLine = Math.Max(lastLine, child.SourceReferences[0].LastLine + 1);

                    switch (child.MemberType.ToLower())
                    {
                    case "class":
                        members.Add(new DomType(new CompilationUnit(fileName), ClassType.Class, child.Name, new DomLocation(child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion(child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List <IMember> ()));
                        break;

                    case "interface":
                        members.Add(new DomType(new CompilationUnit(fileName), ClassType.Interface, child.Name, new DomLocation(child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion(child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List <IMember> ()));
                        break;

                    case "delegate":
                        members.Add(new DomType(new CompilationUnit(fileName), ClassType.Delegate, child.Name, new DomLocation(child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion(child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List <IMember> ()));
                        break;

                    case "struct":
                        members.Add(new DomType(new CompilationUnit(fileName), ClassType.Struct, child.Name, new DomLocation(child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion(child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List <IMember> ()));
                        break;

                    case "enum":
                        members.Add(new DomType(new CompilationUnit(fileName), ClassType.Enum, child.Name, new DomLocation(child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion(child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List <IMember> ()));
                        break;

                    case "method":
                    case "creationmethod":
                    case "constructor":
                        DomMethod method = new DomMethod(child.Name, Modifiers.None, MethodModifier.None, new DomLocation(child.SourceReferences[0].FirstLine, 1), new DomRegion(child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new DomReturnType(child.ReturnType.TypeName));
                        foreach (DataType param in child.Parameters)
                        {
                            method.Add(new DomParameter(method, param.Name, new DomReturnType(param.TypeName)));
                        }
                        members.Add(method);
                        break;

                    case "property":
                        members.Add(new DomProperty(child.Name, Modifiers.None, new DomLocation(child.SourceReferences[0].FirstLine, 1), new DomRegion(child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new DomReturnType()));
                        break;

                    case "field":
                    case "constant":
                    case "errorcode":
                        members.Add(new DomField(child.Name, Modifiers.None, new DomLocation(child.SourceReferences[0].FirstLine, 1), new DomReturnType()));
                        break;

                    case "signal":
                        members.Add(new DomEvent(child.Name, Modifiers.None, new DomLocation(child.SourceReferences[0].FirstLine, 1), new DomReturnType()));
                        break;

                    default:
                        MonoDevelop.Core.LoggingService.LogDebug("ValaDocumentParser: Unsupported member type: {0}", child.MemberType);
                        break;
                    }            // Switch on node type
                }                // Collect members

                cu.Add(new DomType(new CompilationUnit(fileName), ClassType.Class, node.Name, new DomLocation(node.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion(node.SourceReferences[0].FirstLine, int.MaxValue, lastLine, int.MaxValue), members));
            }            // Add each class in file

            return(lastGood = doc);
        } // Parse
		//TODO: handle generics
		public static IMethod CodeDomToMDDomMethod (CodeMemberMethod method)
		{
			DomMethod meth = new DomMethod ();
			meth.Name = method.Name;
			meth.ReturnType = new DomReturnType (method.ReturnType.BaseType);
			meth.Modifiers = CodeDomModifiersToMDDom (method.Attributes);
			
			foreach (CodeParameterDeclarationExpression dec in method.Parameters) {
				DomParameter par = new DomParameter (meth, dec.Name, new DomReturnType (dec.Type.BaseType));
				if (dec.Direction == FieldDirection.Ref)
					par.ParameterModifiers &= ParameterModifiers.Ref;
				else if (dec.Direction == FieldDirection.Out)
					par.ParameterModifiers &= ParameterModifiers.Out;
				else
					par.ParameterModifiers &= ParameterModifiers.In;
				meth.Add (par);
			}
			
			return meth;
		}
			public override object VisitEventDeclaration (ICSharpCode.NRefactory.Ast.EventDeclaration eventDeclaration, object data)
			{
				DomEvent evt = new DomEvent ();
				evt.Name = eventDeclaration.Name;
				evt.Documentation = RetrieveDocumentation (eventDeclaration.StartLocation.Line);
				evt.Location = ConvertLocation (eventDeclaration.StartLocation);
				evt.Modifiers = ConvertModifiers (eventDeclaration.Modifier);
				evt.ReturnType = ConvertReturnType (eventDeclaration.TypeReference);
				evt.BodyRegion = ConvertRegion (eventDeclaration.BodyStart, eventDeclaration.BodyEnd);
				if (eventDeclaration.AddRegion != null && !eventDeclaration.AddRegion.IsNull) {
					DomMethod addMethod = new DomMethod ();
					addMethod.Name = "add";
					addMethod.BodyRegion = ConvertRegion (eventDeclaration.AddRegion.StartLocation, eventDeclaration.AddRegion.EndLocation);
					evt.AddMethod = addMethod;
				}
				if (eventDeclaration.RemoveRegion != null && !eventDeclaration.RemoveRegion.IsNull) {
					DomMethod removeMethod = new DomMethod ();
					removeMethod.Name = "remove";
					removeMethod.BodyRegion = ConvertRegion (eventDeclaration.RemoveRegion.StartLocation, eventDeclaration.RemoveRegion.EndLocation);
					evt.RemoveMethod = removeMethod;
				}
				AddAttributes (evt, eventDeclaration.Attributes);
				AddExplicitInterfaces (evt, eventDeclaration.InterfaceImplementations);
				evt.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (evt);
				return null;
			}
		IMethod ConstructMethodFromDelegate (RefactoringOptions options)
		{
			DomMethod result = new DomMethod (methodName, modifiers, MethodModifier.None, DomLocation.Empty, DomRegion.Empty, returnType);
			result.DeclaringType = new DomType ("GeneratedType") { ClassType = declaringType.ClassType };
			IMethod invocation = (IMethod)delegateType.SearchMember ("Invoke", true).First ();
			foreach (var arg in invocation.Parameters) {
				result.Add (arg);
			}
			result.ReturnType = invocation.ReturnType;
			return result;
		}
		void BuildFunction (XmlElement element)
		{
			var compUnit = this.CompilationUnit as PythonCompilationUnit;
			Console.WriteLine ("Function({0})", element.GetAttribute ("name"));

			var name = element.GetAttribute ("name");
			var mod = Modifiers.None;
			if (name.StartsWith ("_"))
				mod |= Modifiers.Private;
			else
				mod |= Modifiers.Public;

			var start = GetDomLocation (element);
			var region = GetDomRegion (element);
			var func = new DomMethod (name, mod, MethodModifier.None,
			                          start, region);

			compUnit.Add (func);
		}
			public override object VisitDestructorDeclaration (ICSharpCode.NRefactory.Ast.DestructorDeclaration destructorDeclaration, object data)
			{
				DomMethod destructor = new DomMethod ();
				destructor.Name = ".dtor";
				destructor.Documentation = RetrieveDocumentation (destructorDeclaration.StartLocation.Line);
				destructor.Location = ConvertLocation (destructorDeclaration.StartLocation);
				destructor.BodyRegion = ConvertRegion (destructorDeclaration.EndLocation, destructorDeclaration.Body != null ? destructorDeclaration.Body.EndLocation : new ICSharpCode.NRefactory.Location (-1, -1));
				destructor.Modifiers = ConvertModifiers (destructorDeclaration.Modifier);
				AddAttributes (destructor, destructorDeclaration.Attributes);
				destructor.MethodModifier |= MethodModifier.IsFinalizer;

				destructor.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (destructor);

				return null;
			}
        public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            if (invocationExpression == null)
            {
                return(null);
            }

            if (invocationDictionary.ContainsKey(invocationExpression))
            {
                return(invocationDictionary[invocationExpression]);
            }

            // add support for undocumented __makeref and __reftype keywords
            if (invocationExpression.TargetObject is IdentifierExpression)
            {
                IdentifierExpression idExpr = invocationExpression.TargetObject as IdentifierExpression;
                if (idExpr.Identifier == "__makeref")
                {
                    return(CreateResult("System.TypedReference"));
                }
                if (idExpr.Identifier == "__reftype")
                {
                    return(CreateResult("System.Type"));
                }
            }

            ResolveResult targetResult = Resolve(invocationExpression.TargetObject);

            if (targetResult is CombinedMethodResolveResult)
            {
                targetResult = ((CombinedMethodResolveResult)targetResult).MethodResolveResult;
            }

            targetResult.StaticResolve = false;             // invocation result is never static
            if (this.resolver.CallingType != null)
            {
                if (targetResult is ThisResolveResult)
                {
                    targetResult = new MethodResolveResult(this.resolver.CallingType.Methods.Where(method => method.IsConstructor));
                    ((MethodResolveResult)targetResult).Type = this.resolver.CallingType;
                    targetResult.CallingType   = resolver.CallingType;
                    targetResult.CallingMember = resolver.CallingMember;
                }
                else if (targetResult is BaseResolveResult)
                {
                    System.Collections.IEnumerable baseConstructors = null;
                    IType firstBaseType = null;
                    foreach (IReturnType bT in this.resolver.CallingType.BaseTypes)
                    {
                        IType resolvedBaseType = resolver.SearchType(bT);
                        if (firstBaseType == null && resolvedBaseType.ClassType != MonoDevelop.Projects.Dom.ClassType.Interface)
                        {
                            firstBaseType = resolvedBaseType;
                        }
                        foreach (IType baseType in resolver.Dom.GetInheritanceTree(resolvedBaseType))
                        {
                            if (baseType.ClassType == MonoDevelop.Projects.Dom.ClassType.Interface)
                            {
                                break;
                            }
                            baseConstructors = baseType.Methods.Where(method => method.IsConstructor);
                            goto bailOut;
                        }
                    }
bailOut:
                    if (baseConstructors == null)
                    {
                        if (firstBaseType != null)
                        {
                            // if there is a real base type without a .ctor a default .ctor for this type is generated.
                            DomMethod constructedConstructor;
                            constructedConstructor                = new DomMethod();
                            constructedConstructor.Name           = ".ctor";
                            constructedConstructor.MethodModifier = MethodModifier.IsConstructor;
                            constructedConstructor.DeclaringType  = firstBaseType;
                            constructedConstructor.Modifiers      = MonoDevelop.Projects.Dom.Modifiers.Public;
                            baseConstructors = new IMethod[] {
                                constructedConstructor
                            };
                        }
                        else
                        {
                            baseConstructors = resolver.SearchType(DomReturnType.Object).SearchMember(".ctor", true);
                        }
                    }
                    targetResult = new MethodResolveResult(baseConstructors);
                    ((MethodResolveResult)targetResult).Type = this.resolver.CallingType;
                    targetResult.CallingType   = resolver.CallingType;
                    targetResult.CallingMember = resolver.CallingMember;
                }
            }

            MethodResolveResult methodResult = targetResult as MethodResolveResult;

            if (methodResult != null)
            {
                methodResult.GetsInvoked = true;
//				Console.WriteLine ("--------------------");
//				Console.WriteLine ("i:" + methodResult.ResolvedType);

/*				foreach (var arg in methodResult.GenericArguments) {
 *                                      methodResult.AddGenericArgument (arg);
 *                              }*/
                foreach (Expression arg in invocationExpression.Arguments)
                {
                    var type = GetTypeSafe(arg);
                    methodResult.AddArgument(type);
                }
                //Console.WriteLine ("--------------------");
                methodResult.ResolveExtensionMethods();
//				Console.WriteLine ("i2:" + methodResult.ResolvedType);

                /*	MemberReferenceExpression mre = invocationExpression.TargetObject as MemberReferenceExpression;
                 *      if (mre != null) {
                 *              foreach (TypeReference typeReference in mre.TypeArguments) {
                 *                      methodResult.AddGenericArgument (new DomReturnType (String.IsNullOrEmpty (typeReference.SystemType) ? typeReference.Type : typeReference.SystemType));
                 *              }
                 *      }*/
//				return CreateResult (methodResult.Methods [0].ReturnType);
            }
            invocationDictionary[invocationExpression] = targetResult;
            return(targetResult);
        }
Exemple #31
0
        public static MonoDevelop.Projects.Dom.INode ConvertDParserToDomNode(D_Parser.Dom.INode n, ParsedDocument doc)
        {
            //TODO: DDoc comments!

            if (n is DMethod)
            {
                var dm = n as DMethod;

                var domMethod = new DomMethod(
                    n.Name,
                    GetNodeModifiers(dm),
                    dm.SpecialType == DMethod.MethodType.Constructor ? MethodModifier.IsConstructor : MethodModifier.None,
                    FromCodeLocation(n.StartLocation),
                    GetBlockBodyRegion(dm),
                    GetReturnType(n));

                foreach (var pn in dm.Parameters)
                    domMethod.Add(new DomParameter(domMethod, pn.Name, GetReturnType(pn)));

                domMethod.AddTypeParameter(GetTypeParameters(dm));

                foreach (var subNode in dm) domMethod.AddChild(ConvertDParserToDomNode(subNode, doc));

                return domMethod;
            }
            else if (n is DEnum)
            {
                var de = n as DEnum;

                var domType = new DomType(
                    doc.CompilationUnit,
                    ClassType.Enum,
                    GetNodeModifiers(de),
                    n.Name,
                    FromCodeLocation(n.StartLocation),
                    BuildTypeNamespace(n), GetBlockBodyRegion(de));

                foreach (var subNode in de)
                    domType.Add(ConvertDParserToDomNode(subNode, doc) as IMember);
                return domType;
            }
            else if (n is DClassLike)
            {
                var dc = n as DClassLike;

                ClassType ct = ClassType.Unknown;

                switch (dc.ClassType)
                {
                    case DTokens.Template:
                    case DTokens.Class:
                        ct = ClassType.Class;
                        break;
                    case DTokens.Interface:
                        ct = ClassType.Interface;
                        break;
                    case DTokens.Union:
                    case DTokens.Struct:
                        ct = ClassType.Struct;
                        break;
                }

                var domType = new DomType(
                    doc.CompilationUnit,
                    ct,
                    GetNodeModifiers(dc),
                    n.Name,
                    FromCodeLocation(n.StartLocation),
                    BuildTypeNamespace(n),
                    GetBlockBodyRegion(dc));

                domType.AddTypeParameter(GetTypeParameters(dc));
                foreach (var subNode in dc)
                    domType.Add(ConvertDParserToDomNode(subNode, doc) as IMember);
                return domType;
            }
            else if (n is DVariable)
            {
                var dv = n as DVariable;
                return new DomField(n.Name, GetNodeModifiers(dv), FromCodeLocation(n.StartLocation), GetReturnType(n));
            }
            return null;
        }
        /// <summary>
        /// Populate a DomType with methods
        /// </summary>
        void PopulateMethods(DomType parent)
        {
            List<int> removal = new List<int> ();
            Match match;
            DomMethod m;

            foreach (KeyValuePair<int,RubyDeclaration> mpair in methods) {
                if (mpair.Key > parent.Location.Line && mpair.Key < parent.BodyRegion.End.Line) {
                    parent.Add (m = new DomMethod (mpair.Value.name, Modifiers.None, MethodModifier.None, new DomLocation (mpair.Value.beginLine, 1),
                                               new DomRegion (mpair.Value.beginLine, mpair.Value.beginColumn+1,
                                                              mpair.Value.endLine, int.MaxValue), new DomReturnType (string.Empty)));
                    match = methodDefinition.Match (mpair.Value.declaration);
                    if (match.Groups["params"].Success) {
                        foreach (string param in match.Groups["params"].Value.Split (new char[]{',',' ','\t'}, StringSplitOptions.RemoveEmptyEntries)) {
                            m.Add (new DomParameter (m, param, new DomReturnType (param)));
                        }
                    }

                    removal.Add (mpair.Key);
                }// Add methods that are declared within the parent's scope
            }// Check detected methods

            // Remove used methods from map
            foreach (int key in removal){ methods.Remove (key); }
        }
		public void ReadWriteMethodTest ()
		{
			DomMethod input = new DomMethod ();
			input.Name      = "Test";
			input.MethodModifier = MethodModifier.IsConstructor;
			input.Add (new DomParameter (input, "par1", DomReturnType.Void));
			input.AddTypeParameter (new TypeParameter ("T"));
			MemoryStream ms = new MemoryStream ();
			BinaryWriter writer = new BinaryWriter (ms);
			DomPersistence.Write (writer, DefaultNameEncoder, input);
			byte[] bytes = ms.ToArray ();
			
			DomMethod result = DomPersistence.ReadMethod (CreateReader (bytes), DefaultNameDecoder);
			Assert.AreEqual ("Test", result.Name);
			Assert.AreEqual (true, result.IsConstructor);
			Assert.AreEqual ("par1", result.Parameters [0].Name);
			Assert.AreEqual ("Void", result.Parameters [0].ReturnType.Name);
			Assert.AreEqual (1, result.TypeParameters.Count);
			Assert.AreEqual ("T", result.TypeParameters [0].Name);
		}
			public override void Visit (Destructor d)
			{
				DomMethod method = new DomMethod ();
				method.Name = ".dtor";
				method.Documentation = RetrieveDocumentation (d.Location.Row);
				method.Location = Convert (d.MemberName.Location);
				if (d.Block != null) {
					var location = LocationsBag.GetMemberLocation (d);
					var region = ConvertRegion (location != null ? location[1] : d.Block.StartLocation, d.Block.EndLocation);
					if (location != null)
						region.Start = new DomLocation (region.Start.Line, region.Start.Column + 1);
					method.BodyRegion = region;
				}
				method.Modifiers = ConvertModifiers (d.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.SpecialName;
				method.MethodModifier |= MethodModifier.IsFinalizer;
				AddAttributes (method, d.OptAttributes, d);
				AddExplicitInterfaces (method, d);
				method.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (method);
			}
			public override void Visit (Method m)
			{
				DomMethod method = new DomMethod ();
				method.Name = ConvertQuoted (m.MemberName.Name);
				method.Documentation = RetrieveDocumentation (m.Location.Row);
				method.Location = Convert (m.MemberName.Location);
				method.Modifiers = ConvertModifiers (m.ModFlags);
				if (m.Block != null) {
					var location = LocationsBag.GetMemberLocation (m);
					var region = ConvertRegion (location != null ? location[1] : m.Block.StartLocation, m.Block.EndLocation);
					if (location != null)
						region.Start = new DomLocation (region.Start.Line, region.Start.Column + 1);
					method.BodyRegion = region;
				}
				
				method.ReturnType = ConvertReturnType (m.TypeName);
				AddAttributes (method, m.OptAttributes, m);
				AddParameter (method, m.ParameterInfo);
				AddExplicitInterfaces (method, m);
				method.Modifiers = ConvertModifiers (m.ModFlags);
				if (method.IsStatic && method.Parameters.Count > 0 && method.Parameters[0].ParameterModifiers == ParameterModifiers.This)
					method.MethodModifier |= MethodModifier.IsExtension;
				if (m.GenericMethod != null)
					AddTypeParameter (method, m.GenericMethod);
				method.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (method);
			}
Exemple #36
0
        public static MonoDevelop.Projects.Dom.INode ConvertDParserToDomNode(D_Parser.Dom.INode n, ParsedDocument doc)
        {
            //TODO: DDoc comments!

            if (n is DMethod)
            {
                var dm = n as DMethod;

                var domMethod = new DomMethod(
                    n.Name,
                    GetNodeModifiers(dm),
                    dm.SpecialType == DMethod.MethodType.Constructor ? MethodModifier.IsConstructor : MethodModifier.None,
                    FromCodeLocation(n.StartLocation),
                    GetBlockBodyRegion(dm),
                    GetReturnType(n));

                foreach (var pn in dm.Parameters)
                {
                    domMethod.Add(new DomParameter(domMethod, pn.Name, GetReturnType(pn)));
                }


                domMethod.AddTypeParameter(GetTypeParameters(dm));

                foreach (var subNode in dm)
                {
                    domMethod.AddChild(ConvertDParserToDomNode(subNode, doc));
                }

                return(domMethod);
            }
            else if (n is DEnum)
            {
                var de = n as DEnum;

                var domType = new DomType(
                    doc.CompilationUnit,
                    ClassType.Enum,
                    GetNodeModifiers(de),
                    n.Name,
                    FromCodeLocation(n.StartLocation),
                    BuildTypeNamespace(n), GetBlockBodyRegion(de));

                foreach (var subNode in de)
                {
                    domType.Add(ConvertDParserToDomNode(subNode, doc) as IMember);
                }
                return(domType);
            }
            else if (n is DClassLike)
            {
                var dc = n as DClassLike;

                ClassType ct = ClassType.Unknown;

                switch (dc.ClassType)
                {
                case DTokens.Template:
                case DTokens.Class:
                    ct = ClassType.Class;
                    break;

                case DTokens.Interface:
                    ct = ClassType.Interface;
                    break;

                case DTokens.Union:
                case DTokens.Struct:
                    ct = ClassType.Struct;
                    break;
                }

                var domType = new DomType(
                    doc.CompilationUnit,
                    ct,
                    GetNodeModifiers(dc),
                    n.Name,
                    FromCodeLocation(n.StartLocation),
                    BuildTypeNamespace(n),
                    GetBlockBodyRegion(dc));

                domType.AddTypeParameter(GetTypeParameters(dc));
                foreach (var subNode in dc)
                {
                    domType.Add(ConvertDParserToDomNode(subNode, doc) as IMember);
                }
                return(domType);
            }
            else if (n is DVariable)
            {
                var dv = n as DVariable;
                return(new DomField(n.Name, GetNodeModifiers(dv), FromCodeLocation(n.StartLocation), GetReturnType(n)));
            }
            return(null);
        }
        static void GenerateCU(XmlParsedDocument doc)
        {
            if (doc.XDocument == null || doc.XDocument.RootElement == null)
            {
                doc.Add(new Error(ErrorType.Error, 1, 1, "No root node found."));
                return;
            }

            XAttribute rootClass = doc.XDocument.RootElement.Attributes [new XName("x", "Class")];

            if (rootClass == null)
            {
                doc.Add(new Error(ErrorType.Error, 1, 1, "Root node does not contain an x:Class attribute."));
                return;
            }

            bool isApplication = doc.XDocument.RootElement.Name.Name == "Application";

            string rootNamespace, rootType, rootAssembly;

            XamlG.ParseXmlns(rootClass.Value, out rootType, out rootNamespace, out rootAssembly);

            CompilationUnit cu = new CompilationUnit(doc.FileName);

            doc.CompilationUnit = cu;

            DomRegion rootRegion = doc.XDocument.RootElement.Region;

            if (doc.XDocument.RootElement.IsClosed)
            {
                rootRegion.End = doc.XDocument.RootElement.ClosingTag.Region.End;
            }

            DomType declType = new DomType(cu, ClassType.Class, Modifiers.Partial | Modifiers.Public, rootType,
                                           doc.XDocument.RootElement.Region.Start, rootNamespace, rootRegion);

            cu.Add(declType);

            DomMethod initcomp = new DomMethod();

            initcomp.Name       = "InitializeComponent";
            initcomp.Modifiers  = Modifiers.Public;
            initcomp.ReturnType = DomReturnType.Void;
            declType.Add(initcomp);

            DomField _contentLoaded = new DomField("_contentLoaded");

            _contentLoaded.ReturnType = new DomReturnType("System.Boolean");

            if (isApplication)
            {
                return;
            }

            cu.Add(new DomUsing(DomRegion.Empty, "System"));
            cu.Add(new DomUsing(DomRegion.Empty, "System.Windows"));
            cu.Add(new DomUsing(DomRegion.Empty, "System.Windows.Controls"));
            cu.Add(new DomUsing(DomRegion.Empty, "System.Windows.Documents"));
            cu.Add(new DomUsing(DomRegion.Empty, "System.Windows.Input"));
            cu.Add(new DomUsing(DomRegion.Empty, "System.Windows.Media"));
            cu.Add(new DomUsing(DomRegion.Empty, "System.Windows.Media.Animation"));
            cu.Add(new DomUsing(DomRegion.Empty, "System.Windows.Shapes"));
            cu.Add(new DomUsing(DomRegion.Empty, "System.Windows.Controls.Primitives"));

//			Dictionary<string,string> namespaceMap = new Dictionary<string, string> ();
//			namespaceMap["x"] = "http://schemas.microsoft.com/winfx/2006/xaml";

            XName nameAtt = new XName("x", "Name");

            foreach (XElement el in doc.XDocument.RootElement.AllDescendentElements)
            {
                XAttribute name = el.Attributes [nameAtt];
                if (name != null && name.IsComplete)
                {
                    string type = ResolveType(el);
                    if (type == null || type.Length == 0)
                    {
                        doc.Add(new Error(ErrorType.Error, el.Region.Start, "Could not find namespace for '" + el.Name.FullName + "'."));
                    }
                    else
                    {
                        declType.Add(new DomField(name.Value, Modifiers.Internal, el.Region.Start, new DomReturnType(type)));
                    }
                }
            }
        }
		public override ParsedDocument Parse (ProjectDom dom, string fileName, string content)
		{
			ParsedDocument doc = new ParsedDocument (fileName);
			ProjectInformation pi = ProjectInformationManager.Instance.Get ((null == dom)? null: dom.Project);
			if(null == doc.CompilationUnit){ doc.CompilationUnit = new CompilationUnit (fileName); }
			CompilationUnit cu = (CompilationUnit)doc.CompilationUnit;
			int lastLine = 0;
			ICollection<Symbol> classes = pi.GetClassesForFile (fileName); 
			
			if (null == classes || 0 == classes.Count) {
				return lastGood;
			}
			
			foreach (Symbol node in classes) {
				if (null == node){ continue; }
				List<IMember> members = new List<IMember> ();
				lastLine = node.SourceReferences[0].LastLine;
                
				foreach (Symbol child in node.Children) {
					if (1 > child.SourceReferences.Count || 
					    child.SourceReferences[0].File != node.SourceReferences[0].File){ continue; }
					lastLine = Math.Max (lastLine, child.SourceReferences[0].LastLine+1);
					
					switch (child.SymbolType.ToLower ()) {
					case "class":
						members.Add (new DomType (new CompilationUnit (fileName), ClassType.Class, child.Name, new DomLocation (child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion (child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List<IMember> ()));
						break;
					case "interface":
						members.Add (new DomType (new CompilationUnit (fileName), ClassType.Interface, child.Name, new DomLocation (child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion (child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List<IMember> ()));
						break;
					case "delegate":
						members.Add (new DomType (new CompilationUnit (fileName), ClassType.Delegate, child.Name, new DomLocation (child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion (child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List<IMember> ()));
						break;
					case "struct":
						members.Add (new DomType (new CompilationUnit (fileName), ClassType.Struct, child.Name, new DomLocation (child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion (child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List<IMember> ()));
						break;
					case "enum":
						members.Add (new DomType (new CompilationUnit (fileName), ClassType.Enum, child.Name, new DomLocation (child.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion (child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new List<IMember> ()));
						break;
					case "method":
					case "creationmethod":
					case "constructor":
						DomMethod method = new DomMethod (child.Name, Modifiers.None, MethodModifier.None, new DomLocation (child.SourceReferences[0].FirstLine, 1), new DomRegion (child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new DomReturnType (child.ReturnType.TypeName));
						foreach (DataType param in child.Parameters) {
							method.Add (new DomParameter (method, param.Name, new DomReturnType (param.TypeName)));
						}
						members.Add (method);
						break;
					case "property":
						members.Add (new DomProperty (child.Name, Modifiers.None, new DomLocation (child.SourceReferences[0].FirstLine, 1), new DomRegion (child.SourceReferences[0].FirstLine, int.MaxValue, child.SourceReferences[0].LastLine, int.MaxValue), new DomReturnType ()));
						break;
					case "field":
					case "constant":
					case "errorcode":
						members.Add (new DomField (child.Name, Modifiers.None, new DomLocation (child.SourceReferences[0].FirstLine, 1), new DomReturnType ()));
						break;
					case "signal":
						members.Add (new DomEvent (child.Name, Modifiers.None, new DomLocation (child.SourceReferences[0].FirstLine, 1), new DomReturnType ()));
						break;
					default:
						MonoDevelop.Core.LoggingService.LogDebug ("ValaDocumentParser: Unsupported member type: {0}", child.SymbolType);
						break;
					}// Switch on node type
				}// Collect members
				
				cu.Add (new DomType (new CompilationUnit (fileName), ClassType.Class, node.Name, new DomLocation (node.SourceReferences[0].FirstLine, 1), string.Empty, new DomRegion (node.SourceReferences[0].FirstLine, int.MaxValue, lastLine, int.MaxValue), members));
			}// Add each class in file
			
			return (lastGood = doc);
		}// Parse
		static void GenerateCU (XmlParsedDocument doc)
		{
			if (doc.XDocument == null || doc.XDocument.RootElement == null) {
				doc.Add (new Error (ErrorType.Error, 1, 1, "No root node found."));
				return;
			}

			XAttribute rootClass = doc.XDocument.RootElement.Attributes [new XName ("x", "Class")];
			if (rootClass == null) {
				doc.Add (new Error (ErrorType.Error, 1, 1, "Root node does not contain an x:Class attribute."));
				return;
			}

			bool isApplication = doc.XDocument.RootElement.Name.Name == "Application";
			
			string rootNamespace, rootType, rootAssembly;
			XamlG.ParseXmlns (rootClass.Value, out rootType, out rootNamespace, out rootAssembly);
			
			CompilationUnit cu = new CompilationUnit (doc.FileName);
			doc.CompilationUnit = cu;

			DomRegion rootRegion = doc.XDocument.RootElement.Region;
			if (doc.XDocument.RootElement.IsClosed)
				rootRegion.End = doc.XDocument.RootElement.ClosingTag.Region.End;
			
			DomType declType = new DomType (cu, ClassType.Class, Modifiers.Partial | Modifiers.Public, rootType,
			                                doc.XDocument.RootElement.Region.Start, rootNamespace, rootRegion);
			cu.Add (declType);
			
			DomMethod initcomp = new DomMethod ();
			initcomp.Name = "InitializeComponent";
			initcomp.Modifiers = Modifiers.Public;
			initcomp.ReturnType = DomReturnType.Void;
			declType.Add (initcomp);
			
			DomField _contentLoaded = new DomField ("_contentLoaded");
			_contentLoaded.ReturnType = new DomReturnType ("System.Boolean");

			if (isApplication)
				return;
			
			cu.Add (new DomUsing (DomRegion.Empty, "System"));
			cu.Add (new DomUsing (DomRegion.Empty, "System.Windows"));
			cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Controls"));
			cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Documents"));
			cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Input"));
			cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Media"));
			cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Media.Animation"));
			cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Shapes"));
			cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Controls.Primitives"));
			
//			Dictionary<string,string> namespaceMap = new Dictionary<string, string> ();
//			namespaceMap["x"] = "http://schemas.microsoft.com/winfx/2006/xaml";
			
			XName nameAtt = new XName ("x", "Name");
			
			foreach (XElement el in doc.XDocument.RootElement.AllDescendentElements) {
				XAttribute name = el.Attributes [nameAtt];
				if (name != null && name.IsComplete) {
					string type = ResolveType (el);
					if (type == null || type.Length == 0)
						doc.Add (new Error (ErrorType.Error, el.Region.Start, "Could not find namespace for '" + el.Name.FullName + "'."));
					else
						declType.Add (new DomField (name.Value, Modifiers.Internal, el.Region.Start, new DomReturnType (type)));
				}
			}
		}
        IEnumerable<IMethod> BuildFunctions(IEnumerable<PythonFunction> functions)
        {
            if (functions == null)
                yield break;

            foreach (PythonFunction pyFunc in functions)
            {
                var domFunc = new DomMethod () {
                    Name          = pyFunc.Name,
                    Documentation = pyFunc.Documentation,
                    BodyRegion    = pyFunc.Region,
                    Location      = new DomLocation (pyFunc.Region.Start.Line - 1, 0),
                    ReturnType    = new DomReturnType () {
                        Name      = pyFunc.Name, // FIXME: Get inferred type
                        Namespace = Module.FullName,
                    },
                };
                m_AllWrapped.Add (domFunc);

                foreach (PythonArgument pyArg in pyFunc.Arguments)
                {
                    var domArg = new DomParameter () {
                        Name       = pyArg.Name,
                        ReturnType = new DomReturnType () {
                            Name      = pyArg.Name, // FIXME: Get inferred type
                            Namespace = Module.FullName,
                        },
                    };
                    m_AllWrapped.Add (domArg);
                    domFunc.Add (domArg);
                }

                yield return domFunc;
            }
        }
Exemple #41
0
		public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
		{
			if (invocationExpression == null) 
				return null;
			
			if (invocationDictionary.ContainsKey (invocationExpression))
				return invocationDictionary[invocationExpression];
			
			// add support for undocumented __makeref and __reftype keywords
			if (invocationExpression.TargetObject is IdentifierExpression) {
				IdentifierExpression idExpr = invocationExpression.TargetObject as IdentifierExpression;
				if (idExpr.Identifier == "__makeref") 
					return CreateResult ("System.TypedReference");
				if (idExpr.Identifier == "__reftype") 
					return CreateResult ("System.Type");
			}
			
			ResolveResult targetResult = Resolve (invocationExpression.TargetObject);
			
			if (targetResult is CombinedMethodResolveResult)
				targetResult = ((CombinedMethodResolveResult)targetResult).MethodResolveResult;
			
			targetResult.StaticResolve = false; // invocation result is never static
			if (this.resolver.CallingType != null) {
				if (targetResult is ThisResolveResult) {
					targetResult = new MethodResolveResult (this.resolver.CallingType.Methods.Where (method => method.IsConstructor));
					((MethodResolveResult)targetResult).Type = this.resolver.CallingType;
					targetResult.CallingType   = resolver.CallingType;
					targetResult.CallingMember = resolver.CallingMember;
				} else if (targetResult is BaseResolveResult) {
					System.Collections.IEnumerable baseConstructors = null;
					IType firstBaseType = null;
					foreach (IReturnType bT in this.resolver.CallingType.BaseTypes) {
						IType resolvedBaseType = resolver.SearchType (bT);
						if (firstBaseType == null && resolvedBaseType.ClassType != MonoDevelop.Projects.Dom.ClassType.Interface)
							firstBaseType = resolvedBaseType;
						foreach (IType baseType in resolver.Dom.GetInheritanceTree (resolvedBaseType)) {
							if (baseType.ClassType == MonoDevelop.Projects.Dom.ClassType.Interface)
								break;
							baseConstructors = baseType.Methods.Where (method => method.IsConstructor);
							goto bailOut;
						}
					}
				bailOut:
					if (baseConstructors == null) {
						if (firstBaseType != null) {
							// if there is a real base type without a .ctor a default .ctor for this type is generated.
							DomMethod constructedConstructor;
							constructedConstructor = new DomMethod ();
							constructedConstructor.Name = ".ctor";
							constructedConstructor.MethodModifier = MethodModifier.IsConstructor;
							constructedConstructor.DeclaringType = firstBaseType;
							constructedConstructor.Modifiers = MonoDevelop.Projects.Dom.Modifiers.Public;
							baseConstructors = new IMethod[] {
								constructedConstructor
							};
						} else {
							baseConstructors = resolver.SearchType (DomReturnType.Object).SearchMember (".ctor", true);
						}
						
					}
					targetResult = new MethodResolveResult (baseConstructors);
					((MethodResolveResult)targetResult).Type = this.resolver.CallingType;
					targetResult.CallingType   = resolver.CallingType;
					targetResult.CallingMember = resolver.CallingMember;
				}
			}
			
			MethodResolveResult methodResult = targetResult as MethodResolveResult;
			if (methodResult != null) {
				methodResult.GetsInvoked = true;
//				Console.WriteLine ("--------------------");
//				Console.WriteLine ("i:" + methodResult.ResolvedType);
/*				foreach (var arg in methodResult.GenericArguments) {
					methodResult.AddGenericArgument (arg);
				}*/
				foreach (Expression arg in invocationExpression.Arguments) {
					var type = GetTypeSafe (arg);
					methodResult.AddArgument (type);
				}
				//Console.WriteLine ("--------------------");
				methodResult.ResolveExtensionMethods ();
//				Console.WriteLine ("i2:" + methodResult.ResolvedType);
			/*	MemberReferenceExpression mre = invocationExpression.TargetObject as MemberReferenceExpression;
				if (mre != null) {
					foreach (TypeReference typeReference in mre.TypeArguments) {
						methodResult.AddGenericArgument (new DomReturnType (String.IsNullOrEmpty (typeReference.SystemType) ? typeReference.Type : typeReference.SystemType));
					}
				}*/
//				return CreateResult (methodResult.Methods [0].ReturnType);
			}
			invocationDictionary[invocationExpression] = targetResult;
			return targetResult;
		}
Exemple #42
0
		public void InstantiatedMethodByArgumentTest_Complex ()
		{
			// build "T MyMethod<T,S> (S b, KeyValuePair<S, T> a)"
			DomMethod method = new DomMethod ();
			method.Name = "MyMethod";
			method.ReturnType = new DomReturnType ("T");
			method.AddTypeParameter (new TypeParameter ("T"));
			method.AddTypeParameter (new TypeParameter ("S"));
			method.Add (new DomParameter (method, "b", new DomReturnType ("S")));
			
			DomReturnType returnType = new DomReturnType ("KeyValuePair");
			returnType.AddTypeParameter (new DomReturnType ("T"));
			returnType.AddTypeParameter (new DomReturnType ("S"));
			method.Add (new DomParameter (method, "a", returnType));
			
			// give int, object as param type
			List<IReturnType> genArgs = new List<IReturnType> ();
			List<IReturnType> args    = new List<IReturnType> ();
			genArgs.Add (DomReturnType.Int32);
			genArgs.Add (DomReturnType.Object);
			
			IMethod instMethod = DomMethod.CreateInstantiatedGenericMethod (method, genArgs, args);
			
			// check
			Assert.AreEqual (DomReturnType.Int32.FullName, instMethod.ReturnType.FullName);
			Assert.AreEqual (DomReturnType.Object.FullName, instMethod.Parameters[0].ReturnType.FullName);
			
			Assert.AreEqual (DomReturnType.Int32.FullName, instMethod.Parameters[1].ReturnType.GenericArguments[0].FullName);
			Assert.AreEqual (DomReturnType.Object.FullName, instMethod.Parameters[1].ReturnType.GenericArguments[1].FullName);
		}
			public override object VisitConstructorDeclaration (ICSharpCode.NRefactory.Ast.ConstructorDeclaration constructorDeclaration, object data)
			{
				DomMethod constructor = new DomMethod ();
				constructor.Documentation = RetrieveDocumentation (constructorDeclaration.StartLocation.Line);
				constructor.Name = ".ctor";
				constructor.MethodModifier |= MethodModifier.IsConstructor;
				constructor.Location = ConvertLocation (constructorDeclaration.StartLocation);
				constructor.BodyRegion = ConvertRegion (constructorDeclaration.EndLocation, constructorDeclaration.Body != null ? constructorDeclaration.Body.EndLocation : new ICSharpCode.NRefactory.Location (-1, -1));
				constructor.Modifiers = ConvertModifiers (constructorDeclaration.Modifier);
				AddAttributes (constructor, constructorDeclaration.Attributes);
				constructor.Add (ConvertParameterList (constructor, constructorDeclaration.Parameters));

				constructor.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (constructor);
				return null;
			}
Exemple #44
0
		public void ExtensionMethodPreserveParameterTest ()
		{
			// build "T MyMethod<T, S> (T a, S b)"
			DomMethod method = new DomMethod ();
			method.Name = "MyMethod";
			method.ReturnType = new DomReturnType ("T");
			method.AddTypeParameter (new TypeParameter ("T"));
			method.AddTypeParameter (new TypeParameter ("S"));
			
			method.Add (new DomParameter (method, "a", new DomReturnType ("T")));
			method.Add (new DomParameter (method, "b", new DomReturnType ("S")));
			
			// extend method
			List<IReturnType> genArgs = new List<IReturnType> ();
			List<IReturnType> args    = new List<IReturnType> ();
			DomType extType = new DomType ("MyType");
			
			ExtensionMethod extMethod = new ExtensionMethod (extType, method, genArgs, args);
			
			// check for MyType MyMethod<S> (S b)
			Assert.AreEqual ("MyType", extMethod.ReturnType.FullName);
			Assert.AreEqual ("S", extMethod.Parameters[0].ReturnType.FullName);
			Assert.AreEqual (1, extMethod.TypeParameters.Count);
			Assert.AreEqual ("S", extMethod.TypeParameters[0].Name);
		}
			public override object VisitOperatorDeclaration (ICSharpCode.NRefactory.Ast.OperatorDeclaration operatorDeclaration, object data)
			{
				DomMethod method = new DomMethod ();
				method.Name = GetOperatorName (operatorDeclaration);
				method.Documentation = RetrieveDocumentation (operatorDeclaration.StartLocation.Line);
				method.Location = ConvertLocation (operatorDeclaration.StartLocation);
				method.BodyRegion = ConvertRegion (operatorDeclaration.EndLocation, operatorDeclaration.Body != null ? operatorDeclaration.Body.EndLocation : new ICSharpCode.NRefactory.Location (-1, -1));
				method.Modifiers = ConvertModifiers (operatorDeclaration.Modifier) | Modifiers.SpecialName;
				if (operatorDeclaration.IsExtensionMethod)
					method.MethodModifier |= MethodModifier.IsExtension;
				method.ReturnType = ConvertReturnType (operatorDeclaration.TypeReference);
				AddAttributes (method, operatorDeclaration.Attributes);
				method.Add (ConvertParameterList (method, operatorDeclaration.Parameters));
				AddExplicitInterfaces (method, operatorDeclaration.InterfaceImplementations);

				if (operatorDeclaration.Templates != null && operatorDeclaration.Templates.Count > 0) {
					foreach (ICSharpCode.NRefactory.Ast.TemplateDefinition td in operatorDeclaration.Templates) {
						method.AddTypeParameter (ConvertTemplateDefinition (td));
					}
				}
				method.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (method);

				return null;
			}
        static DomType ReadTypeInternal(BinaryReader reader, INameDecoder nameTable)
        {
            uint typeCount = ReadUInt(reader, 1000);

            if (typeCount > 1)
            {
                CompoundType compoundResult = new CompoundType();
                while (typeCount-- > 0)
                {
                    compoundResult.AddPart(ReadTypeInternal(reader, nameTable));
                }

                return(compoundResult);
            }

            DomType result = new DomType();

            ReadMemberInformation(reader, nameTable, result);
//			bool verbose = result.Name == "CopyDelegate";
//			if (verbose) System.Console.WriteLine("read type:" + result.Name);
            result.TypeModifier = (TypeModifier)reader.ReadUInt32();
            result.BodyRegion   = ReadRegion(reader, nameTable);
            string compilationUnitFileName = ReadString(reader, nameTable);

            result.CompilationUnit = new CompilationUnit(compilationUnitFileName);

            result.Namespace = ReadString(reader, nameTable);
            result.ClassType = (ClassType)reader.ReadUInt32();
            result.BaseType  = ReadReturnType(reader, nameTable);

            // implemented interfaces
            long count = ReadUInt(reader, 5000);

//			if (verbose) System.Console.WriteLine("impl. interfaces:" + count);
            while (count-- > 0)
            {
                result.AddInterfaceImplementation(ReadReturnType(reader, nameTable));
            }

            // innerTypes
//			if (verbose) System.Console.WriteLine("pos:" + reader.BaseStream.Position);
            count = ReadUInt(reader, 10000);
//			if (verbose) System.Console.WriteLine("inner types:" + count);
            while (count-- > 0)
            {
                DomType innerType = ReadTypeInternal(reader, nameTable);
                innerType.DeclaringType = result;
                result.Add(innerType);
            }

            // fields
//			if (verbose) System.Console.WriteLine("pos:" + reader.BaseStream.Position);
            count = ReadUInt(reader, 10000);
//			if (verbose) System.Console.WriteLine("fields:" + count);
            while (count-- > 0)
            {
                DomField field = ReadField(reader, nameTable);
                field.DeclaringType = result;
                result.Add(field);
            }

            // methods
//			if (verbose) System.Console.WriteLine("pos:" + reader.BaseStream.Position);
            count = ReadUInt(reader, 10000);
//			if (verbose) System.Console.WriteLine("methods:" + count);
            while (count-- > 0)
            {
                DomMethod method = ReadMethod(reader, nameTable);
                method.DeclaringType = result;
                result.Add(method);
            }

            // properties
//			if (verbose) System.Console.WriteLine("pos:" + reader.BaseStream.Position);
            count = ReadUInt(reader, 10000);
//			if (verbose) System.Console.WriteLine("properties:" + count);
            while (count-- > 0)
            {
                DomProperty property = ReadProperty(reader, nameTable);
                property.DeclaringType = result;
                result.Add(property);
            }

            // events
//			if (verbose) System.Console.WriteLine("pos:" + reader.BaseStream.Position);
            count = ReadUInt(reader, 10000);
//			if (verbose) System.Console.WriteLine("events:" + count);
            while (count-- > 0)
            {
                DomEvent evt = ReadEvent(reader, nameTable);
                evt.DeclaringType = result;
                result.Add(evt);
            }

            // type parameters
            count = ReadUInt(reader, 500);
            while (count-- > 0)
            {
                TypeParameter tp = ReadTypeParameter(reader, nameTable);
                result.AddTypeParameter(tp);
            }
            return(result);
        }
		// used for constructor completion
		public NRefactoryParameterDataProvider (TextEditorData editor, NRefactoryResolver resolver, IType type)
		{
			if (type != null) {
				if (type.ClassType == ClassType.Delegate) {
					IMethod invokeMethod = ExtractInvokeMethod (type);
					if (type is InstantiatedType) {
						this.delegateName = ((InstantiatedType)type).UninstantiatedType.Name;
					} else {
						this.delegateName = type.Name;
					}
					if (invokeMethod != null) {
						methods.Add (invokeMethod);
					} else {
						// no invoke method -> tried to create an abstract delegate
					}
					return;
				}
				bool includeProtected = DomType.IncludeProtected (resolver.Dom, type, resolver.CallingType);
				bool constructorFound = false;
				HashSet<string> alreadyAdded = new HashSet<string> ();
				foreach (IMethod method in type.Methods) {
					constructorFound |= method.IsConstructor;
					string str = ambience.GetString (method, OutputFlags.IncludeParameters);
					if (alreadyAdded.Contains (str))
						continue;
					alreadyAdded.Add (str);
					if ((method.IsConstructor && method.IsAccessibleFrom (resolver.Dom, type, resolver.CallingMember, includeProtected)))
						methods.Add (method);
				}
				// No constructor - generating default
				if (!constructorFound && (type.TypeModifier & TypeModifier.HasOnlyHiddenConstructors) != TypeModifier.HasOnlyHiddenConstructors) {
					DomMethod defaultConstructor = new DomMethod ();
					defaultConstructor.MethodModifier = MethodModifier.IsConstructor;
					defaultConstructor.DeclaringType = type;
					methods.Add (defaultConstructor);
				}
			}
		}
		static DomMethod GenerateMethodStub (RefactoringOptions options, ExtractMethodParameters param)
		{
			DomMethod result = new DomMethod ();
			result.Name = param.Name;
			result.ReturnType = param.ExpressionType ?? DomReturnType.Void;
			result.Modifiers = param.Modifiers;
			if (!param.ReferencesMember)
				result.Modifiers |= MonoDevelop.Projects.Dom.Modifiers.Static;
			
			if (param.Parameters == null)
				return result;
			foreach (var p in param.Parameters) {
				if (param.OneChangedVariable && p.UsedAfterCutRegion && !p.UsedInCutRegion)
					continue;
				var newParameter = new DomParameter ();
				newParameter.Name = p.Name;
				newParameter.ReturnType = p.ReturnType;
				
				if (!param.OneChangedVariable) {
					if (!p.IsDefinedInsideCutRegion && p.IsChangedInsideCutRegion) {
						newParameter.ParameterModifiers = p.UsedBeforeCutRegion ? ParameterModifiers.Ref : ParameterModifiers.Out;
					}
				}
				result.Add (newParameter);
			}
			return result;
		}
		IMethod ConstructMethodFromInvocation (RefactoringOptions options)
		{
			var resolver = options.GetResolver ();
			var data = options.GetTextEditorData ();
			
			DomMethod result = new DomMethod (methodName, modifiers, MethodModifier.None, DomLocation.Empty, DomRegion.Empty, returnType);
			result.DeclaringType = new DomType ("GeneratedType") { ClassType = declaringType.ClassType };
			int i = 1;
			foreach (var curArg in invocation.Arguments) {
				var argument = curArg;
				DomParameter arg = new DomParameter ();
				if (argument is DirectionExpression) {
					var de = (DirectionExpression)argument;
					arg.ParameterModifiers = de.FieldDirection == FieldDirection.Out ? ParameterModifiers.Out : ParameterModifiers.Ref; 
					argument = de.Expression;
				}
				
				string argExpression = data.GetTextBetween (argument.StartLocation.Line, argument.StartLocation.Column, argument.EndLocation.Line, argument.EndLocation.Column);
				var resolveResult = resolver.Resolve (new ExpressionResult (argExpression), resolvePosition);
				
				if (argument is MemberReferenceExpression) {
					arg.Name = ((MemberReferenceExpression)argument).Identifier.Name;
				} else if (argument is IdentifierExpression) {
					arg.Name = ((IdentifierExpression)argument).Identifier;
					int idx = arg.Name.LastIndexOf ('.');
					if (idx >= 0)
						arg.Name = arg.Name.Substring (idx + 1);
				} else {
					arg.Name = "par" + i++;
				}
				
				arg.Name = char.ToLower (arg.Name[0]) + arg.Name.Substring (1);
				
				if (resolveResult != null) {
					arg.ReturnType = resolveResult.ResolvedType;
				} else {
					arg.ReturnType = DomReturnType.Object;
				}
				
				result.Add (arg);
			}
			return result;
		}
Exemple #50
0
		public void ExtensionMethodTest ()
		{
			// build "T MyMethod<T, S> (this KeyValuePair<T, S> a, S b)"
			DomMethod method = new DomMethod ();
			method.Name = "MyMethod";
			method.ReturnType = new DomReturnType ("T");
			method.AddTypeParameter (new TypeParameter ("T"));
			method.AddTypeParameter (new TypeParameter ("S"));
			
			DomReturnType returnType = new DomReturnType ("KeyValuePair");
			returnType.AddTypeParameter (new DomReturnType ("T"));
			returnType.AddTypeParameter (new DomReturnType ("S"));
			method.Add (new DomParameter (method, "a", returnType));
			method.Add (new DomParameter (method, "b", new DomReturnType ("S")));
			
			// Build extendet type KeyValuePair<int, object>
			DomType type = new DomType ("KeyValuePair");
			type.AddTypeParameter (new TypeParameter ("T"));
			type.AddTypeParameter (new TypeParameter ("S"));
			IType extType = DomType.CreateInstantiatedGenericTypeInternal (type, new IReturnType[] { DomReturnType.Int32, DomReturnType.Object });
			Console.WriteLine (extType);
			
			// extend method
			List<IReturnType> genArgs = new List<IReturnType> ();
			List<IReturnType> args    = new List<IReturnType> ();
			
			ExtensionMethod extMethod = new ExtensionMethod (extType, method, genArgs, args);
			
			Console.WriteLine (extMethod);
			// check 
			Assert.AreEqual (DomReturnType.Int32.FullName, extMethod.ReturnType.FullName);
			Assert.AreEqual (DomReturnType.Object.FullName, extMethod.Parameters[0].ReturnType.FullName);
		}
			public override void Visit (Method m)
			{
				DomMethod method = new DomMethod ();
				method.Name = m.MemberName.Name;
				method.Documentation = RetrieveDocumentation (m.Location.Row);
				method.Location = Convert (m.MemberName.Location);
				method.Modifiers = ConvertModifiers (m.ModFlags);
				if (m.Block != null) {
					var location = LocationsBag.GetMemberLocation (m);
					var region = ConvertRegion (location != null ? location[1] : m.Block.StartLocation, m.Block.EndLocation);
					if (location != null)
						region.Start = new DomLocation (region.Start.Line, region.Start.Column + 1);
					method.BodyRegion = region;
				}
				
				method.ReturnType = ConvertReturnType (m.TypeName);
				AddAttributes (method, m.OptAttributes, m);
				AddParameter (method, m.ParameterInfo);
				AddExplicitInterfaces (method, m);
				method.Modifiers = ConvertModifiers (m.ModFlags);
				if (method.IsStatic && method.Parameters.Count > 0 && method.Parameters[0].ParameterModifiers == ParameterModifiers.This)
					method.MethodModifier |= MethodModifier.IsExtension;
				if (m.GenericMethod != null)
					AddTypeParameter (method, m.GenericMethod);
				method.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (method);

				// Hack: Fixes Bug 650840 - Missing completion for locals
				// Take out, when the parser has improved error recovery for this case.
				if (m.Block == null && typeStack.Peek ().ClassType != ClassType.Interface) {
					method.BodyRegion = new DomRegion (new DomLocation (m.Location.Row, m.Location.Column), typeStack.Peek ().BodyRegion.End);
				}
			}
Exemple #52
0
		/// Adds a signal handler to the class
		public void BindSignal (Stetic.Signal signal)
		{
			if (targetObject == null)
				return;

			IType cls = GetClass ();
			if (cls == null)
				return;
			
			if (FindSignalHandler (cls, signal) != null)
				return;

			var met = new DomMethod () {
				Name = signal.Handler,
				Modifiers = Modifiers.Protected,
				ReturnType = new DomReturnType (signal.SignalDescriptor.HandlerReturnTypeName)
			};
			foreach (Stetic.ParameterDescriptor pinfo in signal.SignalDescriptor.HandlerParameters)
				met.Add (new DomParameter () { Name = pinfo.Name, ReturnType = new DomReturnType (pinfo.TypeName) });
			
			CodeGenerationService.AddNewMember (cls, met);
		}
			public override void Visit (Operator o)
			{
				DomMethod method = new DomMethod ();
				method.Name = ConvertQuoted (o.MemberName.Name);
				method.Documentation = RetrieveDocumentation (o.Location.Row);
				method.Location = Convert (o.MemberName.Location);
				method.Modifiers = ConvertModifiers (o.ModFlags);
				if (o.Block != null) {
					var location = LocationsBag.GetMemberLocation (o);
					var region = ConvertRegion (location != null ? location[1] : o.Block.StartLocation, o.Block.EndLocation);
					if (location != null)
						region.Start = new DomLocation (region.Start.Line, region.Start.Column + 1);
					method.BodyRegion = region;
				}
				method.Modifiers = ConvertModifiers (o.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.SpecialName;
				method.ReturnType = ConvertReturnType (o.TypeName);
				AddAttributes (method, o.OptAttributes, o);
				AddParameter (method, o.ParameterInfo);
				AddExplicitInterfaces (method, o);
				
				method.DeclaringType = typeStack.Peek ();
				typeStack.Peek ().Add (method);
			}
		public static DomMethod ReadMethod (BinaryReader reader, INameDecoder nameTable, IDomObjectTable objectTable)
		{
			DomMethod result = new DomMethod ();
			ReadMemberInformation (reader, nameTable, objectTable, result);
			uint explicitInterfaces = ReadUInt (reader, 500);
			while (explicitInterfaces-- > 0) {
				result.AddExplicitInterface (ReadReturnType (reader, nameTable, objectTable));
			}
			
			result.BodyRegion = ReadRegion (reader, nameTable);
			result.ReturnType = ReadReturnType (reader, nameTable, objectTable);
			result.MethodModifier = (MethodModifier)reader.ReadInt32 ();
			
			uint arguments = ReadUInt (reader, 5000);
			while (arguments-- > 0) {
				result.Add (ReadParameter (reader, nameTable, objectTable));
			}
			arguments = ReadUInt (reader, 500);
			while (arguments-- > 0) {
				result.AddTypeParameter (ReadTypeParameter (reader, nameTable, objectTable));
			}
			return result;
		}
            void AppendModifiers(StringBuilder result, CSharpCodeGenerator.CodeGenerationOptions options, IMember member)
            {
                generator.AppendIndent(result);
                if (options.ExplicitDeclaration || options.ImplementingType.ClassType == ClassType.Interface)
                {
                    return;
                }
                result.Append(GetModifiers(options.ImplementingType, member));

                bool isFromInterface = false;

                if (member.DeclaringType != null && member.DeclaringType.ClassType == ClassType.Interface)
                {
                    isFromInterface = true;
                    if (options.ImplementingType != null)
                    {
                        foreach (IType type in options.ImplementingType.SourceProjectDom.GetInheritanceTree(options.ImplementingType))
                        {
                            if (type.ClassType == ClassType.Interface)
                            {
                                continue;
                            }
                            if (type.SearchMember(member.Name, true).Any(m => m.Name == member.Name && member.MemberType == m.MemberType && DomMethod.ParameterListEquals(member.Parameters, m.Parameters)))
                            {
                                isFromInterface = false;
                                break;
                            }
                        }
                    }
                }
                if (!isFromInterface && ((member.Modifiers & Modifiers.Virtual) == Modifiers.Virtual ||
                                         (member.Modifiers & Modifiers.Abstract) == Modifiers.Abstract))
                {
                    result.Append("override ");
                }
            }
		/// <summary>
		/// Create an IMember from a LanguageItem,
		/// using the source document to locate declaration bounds.
		/// </summary>
		/// <param name="pi">
		/// A <see cref="ProjectInformation"/> for the current project.
		/// </param>
		/// <param name="item">
		/// A <see cref="LanguageItem"/>: The item to convert.
		/// </param>
		/// <param name="contentLines">
		/// A <see cref="System.String[]"/>: The document in which item is defined.
		/// </param>
		static IMember LanguageItemToIMember (ProjectInformation pi, LanguageItem item, string[] contentLines)
		{
			if (item is Class || item is Structure) {
				DomType klass = new DomType (new CompilationUnit (item.File), ClassType.Class, item.Name, new DomLocation ((int)item.Line, 1), string.Empty, new DomRegion ((int)item.Line+1, FindFunctionEnd (contentLines, (int)item.Line-1)+2), new List<IMember> ());
				
				foreach (LanguageItem li in pi.AllItems ()) {
					if (klass.Equals (li.Parent) && FilePath.Equals (li.File, item.File)) {
						klass.Add (LanguageItemToIMember (pi, li, contentLines));
					}
				}
				return klass;
			}
			if (item is Enumeration) {
				return new DomType (new CompilationUnit (item.File), ClassType.Enum, item.Name, new DomLocation ((int)item.Line, 1), string.Empty, new DomRegion ((int)item.Line+1, (int)item.Line+1), new List<IMember> ());
			}
			if (item is Function) {
				DomMethod method = new DomMethod (item.Name, Modifiers.None, MethodModifier.None, new DomLocation ((int)item.Line, 1), new DomRegion ((int)item.Line+1, FindFunctionEnd (contentLines, (int)item.Line-1)+2), new DomReturnType ());
				Function function = (Function)item;
				Match match;
				bool abort = false;
				List<IParameter> parameters = new List<IParameter> ();
				
				foreach (string parameter in function.Parameters) {
					match = paramExpression.Match (parameter);
					if (null == match) {
						abort = true;
						break;
					}
					DomParameter p =  (new DomParameter (method, match.Groups["name"].Value,
					  new DomReturnType (string.Format ("{0}{1}{2}", match.Groups["type"].Value, match.Groups["subtype"].Value, match.Groups["array"].Value))));
					parameters.Add (p);
				}
				if (!abort)
					method.Add (parameters);
				return method;
			}
			if (item is Member) {
				return new DomField (item.Name, Modifiers.None, new DomLocation ((int)item.Line, 1), new DomReturnType ());
			}
			return null;
		}