public ElementReturnType(IProjectContent pc, IReturnType enumerableType)
		{
			if (pc == null)
				throw new ArgumentNullException("pc");
			this.enumerableType = enumerableType;
			this.pc = pc;
		}
Exemplo n.º 2
0
		void AddMethodsFromBaseType(List<IMethod> l, IReturnType baseType)
		{
			if (baseType != null) {
				foreach (IMethod m in baseType.GetMethods()) {
					if (m.IsConstructor)
						continue;
					
					bool ok = true;
					if (m.IsOverridable) {
						StringComparer comparer = m.DeclaringType.ProjectContent.Language.NameComparer;
						foreach (IMethod oldMethod in c.Methods) {
							if (comparer.Equals(oldMethod.Name, m.Name)) {
								if (m.IsStatic == oldMethod.IsStatic && object.Equals(m.ReturnType, oldMethod.ReturnType)) {
									if (DiffUtility.Compare(oldMethod.Parameters, m.Parameters) == 0) {
										ok = false;
										break;
									}
								}
							}
						}
					}
					if (ok)
						l.Add(m);
				}
			}
		}
		public static IMethodOrProperty FindOverload(IEnumerable<IMethodOrProperty> list,
		                                             IReturnType[] arguments,
		                                             bool allowAdditionalArguments,
		                                             bool substituteInferredTypes,
		                                             out bool acceptableMatch)
		{
			OverloadResolution or = new OverloadResolution();
			or.candidates = list.Select(m => new Candidate(m)).ToList();
			or.arguments = arguments;
			or.allowAdditionalArguments = allowAdditionalArguments;
			
			if (or.candidates.Count == 0)
				throw new ArgumentException("at least one candidate is required");
			
			MemberLookupHelper.Log("OverloadResolution");
			MemberLookupHelper.Log("  arguments = ", arguments);
			
			or.ConstructExpandedForms();
			or.InferTypeArguments();
			or.CheckApplicability();
			
			Candidate result = or.FindBestCandidate();
			MemberLookupHelper.Log("Overload resolution finished. Winning candidate = " + result);
			acceptableMatch = result.Status == CandidateStatus.Success;
			if (substituteInferredTypes)
				return result.Method;
			else
				return result.OriginalMethod;
		}
Exemplo n.º 4
0
		ResolveResult CreateResolveResult(IReturnType resolvedType)
		{
			if (resolvedType == null)
				return null;
			else
				return new ResolveResult(resolver.CallingClass, resolver.CallingMember, resolvedType);
		}
Exemplo n.º 5
0
		public DefaultParameter(IParameter p)
		{
			this.name = p.Name;
			this.region = p.Region;
			this.modifier = p.Modifiers;
			this.returnType = p.ReturnType;
		}
		protected bool ProvideContextCompletion(ITextEditor editor, IReturnType expected, char charTyped)
		{
			if (expected == null) return false;
			IClass c = expected.GetUnderlyingClass();
			if (c == null) return false;
			if (c.ClassType == ClassType.Enum) {
				CtrlSpaceCompletionItemProvider cdp = new NRefactoryCtrlSpaceCompletionItemProvider(languageProperties);
				var ctrlSpaceList = cdp.GenerateCompletionList(editor);
				if (ctrlSpaceList == null) return false;
				ContextCompletionItemList contextList = new ContextCompletionItemList();
				contextList.Items.AddRange(ctrlSpaceList.Items);
				contextList.activationKey = charTyped;
				foreach (CodeCompletionItem item in contextList.Items.OfType<CodeCompletionItem>()) {
					IClass itemClass = item.Entity as IClass;
					if (itemClass != null && c.FullyQualifiedName == itemClass.FullyQualifiedName && c.TypeParameters.Count == itemClass.TypeParameters.Count) {
						contextList.SuggestedItem = item;
						break;
					}
				}
				if (contextList.SuggestedItem != null) {
					if (charTyped != ' ') contextList.InsertSpace = true;
					editor.ShowCompletionWindow(contextList);
					return true;
				}
			}
			return false;
		}
Exemplo n.º 7
0
		void MakeTypeResult(IReturnType rt)
		{
			if (rt != null)
				resolveResult = new TypeResolveResult(callingClass, resolver.CallingMember, rt);
			else
				ClearResult();
		}
Exemplo n.º 8
0
		void MakeResult(IReturnType type)
		{
			if (type == null)
				ClearResult();
			else
				resolveResult = new ResolveResult(callingClass, resolver.CallingMember, type);
		}
		public EventHandlerCompletitionDataProvider(string expression, ResolveResult resolveResult)
		{
			this.expression = expression;
			this.resolveResult = resolveResult;
			this.resolvedReturnType = resolveResult.ResolvedType;
			this.resolvedClass = resolvedReturnType.GetUnderlyingClass();
		}
Exemplo n.º 10
0
 public DefaultField(IReturnType type, string name, ModifierEnum m, DomRegion region, IClass declaringType)
     : base(declaringType, name)
 {
     this.ReturnType = type;
     this.Region = region;
     this.Modifiers = m;
 }
Exemplo n.º 11
0
 public DefaultMethod(string name, IReturnType type, ModifierEnum m, DomRegion region, DomRegion bodyRegion, IClass declaringType)
     : base(declaringType, name)
 {
     this.ReturnType = type;
     this.Region     = region;
     this.BodyRegion = bodyRegion;
     Modifiers = m;
 }
Exemplo n.º 12
0
		void AddWebViewPageBaseClass(DefaultClass webViewPageClass, IReturnType modelType)
		{
			IClass webViewPageBaseClass = webViewPageClass.ProjectContent.GetClass("System.Web.Mvc.WebViewPage", 1);
			if (webViewPageBaseClass != null) {
				IReturnType returnType = GetWebViewPageBaseClassReturnType(webViewPageBaseClass, modelType);
				webViewPageClass.BaseTypes.Add(returnType);
			}
		}
 public SharpAssemblyParameter(SharpAssembly_ asm, string paramName, IReturnType type)
 {
     name = paramName;
     if (type.Name.EndsWith("&")) {
         modifier |= ParameterModifier.Ref;
     }
     returnType = type;
 }
Exemplo n.º 14
0
		/// <summary>
		/// Returns null if base type is not an interface.
		/// </summary>
		public static CodeInterface CreateFromBaseType(IProjectContent projectContent, IReturnType baseType)
		{
			IClass baseTypeClass = baseType.GetUnderlyingClass();
			if (baseTypeClass.ClassType == ClassType.Interface) {
				return new CodeInterface(projectContent, baseType, baseTypeClass);
			}
			return null;
		}
		public DefaultAttribute(IReturnType attributeType, AttributeTarget attributeTarget, IList<object> positionalArguments, IDictionary<string, object> namedArguments)
		{
			if (attributeType == null)
				throw new ArgumentNullException("attributeType");
			this.AttributeType = attributeType;
			this.AttributeTarget = attributeTarget;
			this.positionalArguments = positionalArguments ?? new List<object>();
			this.namedArguments = namedArguments ?? new SortedList<string, object>();
		}
		public ConstructedReturnType(IReturnType baseType, IList<IReturnType> typeArguments)
		{
			if (baseType == null)
				throw new ArgumentNullException("baseType");
			if (typeArguments == null)
				throw new ArgumentNullException("typeArguments");
			this.typeArguments = typeArguments;
			this.baseType = baseType;
		}
Exemplo n.º 17
0
		static NSObjectInfoService ()
		{
			string wrapperRootNamespace = "MonoTouch";
			string foundation = wrapperRootNamespace + ".Foundation";
			connectAttType = new DomReturnType (foundation, "ConnectAttribute");
			exportAttType = new DomReturnType (foundation, "ExportAttribute");
			registerAttType = new DomReturnType (foundation, "RegisterAttribute");
			modelAttType = new DomReturnType (foundation, "ModelAttribute");
			nsobjectType = new DomReturnType (foundation, "NSObject");
		}
        public static PersistentReturnType Resolve(IReturnType source, ITypeResolver typeResolver)
        {
            if (source == null) return null;

            PersistentReturnType rt = new PersistentReturnType ();
            rt.FullyQualifiedName = typeResolver.Resolve (source.FullyQualifiedName);
            rt.pointerNestingLevel = source.PointerNestingLevel;
            rt.arrayDimensions = source.ArrayDimensions;
            return rt;
        }
Exemplo n.º 19
0
		public DefaultEvent(string name, IReturnType type, ModifierEnum m, DomRegion region, DomRegion bodyRegion, IClass declaringType) : base(declaringType, name)
		{
			this.ReturnType = type;
			this.Region     = region;
			this.BodyRegion = bodyRegion;
			Modifiers       = (ModifierEnum)m;
			if (Modifiers == ModifierEnum.None) {
				Modifiers = ModifierEnum.Private;
			}
		}
Exemplo n.º 20
0
		public virtual IEnumerable<string> ResolvePossibleNamespaces (IReturnType returnType)
		{
			foreach (string ns in InternalResolvePossibleNamespaces (returnType)) {
				yield return ns;
			}
			foreach (ProjectDom refDom in References) {
				foreach (string ns in refDom.InternalResolvePossibleNamespaces (returnType)) {
					yield return ns;
				}
			}
		}
Exemplo n.º 21
0
		protected virtual IEnumerable<string> InternalResolvePossibleNamespaces (IReturnType returnType)
		{
			if (returnType == null) 
				yield break;
			
			foreach (IType type in Types) {
				if (type.DecoratedFullName == type.Namespace + "." + returnType.DecoratedFullName) {
					yield return type.Namespace;
				}
			}
		}
Exemplo n.º 22
0
		public void CreateAttribute(string fullName, string shortName)
		{
			var returnTypeHelper = new ReturnTypeHelper();
			returnTypeHelper.CreateReturnType(fullName);
			returnTypeHelper.AddShortName(shortName);
			AttributeType = returnTypeHelper.ReturnType;
			
			Attribute = MockRepository.GenerateStub<IAttribute>();
			Attribute.Stub(a => a.AttributeType).Return(AttributeType);
			Attribute.Stub(a => a.PositionalArguments).Return(PositionalArguments);
			Attribute.Stub(a => a.NamedArguments).Return(NamedArguments);
		}
		static bool CanCompareEqualityWithOperator(IReturnType type)
		{
			// return true for value types except float and double
			// return false for reference types except string.
			IClass c = type.GetUnderlyingClass();
			return c != null
				&& c.FullyQualifiedName != "System.Single"
				&& c.FullyQualifiedName != "System.Double"
				&& (c.ClassType == Dom.ClassType.Struct
				    || c.ClassType == Dom.ClassType.Enum
				    || c.FullyQualifiedName == "System.String");
		}
Exemplo n.º 24
0
		public ArrayReturnType(IProjectContent pc, IReturnType elementType, int dimensions)
		{
			if (pc == null)
				throw new ArgumentNullException("pc");
			if (dimensions <= 0)
				throw new ArgumentOutOfRangeException("dimensions", dimensions, "dimensions must be positive");
			if (elementType == null)
				throw new ArgumentNullException("elementType");
			this.pc = pc;
			this.elementType = elementType;
			this.dimensions = dimensions;
		}
Exemplo n.º 25
0
		public NSObjectInfoService (string wrapperRoot)
		{
			this.WrapperRoot = wrapperRoot;
			string foundation = wrapperRoot + ".Foundation";
			connectAttType = new DomReturnType (foundation, "ConnectAttribute");
			exportAttType = new DomReturnType (foundation, "ExportAttribute");
			iboutletAttType = new DomReturnType (foundation, "OutletAttribute");
			ibactionAttType = new DomReturnType (foundation, "ActionAttribute");
			registerAttType = new DomReturnType (foundation, "RegisterAttribute");
			modelAttType = new DomReturnType (foundation, "ModelAttribute");
			nsobjectType = new DomReturnType (foundation, "NSObject");
		}
Exemplo n.º 26
0
		TypeResolveResult CreateTypeResolveResult(IReturnType resolvedType)
		{
			if (resolvedType == null) {
				return null;
			} else {
				IReturnType rt = resolvedType;
				while (rt != null && rt.IsArrayReturnType) {
					rt = rt.CastToArrayReturnType().ArrayElementType;
				}
				IClass resolvedClass = rt != null ? rt.GetUnderlyingClass() : null;
				return new TypeResolveResult(resolver.CallingClass, resolver.CallingMember, resolvedType, resolvedClass);
			}
		}
Exemplo n.º 27
0
		public override IReturnType ResolveReturnType(IReturnType[] parameterTypes)
		{
			if (lambdaExpression == null)
				return ResolveReturnType();
			
			try {
				MemberLookupHelper.Log("LambdaReturnType: SetImplicitLambdaParameterTypes ", parameterTypes);
				resolver.SetImplicitLambdaParameterTypes(lambdaExpression, parameterTypes);
				return ResolveReturnType();
			} finally {
				resolver.UnsetImplicitLambdaParameterTypes(lambdaExpression);
			}
		}
Exemplo n.º 28
0
		/// <summary>
		/// Assigns a ranking score to each method in the <paramref name="list"/>.
		/// </summary>
		/// <param name="list">Link with the methods to check.<br/>
		/// <b>Generic methods in the input type are replaced by methods with have the types substituted!</b>
		/// </param>
		/// <param name="typeParameters">List with the type parameters passed to the method.
		/// Can be null (=no type parameters)</param>
		/// <param name="arguments">The types of the arguments passed to the method.
		/// A null return type means any argument type is allowed.</param>
		/// <param name="allowAdditionalArguments">Specifies whether the method can have
		/// more parameters than specified here. Useful for method insight scenarios.</param>
		/// <param name="acceptableMatch">Out parameter that is true when the best ranked
		/// method is acceptable for a method call (no invalid casts)</param>
		/// <returns>Integer array. Each value in the array </returns>
		public static int[] RankOverloads(IList<IMethod> list,
		                                  IReturnType[] typeParameters,
		                                  IReturnType[] arguments,
		                                  bool allowAdditionalArguments,
		                                  out bool acceptableMatch)
		{
			acceptableMatch = false;
			if (list.Count == 0) return new int[] {};
			
			List<IMethodOrProperty> l2 = new List<IMethodOrProperty>(list.Count);
			IReturnType[][] inferredTypeParameters;
			// See ECMA-334, § 14.3
			
			// If type parameters are specified, remove all methods from the list that do not
			// use the specified number of parameters.
			if (typeParameters != null && typeParameters.Length > 0) {
				for (int i = 0; i < list.Count; i++) {
					IMethod m = list[i];
					if (m.TypeParameters.Count == typeParameters.Length) {
						m = (IMethod)m.Clone();
						m.ReturnType = ConstructedReturnType.TranslateType(m.ReturnType, typeParameters, true);
						for (int j = 0; j < m.Parameters.Count; ++j) {
							m.Parameters[j].ReturnType = ConstructedReturnType.TranslateType(m.Parameters[j].ReturnType, typeParameters, true);
						}
						list[i] = m;
						l2.Add(m);
					}
				}
				
				int[] innerRanking = RankOverloads(l2, arguments, allowAdditionalArguments, out acceptableMatch, out inferredTypeParameters);
				int[] ranking = new int[list.Count];
				int innerIndex = 0;
				for (int i = 0; i < ranking.Length; i++) {
					if (list[i].TypeParameters.Count == typeParameters.Length) {
						ranking[i] = innerRanking[innerIndex++];
					} else {
						ranking[i] = 0;
					}
				}
				return ranking;
			} else {
				// Note that when there are no type parameters, methods having type parameters
				// are not removed, since the type inference process might be able to infer the
				// type arguments.
				foreach (IMethod m in list) l2.Add(m);
				
				int[] ranking = RankOverloads(l2, arguments, allowAdditionalArguments, out acceptableMatch, out inferredTypeParameters);
				ApplyInferredTypeParameters(list, inferredTypeParameters);
				return ranking;
			}
		}
Exemplo n.º 29
0
		public static IMethod FindOverload(IList<IMethod> methods, IReturnType[] typeParameters, IReturnType[] arguments)
		{
			if (methods.Count == 0)
				return null;
			bool tmp;
			int[] ranking = RankOverloads(methods, typeParameters, arguments, false, out tmp);
			int bestRanking = -1;
			int best = 0;
			for (int i = 0; i < ranking.Length; i++) {
				if (ranking[i] > bestRanking) {
					bestRanking = ranking[i];
					best = i;
				}
			}
			return methods[best];
		}
Exemplo n.º 30
0
			/// <summary>
			/// Gets whether this type parameter occurs in the specified return type.
			/// </summary>
			public bool OccursIn(IReturnType rt)
			{
				ArrayReturnType art = rt.CastToArrayReturnType();
				if (art != null) {
					return OccursIn(art.ArrayElementType);
				}
				ConstructedReturnType crt = rt.CastToConstructedReturnType();
				if (crt != null) {
					return crt.TypeArguments.Any(ta => OccursIn(ta));
				}
				GenericReturnType grt = rt.CastToGenericReturnType();
				if (grt != null) {
					return this.TypeParameter.Equals(grt.TypeParameter);
				}
				return false;
			}
Exemplo n.º 31
0
 public virtual IType SearchType(ICompilationUnit unit, IType callingClass, DomLocation lookupLocation, IReturnType returnType)
 {
     if (returnType == null)
     {
         return(null);
     }
     return(SearchType(unit, callingClass, lookupLocation, returnType.DecoratedFullName, returnType.GenericArguments));
 }
Exemplo n.º 32
0
        IType SearchType(IUsing iusing, string partitialTypeName, IList <IReturnType> genericArguments, bool caseSensitive)
        {
            IType c = GetType(partitialTypeName, genericArguments, false, caseSensitive);

            if (c != null)
            {
                return(c);
            }

            foreach (string str in iusing.Namespaces)
            {
                string possibleType = String.Concat(str, ".", partitialTypeName);
                c = GetType(possibleType, genericArguments, false, caseSensitive);
                if (c != null)
                {
                    return(c);
                }
            }

            IReturnType alias;

            // search class in partial namespaces
            if (iusing.Aliases.TryGetValue("", out alias))
            {
                string declaringNamespace = alias.FullName;
                while (declaringNamespace.Length > 0)
                {
                    string className = String.Concat(declaringNamespace, ".", partitialTypeName);
                    c = GetType(className, genericArguments, false, caseSensitive);
                    if (c != null)
                    {
                        return(c);
                    }
                    int index = declaringNamespace.IndexOf('.');
                    if (index > 0)
                    {
                        declaringNamespace = declaringNamespace.Substring(0, index);
                    }
                    else
                    {
                        break;
                    }
                }
            }

            foreach (string aliasString in iusing.Aliases.Keys)
            {
                if (caseSensitive ? partitialTypeName.StartsWith(aliasString) : partitialTypeName.ToLower().StartsWith(aliasString.ToLower()))
                {
                    string className = null;
                    if (aliasString.Length > 0)
                    {
                        IReturnType rt = iusing.Aliases [aliasString];
                        className = String.Concat(rt.FullName, partitialTypeName.Remove(0, aliasString.Length));
                        c         = GetType(className, genericArguments, false, caseSensitive);
                        if (c != null)
                        {
                            return(c);
                        }
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Gets all types the specified type inherits from (all classes and interfaces).
        /// Unlike the class inheritance tree, this method takes care of type arguments and calculates the type
        /// arguments that are passed to base classes.
        /// </summary>
        public static IEnumerable <IReturnType> GetTypeInheritanceTree(IReturnType typeToListInheritanceTreeFor)
        {
            if (typeToListInheritanceTreeFor == null)
            {
                throw new ArgumentNullException("typeToListInheritanceTreeFor");
            }

            lock (getTypeInheritanceTreeCache) {
                IEnumerable <IReturnType> result;
                if (getTypeInheritanceTreeCache.TryGetValue(typeToListInheritanceTreeFor, out result))
                {
                    return(result);
                }
            }

            IClass classToListInheritanceTreeFor = typeToListInheritanceTreeFor.GetUnderlyingClass();

            if (classToListInheritanceTreeFor == null)
            {
                return new IReturnType[] { typeToListInheritanceTreeFor }
            }
            ;

            if (typeToListInheritanceTreeFor.IsArrayReturnType)
            {
                IReturnType elementType = typeToListInheritanceTreeFor.CastToArrayReturnType().ArrayElementType;

                List <IReturnType> resultList = new List <IReturnType>();
                resultList.Add(typeToListInheritanceTreeFor);
                resultList.AddRange(GetTypeInheritanceTree(
                                        new ConstructedReturnType(
                                            classToListInheritanceTreeFor.ProjectContent.GetClass("System.Collections.Generic.IList", 1).DefaultReturnType,
                                            new IReturnType[] { elementType }
                                            )
                                        ));
                resultList.Add(classToListInheritanceTreeFor.ProjectContent.GetClass("System.Collections.IList", 0).DefaultReturnType);
                resultList.Add(classToListInheritanceTreeFor.ProjectContent.GetClass("System.Collections.ICollection", 0).DefaultReturnType);
                // non-generic IEnumerable is already added by generic IEnumerable
                return(resultList);
            }

            HashSet <IReturnType> visitedSet   = new HashSet <IReturnType>();
            List <IReturnType>    visitedList  = new List <IReturnType>();
            Queue <IReturnType>   typesToVisit = new Queue <IReturnType>();
            bool enqueuedLastBaseType          = false;

            IReturnType currentType  = typeToListInheritanceTreeFor;
            IClass      currentClass = classToListInheritanceTreeFor;
            IReturnType nextType;

            do
            {
                if (currentClass != null)
                {
                    if (visitedSet.Add(currentType))
                    {
                        visitedList.Add(currentType);
                        foreach (IReturnType type in currentClass.BaseTypes)
                        {
                            typesToVisit.Enqueue(TranslateIfRequired(currentType, type));
                        }
                    }
                }
                if (typesToVisit.Count > 0)
                {
                    nextType = typesToVisit.Dequeue();
                }
                else
                {
                    nextType             = enqueuedLastBaseType ? null : DefaultClass.GetBaseTypeByClassType(classToListInheritanceTreeFor);
                    enqueuedLastBaseType = true;
                }
                if (nextType != null)
                {
                    currentType  = nextType;
                    currentClass = nextType.GetUnderlyingClass();
                }
            } while (nextType != null);
            lock (getTypeInheritanceTreeCache) {
                if (getTypeInheritanceTreeCache.Count == 0)
                {
                    DomCache.RegisterForClear(ClearGetTypeInheritanceTreeCache);
                }
                getTypeInheritanceTreeCache[typeToListInheritanceTreeFor] = visitedList;
            }
            return(visitedList);
        }
        public override object VisitTypeDeclaration(NRefactoryAST.TypeDeclaration typeDeclaration, object data)
        {
            DomRegion region     = GetRegion(typeDeclaration.StartLocation, typeDeclaration.EndLocation);
            DomRegion bodyRegion = GetRegion(typeDeclaration.BodyStartLocation, typeDeclaration.EndLocation);

            DefaultClass c = new DefaultClass(cu, TranslateClassType(typeDeclaration.Type), ConvertTypeModifier(typeDeclaration.Modifier), region, GetCurrentClass());

            if (c.IsStatic)
            {
                // static classes are also abstract and sealed at the same time
                c.Modifiers |= ModifierEnum.Abstract | ModifierEnum.Sealed;
            }
            c.BodyRegion = bodyRegion;
            ConvertAttributes(typeDeclaration, c);
            c.Documentation = GetDocumentation(region.BeginLine, typeDeclaration.Attributes);

            DefaultClass outerClass = GetCurrentClass();

            if (outerClass != null)
            {
                outerClass.InnerClasses.Add(c);
                c.FullyQualifiedName = outerClass.FullyQualifiedName + '.' + typeDeclaration.Name;
            }
            else
            {
                c.FullyQualifiedName = PrependCurrentNamespace(typeDeclaration.Name);
                cu.Classes.Add(c);
            }
            c.UsingScope = currentNamespace;
            currentClass.Push(c);

            ConvertTemplates(outerClass, typeDeclaration.Templates, c);             // resolve constrains in context of the class
            // templates must be converted before base types because base types may refer to generic types

            if (c.ClassType != ClassType.Enum && typeDeclaration.BaseTypes != null)
            {
                foreach (NRefactoryAST.TypeReference type in typeDeclaration.BaseTypes)
                {
                    IReturnType rt = CreateReturnType(type, null, TypeVisitor.ReturnTypeOptions.BaseTypeReference);
                    if (rt != null)
                    {
                        c.BaseTypes.Add(rt);
                    }
                }
            }

            object ret = typeDeclaration.AcceptChildren(this, data);

            currentClass.Pop();

            if (c.ClassType == ClassType.Module)
            {
                foreach (DefaultField f in c.Fields)
                {
                    f.Modifiers |= ModifierEnum.Static;
                }
                foreach (DefaultMethod m in c.Methods)
                {
                    m.Modifiers |= ModifierEnum.Static;
                }
                foreach (DefaultProperty p in c.Properties)
                {
                    p.Modifiers |= ModifierEnum.Static;
                }
                foreach (DefaultEvent e in c.Events)
                {
                    e.Modifiers |= ModifierEnum.Static;
                }
            }

            mapType(typeDeclaration, c);

            return(ret);
        }
Exemplo n.º 35
0
 public override bool Equals(IReturnType o)
 {
     return(o is NullReturnType);
 }
Exemplo n.º 36
0
        /// <remarks>
        /// does the dynamic lookup for the typeName
        /// </remarks>
        public IReturnType DynamicLookup(string typeName)
        {
//			Console.WriteLine("starting dynamic lookup");
//			Console.WriteLine("name == " + typeName);

            // try if it exists a variable named typeName
            ReturnType variable = SearchVariable(typeName);

            if (variable != null)
            {
                showStatic = false;
                return(variable);
            }
//			Console.WriteLine("No Variable found");

            if (callingClass == null)
            {
                return(null);
            }
            //// somehow search in callingClass fields is not returning anything, so I am searching here once again
            foreach (IField f in callingClass.Fields)
            {
                if (f.Name == typeName)
                {
//					Console.WriteLine("Field found " + f.Name);
                    return(f.ReturnType);
                }
            }
            //// end of mod for search in Fields

            // try if typeName is a method parameter
            IReturnType p = SearchMethodParameter(typeName);

            if (p != null)
            {
//				Console.WriteLine("MethodParameter Found");
                showStatic = false;
                return(p);
            }
//			Console.WriteLine("No Parameter found");

            // check if typeName == value in set method of a property
            if (typeName == "value")
            {
                p = SearchProperty();
                if (p != null)
                {
                    showStatic = false;
                    return(p);
                }
            }
//			Console.WriteLine("No Property found");

            // try if there exists a nonstatic member named typeName
            showStatic = false;
            IReturnType t = SearchMember(callingClass == null ? null : new ReturnType(callingClass.FullyQualifiedName), typeName);

            if (t != null)
            {
                return(t);
            }
//			Console.WriteLine("No nonstatic member found");

            // try if there exists a static member named typeName
            showStatic = true;
            t          = SearchMember(callingClass == null ? null : new ReturnType(callingClass.FullyQualifiedName), typeName);
            if (t != null)
            {
                showStatic = false;
                return(t);
            }
//			Console.WriteLine("No static member found");

            // try if there exists a static member in outer classes named typeName
            ClassCollection classes = GetOuterClasses();

            foreach (IClass c in GetOuterClasses())
            {
                t = SearchMember(callingClass == null ? null : new ReturnType(c.FullyQualifiedName), typeName);
                if (t != null)
                {
                    showStatic = false;
                    return(t);
                }
            }
//			Console.WriteLine("No static member in outer classes found");
//			Console.WriteLine("DynamicLookUp resultless");
            return(null);
        }
Exemplo n.º 37
0
        public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            if (resolver.Language == SupportedLanguage.CSharp && resolver.CallingClass != null)
            {
                if (invocationExpression.TargetObject is ThisReferenceExpression)
                {
                    // call to constructor
                    return(ResolveConstructorOverload(resolver.CallingClass, invocationExpression.Arguments));
                }
                else if (invocationExpression.TargetObject is BaseReferenceExpression)
                {
                    return(ResolveConstructorOverload(resolver.CallingClass.BaseType, invocationExpression.Arguments));
                }
            }

            ResolveResult      rr      = Resolve(invocationExpression.TargetObject);
            MixedResolveResult mixedRR = rr as MixedResolveResult;

            if (mixedRR != null)
            {
                rr = mixedRR.PrimaryResult;
            }
            MethodGroupResolveResult mgrr = rr as MethodGroupResolveResult;

            if (mgrr != null)
            {
                if (resolver.Language == SupportedLanguage.VBNet && mgrr.Methods.All(mg => mg.Count == 0))
                {
                    return(CreateMemberResolveResult(GetVisualBasicIndexer(invocationExpression)));
                }

                IReturnType[] argumentTypes = invocationExpression.Arguments.Select <Expression, IReturnType>(ResolveType).ToArray();

                MemberResolveResult firstResult = null;
                foreach (MethodGroup methodGroup in mgrr.Methods)
                {
                    bool    resultIsAcceptable;
                    IMethod method;
                    if (methodGroup.IsExtensionMethodGroup)
                    {
                        IReturnType[] extendedTypes = new IReturnType[argumentTypes.Length + 1];
                        extendedTypes[0] = mgrr.ContainingType;
                        argumentTypes.CopyTo(extendedTypes, 1);
                        method = MemberLookupHelper.FindOverload(methodGroup, extendedTypes, out resultIsAcceptable);
                    }
                    else
                    {
                        method = MemberLookupHelper.FindOverload(methodGroup, argumentTypes, out resultIsAcceptable);
                    }
                    MemberResolveResult result = CreateMemberResolveResult(method);
                    if (result != null && methodGroup.IsExtensionMethodGroup)
                    {
                        result.IsExtensionMethodCall = true;
                    }
                    if (resultIsAcceptable)
                    {
                        return(result);
                    }
                    if (firstResult == null)
                    {
                        firstResult = result;
                    }
                }
                if (firstResult != null)
                {
                    return(firstResult);
                }
                else
                {
                    return(FallbackResolveMethod(invocationExpression, mgrr, argumentTypes));
                }
            }
            else if (rr != null && rr.ResolvedType != null)
            {
                IClass c = rr.ResolvedType.GetUnderlyingClass();
                if (c != null && c.ClassType == ClassType.Delegate)
                {
                    // We don't want to show "System.EventHandler.Invoke" in the tooltip
                    // of "EventCall(this, EventArgs.Empty)", we just show the event/delegate for now
                    // but for DelegateCall(params).* completion, we use the delegate's
                    // return type instead of the delegate type itself

                    IMethod method = rr.ResolvedType.GetMethods().FirstOrDefault(innerMethod => innerMethod.Name == "Invoke");
                    if (method != null)
                    {
                        return(new DelegateCallResolveResult(rr, method));
                    }
                }
            }
            if (resolver.Language == SupportedLanguage.VBNet)
            {
                return(CreateMemberResolveResult(GetVisualBasicIndexer(invocationExpression)));
            }
            return(null);
        }
 bool IsApplicable(IReturnType argument, IReturnType expected)
 {
     return(MemberLookupHelper.IsApplicable(argument, expected, methodForGenericCalls));
 }
Exemplo n.º 39
0
 protected TypeReference ConvertType(IReturnType type)
 {
     return(CodeGenerator.ConvertType(type, classFinderContext));
 }
Exemplo n.º 40
0
 public void Add(string name, IReturnType type)
 {
     typeTable.Add(name, type);
 }
Exemplo n.º 41
0
        public static DomType CreateDelegate(ICompilationUnit compilationUnit, string name, DomLocation location, IReturnType type, IEnumerable <IParameter> parameters)
        {
            DomType result = new DomType();

            result.compilationUnit = compilationUnit;
            result.Name            = name;
            result.classType       = MonoDevelop.Projects.Dom.ClassType.Delegate;
            DomMethod delegateMethod = new DomMethod("Invoke", Modifiers.None, MethodModifier.None, location, DomRegion.Empty, type);

            delegateMethod.Add(parameters);
            result.Add(delegateMethod);
            return(result);
        }
Exemplo n.º 42
0
 public static ICSharpCode.NRefactory.CSharp.AstType ShortenTypeName(MonoDevelop.Ide.Gui.Document doc, IReturnType fullyQualifiedTypeName)
 {
     return(doc.ParsedDocument.CompilationUnit.ShortenTypeName(fullyQualifiedTypeName, doc.Editor.Caret.Line, doc.Editor.Caret.Column).ConvertToTypeReference());
 }
Exemplo n.º 43
0
        public override object VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, object data)
        {
            IReturnType left   = GetTypeSafe(binaryOperatorExpression.Left);
            IReturnType right  = GetTypeSafe(binaryOperatorExpression.Right);
            string      opName = GetOperatorName(binaryOperatorExpression.Op);

            if (!String.IsNullOrEmpty(opName))
            {
                IType   leftType          = this.resolver.Dom.GetType(left);
                int     leftOperatorLevel = 0;
                IMethod leftOperator      = leftType != null?FindOperator(leftType, opName, out leftOperatorLevel) : null;

                IType   rightType          = this.resolver.Dom.GetType(right);
                int     rightOperatorLevel = 0;
                IMethod rightOperator      = rightType != null?FindOperator(rightType, opName, out rightOperatorLevel) : null;

                if (leftOperator != null && rightOperator != null)
                {
                    if (leftOperatorLevel < rightOperatorLevel)
                    {
                        return(CreateResult(leftOperator.ReturnType));
                    }
                    return(CreateResult(rightOperator.ReturnType));
                }
                if (leftOperator != null)
                {
                    return(CreateResult(leftOperator.ReturnType));
                }
                if (rightOperator != null)
                {
                    return(CreateResult(rightOperator.ReturnType));
                }
            }

            switch (binaryOperatorExpression.Op)
            {
            case BinaryOperatorType.Equality:
            case BinaryOperatorType.InEquality:
            case BinaryOperatorType.ReferenceEquality:
            case BinaryOperatorType.ReferenceInequality:
            case BinaryOperatorType.LogicalAnd:
            case BinaryOperatorType.LogicalOr:
            case BinaryOperatorType.LessThan:
            case BinaryOperatorType.LessThanOrEqual:
            case BinaryOperatorType.GreaterThan:
            case BinaryOperatorType.GreaterThanOrEqual:
                return(CreateResult(typeof(bool).FullName));

            case BinaryOperatorType.NullCoalescing:
                return(Resolve(binaryOperatorExpression.Left));

            // vb operators
            case BinaryOperatorType.DivideInteger:
                return(CreateResult(typeof(int).FullName));

            case BinaryOperatorType.Concat:
                return(CreateResult(typeof(string).FullName));

            default:
                return(CreateResult(GetCommonType(left,
                                                  right).FullName));
            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// Gets which function member is better. (§ 14.4.2.2)
        /// </summary>
        /// <returns>0 if neither method is better. 1 if c1 is better. 2 if c2 is better.</returns>
        int GetBetterFunctionMember(Candidate c1, Candidate c2)
        {
            int  length = Math.Min(Math.Min(c1.Parameters.Count, c2.Parameters.Count), arguments.Count);
            bool foundBetterParamIn1 = false;
            bool foundBetterParamIn2 = false;

            for (int i = 0; i < length; i++)
            {
                if (arguments[i] == null)
                {
                    continue;
                }
                int res = MemberLookupHelper.GetBetterConversion(arguments[i], c1.Parameters[i].ReturnType, c2.Parameters[i].ReturnType);
                if (res == 1)
                {
                    foundBetterParamIn1 = true;
                }
                if (res == 2)
                {
                    foundBetterParamIn2 = true;
                }
            }
            if (foundBetterParamIn1 && !foundBetterParamIn2)
            {
                return(1);
            }
            if (foundBetterParamIn2 && !foundBetterParamIn1)
            {
                return(2);
            }
            if (foundBetterParamIn1 && foundBetterParamIn2)
            {
                return(0);                // ambigous
            }
            // If none conversion is better than any other, it is possible that the
            // expanded parameter lists are the same:
            for (int i = 0; i < length; i++)
            {
                if (!object.Equals(c1.Parameters[i].ReturnType, c2.Parameters[i].ReturnType))
                {
                    // if expanded parameters are not the same, neither function member is better
                    return(0);
                }
            }

            // the expanded parameters are the same, apply the tie-breaking rules from the spec:

            // if one method is generic and the other non-generic, the non-generic is better
            bool m1IsGeneric = c1.TypeParameterCount > 0;
            bool m2IsGeneric = c2.TypeParameterCount > 0;

            if (m1IsGeneric && !m2IsGeneric)
            {
                return(2);
            }
            if (m2IsGeneric && !m1IsGeneric)
            {
                return(1);
            }

            // for params parameters: non-expanded calls are better
            if (c1.IsExpanded && !c2.IsExpanded)
            {
                return(2);
            }
            if (c2.IsExpanded && !c1.IsExpanded)
            {
                return(1);
            }

            // if the number of parameters is different, the one with more parameters is better
            // this occurs when only when both methods are expanded
            if (c1.OriginalMethod.Parameters.Count > c2.OriginalMethod.Parameters.Count)
            {
                return(1);
            }
            if (c2.OriginalMethod.Parameters.Count > c1.OriginalMethod.Parameters.Count)
            {
                return(2);
            }

            IReturnType[] m1ParamTypes = new IReturnType[c1.Parameters.Count];
            IReturnType[] m2ParamTypes = new IReturnType[c2.Parameters.Count];
            for (int i = 0; i < m1ParamTypes.Length; i++)
            {
                m1ParamTypes[i] = c1.Parameters[i].ReturnType;
                m2ParamTypes[i] = c2.Parameters[i].ReturnType;
            }
            return(GetMoreSpecific(m1ParamTypes, m2ParamTypes));
        }
Exemplo n.º 45
0
 public static bool Equals(IReturnType rt1, IReturnType rt2)
 {
     return(rt1.FullyQualifiedName == rt2.FullyQualifiedName && rt1.TypeParameterCount == rt2.TypeParameterCount);
 }
 ConstructedReturnType EnumerableOf(IReturnType element)
 {
     return(new ConstructedReturnType(EnumerableClass.DefaultReturnType, new IReturnType[] { element }));
 }
Exemplo n.º 47
0
        public ResolveResult Resolve(IParserContext parserService, string expression, int caretLineNumber, int caretColumn, string fileName, string fileContent)
        {
            Console.WriteLine("Start Resolving");
            if (expression == null)
            {
                return(null);
            }
            expression = expression.TrimStart(null);
            if (expression == "")
            {
                return(null);
            }
            if (expression.StartsWith("using "))
            {
                // expression[expression.Length - 1] != '.'
                // the period that causes this Resove() is not part of the expression
                if (expression[expression.Length - 1] == '.')
                {
                    return(null);
                }
                int i;
                for (i = expression.Length - 1; i >= 0; --i)
                {
                    if (!(Char.IsLetterOrDigit(expression[i]) || expression[i] == '_' || expression[i] == '.'))
                    {
                        break;
                    }
                }
                // no Identifier before the period
                if (i == expression.Length - 1)
                {
                    return(null);
                }
                string t = expression.Substring(i + 1);
//				Console.WriteLine("in Using Statement");
                string[] namespaces = parserService.GetNamespaceList(t);
                if (namespaces == null || namespaces.Length <= 0)
                {
                    return(null);
                }
                return(new ResolveResult(namespaces));
            }

            Console.WriteLine("Not in Using");
            this.caretLine   = caretLineNumber;
            this.caretColumn = caretColumn;

            this.parserService = parserService;
            IParseInformation parseInfo = parserService.GetParseInformation(fileName);

            JRefactory.Parser.AST.CompilationUnit fileCompilationUnit = parseInfo.MostRecentCompilationUnit.Tag as JRefactory.Parser.AST.CompilationUnit;
            if (fileCompilationUnit == null)
            {
//				JRefactory.Parser.Parser fileParser = new JRefactory.Parser.Parser();
//				fileParser.Parse(new Lexer(new StringReader(fileContent)));
                Console.WriteLine("!Warning: no parseinformation!");
                return(null);
            }

            /*
             * //// try to find last expression in original string, it could be like " if (act!=null) act"
             * //// in this case only "act" should be parsed as expression
             * !!is so!! don't change things that work
             * Expression expr=null;	// tentative expression
             * Lexer l=null;
             * JRefactory.Parser.Parser p = new JRefactory.Parser.Parser();
             * while (expression.Length > 0) {
             *      l = new Lexer(new StringReader(expression));
             *      expr = p.ParseExpression(l);
             *      if (l.LookAhead.val != "" && expression.LastIndexOf(l.LookAhead.val) >= 0) {
             *              if (expression.Substring(expression.LastIndexOf(l.LookAhead.val) + l.LookAhead.val.Length).Length > 0)
             *                      expression=expression.Substring(expression.LastIndexOf(l.LookAhead.val) + l.LookAhead.val.Length).Trim();
             *              else {
             *                      expression=l.LookAhead.val.Trim();
             *                      l=new Lexer(new StringReader(expression));
             *                      expr=p.ParseExpression(l);
             *                      break;
             *              }
             *      } else {
             *              if (l.Token.val!="" || expr!=null) break;
             *      }
             * }
             * //// here last subexpression should be fixed in expr
             * if it should be changed in expressionfinder don't fix it here
             */
            JRefactory.Parser.Parser p = new JRefactory.Parser.Parser();
            Lexer      l    = new Lexer(new StringReader(expression));
            Expression expr = p.ParseExpression(l);

            if (expr == null)
            {
                return(null);
            }
            lookupTableVisitor = new LookupTableVisitor();
            lookupTableVisitor.Visit(fileCompilationUnit, null);

            TypeVisitor typeVisitor = new TypeVisitor(this);

            JavaVisitor cSharpVisitor = new JavaVisitor();

            cu = (ICompilationUnit)cSharpVisitor.Visit(fileCompilationUnit, null);
            if (cu != null)
            {
                callingClass = GetInnermostClass();
                //Console.WriteLine("CallingClass is " + callingClass == null ? "null" : callingClass.Name);
            }
            //Console.WriteLine("expression = " + expr.ToString());
            IReturnType type = expr.AcceptVisitor(typeVisitor, null) as IReturnType;

            //Console.WriteLine("type visited");
            if (type == null || type.PointerNestingLevel != 0)
            {
//				Console.WriteLine("Type == null || type.PointerNestingLevel != 0");
                if (type != null)
                {
                    //Console.WriteLine("PointerNestingLevel is " + type.PointerNestingLevel);
                }
                else
                {
                    //Console.WriteLine("Type == null");
                }
                //// when type is null might be file needs to be reparsed - some vars were lost
                fileCompilationUnit = parserService.ParseFile(fileName, fileContent).MostRecentCompilationUnit.Tag
                                      as JRefactory.Parser.AST.CompilationUnit;
                lookupTableVisitor.Visit(fileCompilationUnit, null);
                cu = (ICompilationUnit)cSharpVisitor.Visit(fileCompilationUnit, null);
                if (cu != null)
                {
                    callingClass = GetInnermostClass();
                }
                type = expr.AcceptVisitor(typeVisitor, null) as IReturnType;
                if (type == null)
                {
                    return(null);
                }
            }
            if (type.ArrayDimensions != null && type.ArrayDimensions.Length > 0)
            {
                type = new ReturnType("System.Array");
            }
            Console.WriteLine("Here: Type is " + type.FullyQualifiedName);
            IClass returnClass = SearchType(type.FullyQualifiedName, cu);

            if (returnClass == null)
            {
                // Try if type is Namespace:
                string n = SearchNamespace(type.FullyQualifiedName, cu);
                if (n == null)
                {
                    return(null);
                }
                ArrayList content = parserService.GetNamespaceContents(n);
                ArrayList classes = new ArrayList();
                for (int i = 0; i < content.Count; ++i)
                {
                    if (content[i] is IClass)
                    {
                        classes.Add((IClass)content[i]);
                    }
                }
                string[] namespaces = parserService.GetNamespaceList(n);
                return(new ResolveResult(namespaces, classes));
            }
            Console.WriteLine("Returning Result!");
            return(new ResolveResult(returnClass, ListMembers(new ArrayList(), returnClass)));
        }
 ConstructedReturnType ListOf(IReturnType element)
 {
     return(new ConstructedReturnType(msc.GetClass("System.Collections.Generic.List", 1).DefaultReturnType, new IReturnType[] { element }));
 }
Exemplo n.º 49
0
 public ArrayIndexer(IReturnType elementType, IClass systemArray)
     : base("Indexer", elementType, ModifierEnum.Public, DomRegion.Empty, DomRegion.Empty, systemArray)
 {
     IsIndexer = true;
 }
        public void TypeParameterPassedToBaseClassTestString()
        {
            IReturnType res = MemberLookupHelper.GetTypeParameterPassedToBaseClass(msc.SystemTypes.String, EnumerableClass, 0);

            Assert.AreEqual("System.Char", res.FullyQualifiedName);
        }
Exemplo n.º 51
0
        // no methods or indexer
        public IReturnType SearchMember(IReturnType type, string memberName)
        {
            if (type == null || memberName == null || memberName == "")
            {
                return(null);
            }
//			Console.WriteLine("searching member {0} in {1}", memberName, type.Name);
            IClass curType = SearchType(type.FullyQualifiedName, cu);

            if (curType == null)
            {
//				Console.WriteLine("Type not found in SearchMember");
                return(null);
            }
            if (type.PointerNestingLevel != 0)
            {
                return(null);
            }
            if (type.ArrayDimensions != null && type.ArrayDimensions.Length > 0)
            {
                curType = SearchType("System.Array", null);
            }
            if (curType.ClassType == ClassType.Enum)
            {
                foreach (IField f in curType.Fields)
                {
                    if (f.Name == memberName && MustBeShowen(curType, f))
                    {
                        showStatic = false;
                        return(type);                        // enum members have the type of the enum
                    }
                }
            }
            if (showStatic)
            {
//				Console.WriteLine("showStatic == true");
                foreach (IClass c in curType.InnerClasses)
                {
                    if (c.Name == memberName && IsAccessible(curType, c))
                    {
                        return(new ReturnType(c.FullyQualifiedName));
                    }
                }
            }
//			Console.WriteLine("#Properties " + curType.Properties.Count);
            foreach (IProperty p in curType.Properties)
            {
//				Console.WriteLine("checke Property " + p.Name);
//				Console.WriteLine("member name " + memberName);
                if (p.Name == memberName && MustBeShowen(curType, p))
                {
//					Console.WriteLine("Property found " + p.Name);
                    showStatic = false;
                    return(p.ReturnType);
                }
            }
            foreach (IField f in curType.Fields)
            {
//				Console.WriteLine("checke Feld " + f.Name);
//				Console.WriteLine("member name " + memberName);
                if (f.Name == memberName && MustBeShowen(curType, f))
                {
//					Console.WriteLine("Field found " + f.Name);
                    showStatic = false;
                    return(f.ReturnType);
                }
            }
            foreach (IEvent e in curType.Events)
            {
                if (e.Name == memberName && MustBeShowen(curType, e))
                {
                    showStatic = false;
                    return(e.ReturnType);
                }
            }
            foreach (string baseType in curType.BaseTypes)
            {
                IClass c = SearchType(baseType, curType.CompilationUnit);
                if (c != null)
                {
                    IReturnType erg = SearchMember(new ReturnType(c.FullyQualifiedName), memberName);
                    if (erg != null)
                    {
                        return(erg);
                    }
                }
            }
            return(null);
        }
        /// <summary>
        /// Tests if an implicit conversion exists from "from" to "to".
        /// Conversions from concrete types to generic types are only allowed when the generic type belongs to the
        /// method "allowGenericTargetsOnThisMethod".
        /// </summary>
        static bool ConversionExistsInternal(IReturnType from, IReturnType to, IMethod allowGenericTargetsOnThisMethod)
        {
            // ECMA-334, § 13.1 Implicit conversions

            // Identity conversion:
            if (from == to)
            {
                return(true);
            }
            if (from == null || to == null)
            {
                return(false);
            }
            if (from.Equals(to))
            {
                return(true);
            }

            bool fromIsDefault = from.IsDefaultReturnType;
            bool toIsDefault   = to.IsDefaultReturnType;

            if (fromIsDefault && toIsDefault)
            {
                // Implicit numeric conversions:
                int f = GetPrimitiveType(from);
                int t = GetPrimitiveType(to);
                if (f == SByte && (t == Short || t == Int || t == Long || t == Float || t == Double || t == Decimal))
                {
                    return(true);
                }
                if (f == Byte && (t == Short || t == UShort || t == Int || t == UInt || t == Long || t == ULong || t == Float || t == Double || t == Decimal))
                {
                    return(true);
                }
                if (f == Short && (t == Int || t == Long || t == Float || t == Double || t == Decimal))
                {
                    return(true);
                }
                if (f == UShort && (t == Int || t == UInt || t == Long || t == ULong || t == Float || t == Double || t == Decimal))
                {
                    return(true);
                }
                if (f == Int && (t == Long || t == Float || t == Double || t == Decimal))
                {
                    return(true);
                }
                if (f == UInt && (t == Long || t == ULong || t == Float || t == Double || t == Decimal))
                {
                    return(true);
                }
                if ((f == Long || f == ULong) && (t == Float || t == Double || t == Decimal))
                {
                    return(true);
                }
                if (f == Char && (t == UShort || t == Int || t == UInt || t == Long || t == ULong || t == Float || t == Double || t == Decimal))
                {
                    return(true);
                }
                if (f == Float && t == Double)
                {
                    return(true);
                }
            }
            // Implicit reference conversions:

            if (toIsDefault && to.FullyQualifiedName == "System.Object")
            {
                return(true);                // from any type to object
            }
            if (from == NullReturnType.Instance)
            {
                IClass toClass = to.GetUnderlyingClass();
                if (toClass != null)
                {
                    switch (toClass.ClassType)
                    {
                    case ClassType.Class:
                    case ClassType.Delegate:
                    case ClassType.Interface:
                        return(true);

                    case ClassType.Struct:
                        return(toClass.FullyQualifiedName == "System.Nullable");
                    }
                }
                return(false);
            }

            if ((toIsDefault || to.IsConstructedReturnType || to.IsGenericReturnType) &&
                (fromIsDefault || from.IsArrayReturnType || from.IsConstructedReturnType))
            {
                foreach (IReturnType baseTypeOfFrom in GetTypeInheritanceTree(from))
                {
                    if (IsConstructedConversionToGenericReturnType(baseTypeOfFrom, to, allowGenericTargetsOnThisMethod))
                    {
                        return(true);
                    }
                }
            }

            if (from.IsArrayReturnType && to.IsArrayReturnType)
            {
                ArrayReturnType fromArt = from.CastToArrayReturnType();
                ArrayReturnType toArt   = to.CastToArrayReturnType();
                // from array to other array type
                if (fromArt.ArrayDimensions == toArt.ArrayDimensions)
                {
                    return(ConversionExistsInternal(fromArt.ArrayElementType, toArt.ArrayElementType, allowGenericTargetsOnThisMethod));
                }
            }

            if (from.IsDecoratingReturnType <AnonymousMethodReturnType>() && (toIsDefault || to.IsConstructedReturnType))
            {
                AnonymousMethodReturnType amrt = from.CastToDecoratingReturnType <AnonymousMethodReturnType>();
                IMethod method = CSharp.TypeInference.GetDelegateOrExpressionTreeSignature(to, amrt.CanBeConvertedToExpressionTree);
                if (method != null)
                {
                    if (amrt.HasParameterList)
                    {
                        if (amrt.MethodParameters.Count != method.Parameters.Count)
                        {
                            return(false);
                        }
                        for (int i = 0; i < amrt.MethodParameters.Count; i++)
                        {
                            if (amrt.MethodParameters[i].ReturnType != null)
                            {
                                if (!object.Equals(amrt.MethodParameters[i].ReturnType,
                                                   method.Parameters[i].ReturnType))
                                {
                                    return(false);
                                }
                            }
                        }
                    }
                    IReturnType rt = amrt.ResolveReturnType(method.Parameters.Select(p => p.ReturnType).ToArray());
                    return(ConversionExistsInternal(rt, method.ReturnType, allowGenericTargetsOnThisMethod));
                }
            }

            return(false);
        }
Exemplo n.º 53
0
 public override IType GetType(IReturnType returnType)
 {
     return(CheckType(base.GetType(returnType)));
 }
 public Constructor(ModifierEnum m, IReturnType returnType, IClass declaringType)
     : base((m & ModifierEnum.Static) != 0 ? "#cctor" : "#ctor",
            returnType, m, DomRegion.Empty, DomRegion.Empty, declaringType)
 {
 }
 /// <summary>
 /// Gets the common base type of a and b.
 /// </summary>
 public static IReturnType GetCommonType(IProjectContent projectContent, IReturnType a, IReturnType b)
 {
     if (projectContent == null)
     {
         throw new ArgumentNullException("projectContent");
     }
     if (a == null)
     {
         return(b);
     }
     if (b == null)
     {
         return(a);
     }
     if (ConversionExists(a, b))
     {
         return(b);
     }
     //if (ConversionExists(b, a)) - not required because the first baseTypeOfA is a
     //	return a;
     foreach (IReturnType baseTypeOfA in GetTypeInheritanceTree(a))
     {
         if (ConversionExists(b, baseTypeOfA))
         {
             return(baseTypeOfA);
         }
     }
     return(projectContent.SystemTypes.Object);
 }
Exemplo n.º 56
0
 internal ResolveResult CreateResult(IReturnType type)
 {
     return(CreateResult(resolver.Unit, type));
 }
 /// <summary>
 /// Checks if an implicit conversion exists from <paramref name="from"/> to <paramref name="to"/>.
 /// </summary>
 public static bool ConversionExists(IReturnType from, IReturnType to)
 {
     return(ConversionExistsInternal(from, to, null));
 }
Exemplo n.º 58
0
/*		public virtual IType SearchType (SearchTypeRequest request)
 *              {
 *                      return SearchType (request.Name, request.CallingType, request.CurrentCompilationUnit, request.GenericParameters);
 *              }*/

        internal IType SearchType(ICompilationUnit unit, IType callingClass, DomLocation lookupLocation, string name, IList <IReturnType> genericParameters)
        {
            // TODO dom check generic parameter count
            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }

            IType result = null;

            // It may be one of the generic parameters in the calling class
            if (genericParameters == null || genericParameters.Count == 0)
            {
                if (callingClass != null)
                {
                    result = FindGenericParameter(unit, ResolveType(callingClass), name);
                    if (result != null)
                    {
                        return(result);
                    }
                }
            }

            // A known type?
            result = GetType(name, genericParameters, false, true);
            if (result != null)
            {
                return(result);
            }

            // Maybe an inner type that isn't fully qualified?
            if (callingClass != null)
            {
                IType t = ResolveType(callingClass);
                result = SearchInnerType(t, name.Split('.'), 0, genericParameters != null ? genericParameters.Count : 0, true);
                if (result != null)
                {
                    if (genericParameters != null && genericParameters.Count > 0)
                    {
                        return(CreateInstantiatedGenericType(result, genericParameters));
                    }
                    return(result);
                }
            }
            // If the name matches an alias, try using the alias first.
            if (unit != null)
            {
                IReturnType ualias = FindAlias(name, unit.Usings);
                if (ualias != null)
                {
                    // Don't provide the compilation unit when trying to resolve the alias,
                    // since aliases are not affected by other 'using' directives.
                    result = GetType(ualias.FullName, ualias.GenericArguments, false, true);
                    if (result != null)
                    {
                        return(result);
                    }
                }
            }

            // The enclosing namespace has preference over the using directives.
            // Check it now.
            if (callingClass != null)
            {
                List <int> indices = new List <int> ();
                string     str     = callingClass.FullName;
                for (int i = 0; i < str.Length; i++)
                {
                    if (str[i] == '.')
                    {
                        indices.Add(i);
                    }
                }
                for (int n = indices.Count - 1; n >= 0; n--)
                {
                    if (n < 1)
                    {
                        continue;
                    }
                    string curnamespace = str.Substring(0, indices[n] + 1);
                    result = GetType(curnamespace + name, genericParameters, false, true);
                    if (result != null)
                    {
                        return(result);
                    }
                }
            }

            // Now try to find the class using the included namespaces
            if (unit != null)
            {
                // it's a difference having using A; namespace B { } or namespace B { using A;  }, when a type
                // request equals a namespace name; for example the type B could be resolved in the 2nd case when a type
                // A.B exists but not in the 1st.
                foreach (IUsing u in unit.Usings.Reverse())
                {
                    if (u.Namespaces.Contains(name))
                    {
                        return(null);
                    }
                    if (callingClass != null && !u.ValidRegion.Contains(lookupLocation))
                    {
                        continue;
                    }
                    if (u != null)
                    {
                        result = SearchType(u, name, genericParameters, true);
                        if (result != null)
                        {
                            return(result);
                        }
                    }
                }
            }

            return(null);
        }
Exemplo n.º 59
0
 IReturnType GetCommonType(IReturnType left, IReturnType right)
 {
     return(left ?? right);
 }
Exemplo n.º 60
0
 public IType GetArrayType(IReturnType elementType)
 {
     return(GetArrayType(elementType, MonoDevelop.Projects.Dom.Output.AmbienceService.DefaultAmbience));
 }