Esempio n. 1
0
		IEnumerable<INamespace> ResolveNamespaces(ICompilation compilation)
		{
			IType xmlnsDefinition = compilation.FindType(typeof(System.Windows.Markup.XmlnsDefinitionAttribute));
			if (XmlNamespace.StartsWith("clr-namespace:", StringComparison.Ordinal)) {
				string name = XmlNamespace.Substring("clr-namespace:".Length);
				IAssembly asm = compilation.MainAssembly;
				int asmIndex = name.IndexOf(";assembly=", StringComparison.Ordinal);
				if (asmIndex >= 0) {
					string asmName = name.Substring(asmIndex + ";assembly=".Length);
					asm = compilation.ReferencedAssemblies.FirstOrDefault(a => a.AssemblyName == asmName) ?? compilation.MainAssembly;
					name = name.Substring(0, asmIndex);
				}
				string[] parts = name.Split('.');
				var @namespace = FindNamespace(asm, parts);
				if (@namespace != null) yield return @namespace;
			} else {
				foreach (IAssembly asm in compilation.Assemblies) {
					foreach (IAttribute attr in asm.AssemblyAttributes) {
						if (xmlnsDefinition.Equals(attr.AttributeType) && attr.PositionalArguments.Count == 2) {
							string xmlns = attr.PositionalArguments[0].ConstantValue as string;
							if (xmlns != XmlNamespace) continue;
							string ns = attr.PositionalArguments[1].ConstantValue as string;
							if (ns == null) continue;
							var @namespace = FindNamespace(asm, ns.Split('.'));
							if (@namespace != null) yield return @namespace;
						}
					}
				}
			}
		}
Esempio n. 2
0
		/// <summary>
		/// Creates a task type.
		/// </summary>
		public static IType Create(ICompilation compilation, IType elementType)
		{
			if (compilation == null)
				throw new ArgumentNullException("compilation");
			if (elementType == null)
				throw new ArgumentNullException("elementType");
			
			if (elementType.Kind == TypeKind.Void)
				return compilation.FindType(KnownTypeCode.Task);
			IType taskType = compilation.FindType(KnownTypeCode.TaskOfT);
			ITypeDefinition taskTypeDef = taskType.GetDefinition();
			if (taskTypeDef != null)
				return new ParameterizedType(taskTypeDef, new [] { elementType });
			else
				return taskType;
		}
		static IAttribute CreateSuppressAttribute(ICompilation compilation, FxCopTaskTag tag)
		{
			// [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId:="fileIdentifier"]
			IType attributeType = compilation.FindType(new FullTypeName(FullAttributeName));
			IType stringType = compilation.FindType(KnownTypeCode.String);
			
			KeyValuePair<IMember, ResolveResult>[] namedArgs = null;
			if (tag.MessageID != null) {
				IMember messageId = attributeType.GetProperties(p => p.Name == "MessageId").FirstOrDefault();
				namedArgs = new[] { new KeyValuePair<IMember, ResolveResult>(messageId, new ConstantResolveResult(stringType, tag.MessageID)) };
			}
			
			return new DefaultAttribute(
				attributeType, new[] {
					new ConstantResolveResult(stringType, tag.Category),
					new ConstantResolveResult(stringType, tag.CheckID)
				}, namedArgs);
		}
Esempio n. 4
0
		/// <summary>
		/// Gets the T in Task&lt;T&gt;.
		/// Returns void for non-generic Task.
		/// Any other type is returned unmodified.
		/// </summary>
		public static IType UnpackTask(ICompilation compilation, IType type)
		{
			if (!IsTask(type))
				return type;
			if (type.TypeParameterCount == 0)
				return compilation.FindType(KnownTypeCode.Void);
			else
				return type.TypeArguments[0];
		}
		protected IType GetDesignedClass(ICompilation compilation)
		{
			var xamlContext = viewContent.DesignContext as Designer.Xaml.XamlDesignContext;
			if (xamlContext != null) {
				string className = xamlContext.ClassName;
				if (!string.IsNullOrEmpty(className)) {
					return compilation.FindType(new FullTypeName(className));
				}
			}
			return null;
		}
Esempio n. 6
0
		/// <summary>
		/// Creates a nullable type.
		/// </summary>
		public static IType Create(ICompilation compilation, IType elementType)
		{
			if (compilation == null)
				throw new ArgumentNullException("compilation");
			if (elementType == null)
				throw new ArgumentNullException("elementType");
			
			IType nullableType = compilation.FindType(KnownTypeCode.NullableOfT);
			ITypeDefinition nullableTypeDef = nullableType.GetDefinition();
			if (nullableTypeDef != null)
				return new ParameterizedType(nullableTypeDef, new [] { elementType });
			else
				return nullableType;
		}
Esempio n. 7
0
		public void SetUp()
		{
			pc = new CSharpProjectContent();
			pc = pc.SetAssemblyName("MyAssembly");
			parsedFile = new CSharpParser().Parse(new StringReader(program), "program.cs").ToTypeSystem();
			pc = pc.UpdateProjectContent(null, parsedFile);
			pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib });
			
			compilation = pc.CreateCompilation();
			
			baseClass = compilation.RootNamespace.GetTypeDefinition("Base", 1);
			nestedClass = baseClass.NestedTypes.Single();
			derivedClass = compilation.RootNamespace.GetTypeDefinition("Derived", 2);
			systemClass = compilation.FindType("NS.System, MyAssembly").GetDefinition();
		}
		internal static bool PreferAttributeTypeWithSuffix(IType t1, IType t2, ICompilation compilation)
		{
			if (t2.Kind == TypeKind.Unknown) return false;
			if (t1.Kind == TypeKind.Unknown) return true;
			
			var attrTypeDef = compilation.FindType(KnownTypeCode.Attribute).GetDefinition();
			if (attrTypeDef != null) {
				bool t1IsAttribute = (t1.GetDefinition() != null && t1.GetDefinition().IsDerivedFrom(attrTypeDef));
				bool t2IsAttribute = (t2.GetDefinition() != null && t2.GetDefinition().IsDerivedFrom(attrTypeDef));
				if (t2IsAttribute && !t1IsAttribute)
					return true;
				// If both types exist and are attributes, C# considers that to be an ambiguity, but we are less strict.
			}
			return false;
		}
Esempio n. 9
0
        public DecompilerTypeSystem(ModuleDefinition moduleDefinition, DecompilerSettings settings)
        {
            if (moduleDefinition == null)
            {
                throw new ArgumentNullException(nameof(moduleDefinition));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            this.moduleDefinition    = moduleDefinition;
            typeReferenceCecilLoader = new CecilLoader {
                UseDynamicType = settings.Dynamic,
                UseTupleTypes  = settings.TupleTypes,
            };
            CecilLoader cecilLoader = new CecilLoader {
                IncludeInternalMembers = true,
                LazyLoad                  = true,
                OnEntityLoaded            = StoreMemberReference,
                ShortenInterfaceImplNames = false,
                UseDynamicType            = settings.Dynamic,
                UseTupleTypes             = settings.TupleTypes,
            };

            typeReferenceCecilLoader.SetCurrentModule(moduleDefinition);
            IUnresolvedAssembly mainAssembly = cecilLoader.LoadModule(moduleDefinition);
            // Load referenced assemblies and type-forwarder references.
            // This is necessary to make .NET Core/PCL binaries work better.
            var referencedAssemblies        = new List <IUnresolvedAssembly>();
            var assemblyReferenceQueue      = new Queue <AssemblyNameReference>(moduleDefinition.AssemblyReferences);
            var processedAssemblyReferences = new HashSet <AssemblyNameReference>(KeyComparer.Create((AssemblyNameReference reference) => reference.FullName));

            while (assemblyReferenceQueue.Count > 0)
            {
                var asmRef = assemblyReferenceQueue.Dequeue();
                if (!processedAssemblyReferences.Add(asmRef))
                {
                    continue;
                }
                var asm = moduleDefinition.AssemblyResolver.Resolve(asmRef);
                if (asm != null)
                {
                    referencedAssemblies.Add(cecilLoader.LoadAssembly(asm));
                    foreach (var forwarder in asm.MainModule.ExportedTypes)
                    {
                        if (!forwarder.IsForwarder || !(forwarder.Scope is AssemblyNameReference forwarderRef))
                        {
                            continue;
                        }
                        assemblyReferenceQueue.Enqueue(forwarderRef);
                    }
                }
            }
            compilation = new SimpleCompilation(mainAssembly, referencedAssemblies);
            // Primitive types are necessary to avoid assertions in ILReader.
            // Fallback to MinimalCorlib to provide the primitive types.
            if (compilation.FindType(KnownTypeCode.Void).Kind == TypeKind.Unknown || compilation.FindType(KnownTypeCode.Int32).Kind == TypeKind.Unknown)
            {
                referencedAssemblies.Add(MinimalCorlib.Instance);
                compilation = new SimpleCompilation(mainAssembly, referencedAssemblies);
            }
            context = new SimpleTypeResolveContext(compilation.MainAssembly);
        }
Esempio n. 10
0
        void TestFindType(Type type)
        {
            IType t = compilation.FindType(type);

            Assert.IsNotNull(t, type.FullName);
            Assert.AreEqual(type.FullName, t.ReflectionName);
        }
Esempio n. 11
0
 protected ITypeDefinition GetTypeDefinition(Type type)
 {
     return(compilation.FindType(type).GetDefinition());
 }
Esempio n. 12
0
        private IType ReadCustomAttributeFieldOrPropType()
        {
            ICompilation compilation = currentResolvedAssembly.Compilation;
            var          b           = ReadByte();

            switch (b)
            {
            case 0x02:
                return(compilation.FindType(KnownTypeCode.Boolean));

            case 0x03:
                return(compilation.FindType(KnownTypeCode.Char));

            case 0x04:
                return(compilation.FindType(KnownTypeCode.SByte));

            case 0x05:
                return(compilation.FindType(KnownTypeCode.Byte));

            case 0x06:
                return(compilation.FindType(KnownTypeCode.Int16));

            case 0x07:
                return(compilation.FindType(KnownTypeCode.UInt16));

            case 0x08:
                return(compilation.FindType(KnownTypeCode.Int32));

            case 0x09:
                return(compilation.FindType(KnownTypeCode.UInt32));

            case 0x0a:
                return(compilation.FindType(KnownTypeCode.Int64));

            case 0x0b:
                return(compilation.FindType(KnownTypeCode.UInt64));

            case 0x0c:
                return(compilation.FindType(KnownTypeCode.Single));

            case 0x0d:
                return(compilation.FindType(KnownTypeCode.Double));

            case 0x0e:
                return(compilation.FindType(KnownTypeCode.String));

            case 0x1d:
                return(new ArrayType(compilation, ReadCustomAttributeFieldOrPropType()));

            case 0x50:
                return(compilation.FindType(KnownTypeCode.Type));

            case 0x51:                     // boxed value type
                return(compilation.FindType(KnownTypeCode.Object));

            case 0x55:                     // enum
                return(ReadType());

            default:
                throw new NotSupportedException(string.Format("Custom attribute type 0x{0:x} is not supported.", b));
            }
        }
        void ProjectTreeScanningBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            if (this.project == null)
            {
                return;
            }

            ProjectResourceInfo selectedProjectResource = e.Argument as ProjectResourceInfo;

            ICompilation compilation     = SD.ParserService.GetCompilation(this.project);
            var          codeDomProvider = project.CreateCodeDomProvider();

            TreeNode root           = new TreeNode(this.project.Name, 0, 0);
            TreeNode preSelection   = null;
            TreeNode lastFileNode   = null;
            int      fileNodesCount = 0;

            foreach (FileProjectItem item in this.project.GetItemsOfType(ItemType.EmbeddedResource).OfType <FileProjectItem>().OrderBy(fpi => Path.GetFileName(fpi.VirtualName)))
            {
                if (this.projectTreeScanningBackgroundWorker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                // Skip files where the generated class name
                // would conflict with an existing class.
                string namespaceName = item.GetEvaluatedMetadata("CustomToolNamespace");
                if (string.IsNullOrEmpty(namespaceName))
                {
                    namespaceName = CustomToolsService.GetDefaultNamespace(item.Project, item.FileName);
                }
                string className = item.FileName.GetFileNameWithoutExtension();
                if (codeDomProvider != null)
                {
                    className = StronglyTypedResourceBuilder.VerifyResourceName(className, codeDomProvider);
                    if (className == null)
                    {
                        continue;
                    }
                }
                ITypeDefinition existingClass = compilation.FindType(new TopLevelTypeName(namespaceName, className)).GetDefinition();
                if (existingClass != null)
                {
                    if (!ProjectResourceService.IsGeneratedResourceClass(existingClass))
                    {
                        continue;
                    }
                }

                bool     selectedFile = (selectedProjectResource != null) && FileUtility.IsEqualFileName(selectedProjectResource.ResourceFile, item.FileName);
                TreeNode file         = null;

                try {
                    foreach (KeyValuePair <string, object> r in this.GetResources(item.FileName).OrderBy(pair => pair.Key))
                    {
                        if (this.projectTreeScanningBackgroundWorker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        if (file == null)
                        {
                            file = CreateAndAddFileNode(root, item);
                        }

                        TreeNode resNode = new TreeNode(r.Key, 3, 3);
                        resNode.Tag = r.Value;
                        file.Nodes.Add(resNode);

                        if (selectedFile)
                        {
                            if (String.Equals(r.Key, selectedProjectResource.ResourceKey, StringComparison.Ordinal))
                            {
                                preSelection = resNode;
                            }
                        }
                    }

                    if (file != null)
                    {
                        lastFileNode = file;
                        ++fileNodesCount;
                    }
                } catch (Exception ex) {
                    if (file == null)
                    {
                        file = CreateAndAddFileNode(root, item);
                    }
                    TreeNode error = new TreeNode(ex.Message, 4, 4);
                    file.Nodes.Add(error);
                }
            }

            if (e.Cancel)
            {
                DisposeNodeImages(root);
            }
            else
            {
                // Preselect the file node if there is only one
                if (preSelection == null && fileNodesCount == 1)
                {
                    preSelection = lastFileNode;
                }
                e.Result = new TreeScanResult(root, preSelection);
            }
        }
Esempio n. 14
0
 public override IEnumerable <IMethod> GetMethods(Predicate <IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
 {
     return(compilation.FindType(KnownTypeCode.Array).GetMethods(filter, options));
 }
		IEvent FindEventDeclaration(ICompilation compilation, Type declaringType, string name)
		{
			return compilation.FindType(declaringType).GetEvents(ue => ue.Name == name).FirstOrDefault();
		}
Esempio n. 16
0
		public void ClassDerivingFromTwoInstanciationsOfIEnumerable()
		{
			// class C : IEnumerable<int>, IEnumerable<uint> {}
			var c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
			c.BaseTypes.Add(typeof(IEnumerable<int>).ToTypeReference());
			c.BaseTypes.Add(typeof(IEnumerable<uint>).ToTypeReference());
			compilation = TypeSystemHelper.CreateCompilation(c);
			ITypeDefinition resolvedC = Resolve(c);
			IType[] expected = {
				resolvedC,
				compilation.FindType(typeof(IEnumerable<int>)),
				compilation.FindType(typeof(IEnumerable<uint>)),
				compilation.FindType(typeof(IEnumerable)),
				compilation.FindType(typeof(object))
			};
			Assert.AreEqual(expected,
			                resolvedC.GetAllBaseTypes().OrderBy(t => t.ReflectionName).ToArray());
		}
		public IEnumerable<ICompletionItem> CreateListForXmlnsCompletion(ICompilation compilation)
		{
			this.compilation = compilation;
			
			List<XmlnsCompletionItem> list = new List<XmlnsCompletionItem>();
			IType xmlnsAttrType = compilation.FindType(typeof(System.Windows.Markup.XmlnsDefinitionAttribute));
			foreach (IAssembly asm in compilation.ReferencedAssemblies) {
				foreach (IAttribute att in asm.AssemblyAttributes) {
					if (att.PositionalArguments.Count == 2 && att.AttributeType.Equals(xmlnsAttrType)) {
						ResolveResult arg1 = att.PositionalArguments[0];
						if (arg1.IsCompileTimeConstant && arg1.ConstantValue is string) {
							list.Add(new XmlnsCompletionItem((string)arg1.ConstantValue, true));
						}
					}
				}
				
				foreach (INamespace @namespace in TreeTraversal.PreOrder(asm.RootNamespace, ns => ns.ChildNamespaces)) {
					list.Add(new XmlnsCompletionItem(@namespace.FullName, asm.AssemblyName));
				}
			}
			
			foreach (INamespace @namespace in TreeTraversal.PreOrder(compilation.MainAssembly.RootNamespace, ns => ns.ChildNamespaces)) {
				list.Add(new XmlnsCompletionItem(@namespace.FullName, false));
			}
			
			list.Add(new XmlnsCompletionItem(XamlConst.MarkupCompatibilityNamespace, true));
			
			return list
				.Distinct(new XmlnsEqualityComparer())
				.OrderBy(item => item, new XmlnsComparer());
		}
Esempio n. 18
0
        /// <summary>
        /// Infers the C# type for an IL instruction.
        ///
        /// Returns SpecialType.UnknownType for unsupported instructions.
        /// </summary>
        public static IType InferType(this ILInstruction inst, ICompilation compilation)
        {
            switch (inst)
            {
            case NewObj newObj:
                return(newObj.Method.DeclaringType);

            case NewArr newArr:
                if (compilation != null)
                {
                    return(new ArrayType(compilation, newArr.Type, newArr.Indices.Count));
                }
                else
                {
                    return(SpecialType.UnknownType);
                }

            case Call call:
                return(call.Method.ReturnType);

            case CallVirt callVirt:
                return(callVirt.Method.ReturnType);

            case CallIndirect calli:
                return(calli.FunctionPointerType.ReturnType);

            case UserDefinedLogicOperator logicOp:
                return(logicOp.Method.ReturnType);

            case LdObj ldobj:
                return(ldobj.Type);

            case StObj stobj:
                return(stobj.Type);

            case LdLoc ldloc:
                return(ldloc.Variable.Type);

            case StLoc stloc:
                return(stloc.Variable.Type);

            case LdLoca ldloca:
                return(new ByReferenceType(ldloca.Variable.Type));

            case LdFlda ldflda:
                return(new ByReferenceType(ldflda.Field.Type));

            case LdsFlda ldsflda:
                return(new ByReferenceType(ldsflda.Field.Type));

            case LdElema ldelema:
                if (ldelema.Array.InferType(compilation) is ArrayType arrayType)
                {
                    if (TypeUtils.IsCompatibleTypeForMemoryAccess(arrayType.ElementType, ldelema.Type))
                    {
                        return(new ByReferenceType(arrayType.ElementType));
                    }
                }
                return(new ByReferenceType(ldelema.Type));

            case Comp comp:
                if (compilation == null)
                {
                    return(SpecialType.UnknownType);
                }
                switch (comp.LiftingKind)
                {
                case ComparisonLiftingKind.None:
                case ComparisonLiftingKind.CSharp:
                    return(compilation.FindType(KnownTypeCode.Boolean));

                case ComparisonLiftingKind.ThreeValuedLogic:
                    return(NullableType.Create(compilation, compilation.FindType(KnownTypeCode.Boolean)));

                default:
                    return(SpecialType.UnknownType);
                }

            case BinaryNumericInstruction bni:
                if (bni.IsLifted)
                {
                    return(SpecialType.UnknownType);
                }
                switch (bni.Operator)
                {
                case BinaryNumericOperator.BitAnd:
                case BinaryNumericOperator.BitOr:
                case BinaryNumericOperator.BitXor:
                    var left  = bni.Left.InferType(compilation);
                    var right = bni.Right.InferType(compilation);
                    if (left.Equals(right) && (left.IsCSharpPrimitiveIntegerType() || left.IsCSharpNativeIntegerType() || left.IsKnownType(KnownTypeCode.Boolean)))
                    {
                        return(left);
                    }
                    else
                    {
                        return(SpecialType.UnknownType);
                    }

                default:
                    return(SpecialType.UnknownType);
                }

            default:
                return(SpecialType.UnknownType);
            }
        }
Esempio n. 19
0
 /// <summary>
 /// Retrieves a built-in type using the specified type code.
 /// </summary>
 public static IType FindType(this ICompilation compilation, TypeCode typeCode)
 {
     return(compilation.FindType((KnownTypeCode)typeCode));
 }
Esempio n. 20
0
 public void AddFixedArg(KnownTypeCode type, object value)
 {
     AddFixedArg(compilation.FindType(type), value);
 }
        Value VisitBinaryOperator(OperatorResolveResult result, BinaryOperatorType operatorType, bool checkForOverflow = false)
        {
            Debug.Assert(result.Operands.Count == 2);
            Debug.Assert(operatorType != BinaryOperatorType.ConditionalAnd && operatorType != BinaryOperatorType.ConditionalOr && operatorType != BinaryOperatorType.NullCoalescing);
            var lhs = Convert(result.Operands[0]).GetPermanentReference(evalThread);
            var rhs = Convert(result.Operands[1]).GetPermanentReference(evalThread);

            if (result.UserDefinedOperatorMethod != null)
            {
                return(InvokeMethod(null, result.UserDefinedOperatorMethod, lhs, rhs));
            }
            var            lhsRR    = lhs.ToResolveResult(context);
            var            rhsRR    = rhs.ToResolveResult(context);
            CSharpResolver resolver = new CSharpResolver(debuggerTypeSystem).WithCheckForOverflow(checkForOverflow);
            var            val      = resolver.ResolveBinaryOperator(operatorType, lhsRR, rhsRR);

            if (val.IsCompileTimeConstant)
            {
                return(Convert(val));
            }
            switch (operatorType)
            {
            case BinaryOperatorType.Equality:
            case BinaryOperatorType.InEquality:
                bool equality = (operatorType == BinaryOperatorType.Equality);
                if (lhsRR.Type.IsKnownType(KnownTypeCode.String) && rhsRR.Type.IsKnownType(KnownTypeCode.String))
                {
                    if (lhs.IsNull || rhs.IsNull)
                    {
                        bool bothNull = lhs.IsNull && rhs.IsNull;
                        return(Eval.CreateValue(evalThread, equality ? bothNull : !bothNull));
                    }
                    else
                    {
                        bool equal = (string)lhs.PrimitiveValue == (string)rhs.PrimitiveValue;
                        return(Eval.CreateValue(evalThread, equality ? equal : !equal));
                    }
                }
                if (lhsRR.Type.IsReferenceType != false && rhsRR.Type.IsReferenceType != false)
                {
                    // Reference comparison
                    if (lhs.IsNull || rhs.IsNull)
                    {
                        bool bothNull = lhs.IsNull && rhs.IsNull;
                        return(Eval.CreateValue(evalThread, equality ? bothNull : !bothNull));
                    }
                    else
                    {
                        bool equal = lhs.Address == rhs.Address;
                        return(Eval.CreateValue(evalThread, equality ? equal : !equal));
                    }
                }
                goto default;

            case BinaryOperatorType.Add:
                if (lhsRR.Type.IsKnownType(KnownTypeCode.String) || rhsRR.Type.IsKnownType(KnownTypeCode.String))
                {
                    var method = debuggerTypeSystem.FindType(KnownTypeCode.String)
                                 .GetMethods(m => m.Name == "Concat" && m.Parameters.Count == 2)
                                 .Single(m => m.Parameters.All(p => p.Type.IsKnownType(KnownTypeCode.Object)));
                    return(InvokeMethod(null, method, lhs, rhs));
                }
                goto default;

            default:
                throw new GetValueException("Operator {0} is not supported for {1} and {2}!", operatorType, new CSharpAmbience().ConvertType(lhsRR.Type), new CSharpAmbience().ConvertType(rhsRR.Type));
            }
        }
Esempio n. 22
0
 IType[] GetAllBaseTypes(Type type)
 {
     return(compilation.FindType(type).GetAllBaseTypes().OrderBy(t => t.ReflectionName).ToArray());
 }
        public IList<JsStatement> Rewrite(IEnumerable<JsType> types, ICompilation compilation)
        {
            var netSystemType = compilation.FindType(KnownTypeCode.Type).GetDefinition();
            var systemType = new JsTypeReferenceExpression(netSystemType.ParentAssembly, _metadataImporter.GetTypeSemantics(netSystemType).Name);

            var result = new List<JsStatement>();

            var orderedTypes = types.OrderBy(t => t.Name).ToList();
            string currentNs = "";
            foreach (var t in orderedTypes) {
                try {
                    var globalMethodsPrefix = _metadataImporter.GetGlobalMethodsPrefix(t.CSharpTypeDefinition);

                    string ns = GetNamespace(t.Name);
                    if (ns != currentNs && globalMethodsPrefix == null) {
                        result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.MemberAccess(systemType, RegisterNamespace), JsExpression.String(ns))));
                        currentNs = ns;
                    }
                    result.Add(new JsComment("//////////////////////////////////////////////////////////////////////////////" + Environment.NewLine + " " + t.Name));

                    var typeRef = new JsTypeReferenceExpression(compilation.MainAssembly, t.Name);
                    if (t is JsClass) {
                        var c = (JsClass)t;
                        if (globalMethodsPrefix != null) {
                            if (globalMethodsPrefix == "") {
                                result.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Binary(ExpressionNodeType.Assign, JsExpression.MemberAccess(JsExpression.Identifier("window"), m.Name), m.Definition))));
                            }
                            else {
                                result.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Assign(MakeNestedMemberAccess(globalMethodsPrefix + "." + m.Name), m.Definition))));
                            }
                        }
                        else if (_metadataImporter.IsResources(t.CSharpTypeDefinition)) {
                            result.Add(GenerateResourcesClass(c));
                        }
                        else {
                            var unnamedCtor = c.UnnamedConstructor ?? JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement);

                            if (c.TypeArgumentNames.Count == 0) {
                                result.Add(new JsExpressionStatement(JsExpression.Assign(typeRef, unnamedCtor)));
                                AddClassMembers(c, typeRef, compilation, result);
                            }
                            else {
                                var stmts = new List<JsStatement> { new JsVariableDeclarationStatement(InstantiatedGenericTypeVariableName, unnamedCtor) };
                                AddClassMembers(c, JsExpression.Identifier(InstantiatedGenericTypeVariableName), compilation, stmts);
                                stmts.AddRange(c.StaticInitStatements);
                                stmts.Add(new JsReturnStatement(JsExpression.Identifier(InstantiatedGenericTypeVariableName)));
                                result.Add(new JsExpressionStatement(JsExpression.Assign(typeRef, JsExpression.FunctionDefinition(c.TypeArgumentNames, new JsBlockStatement(stmts)))));
                                result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.MemberAccess(typeRef, c.ClassType == JsClass.ClassTypeEnum.Interface ? RegisterGenericInterface : RegisterGenericClass), JsExpression.String(c.Name), JsExpression.Number(c.TypeArgumentNames.Count))));
                            }
                        }
                    }
                    else if (t is JsEnum) {
                        var e = (JsEnum)t;
                        bool flags = GetAttributePositionalArgs(t.CSharpTypeDefinition, FlagsAttribute, "System") != null;
                        result.Add(new JsExpressionStatement(JsExpression.Assign(typeRef, JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement))));
                        result.Add(new JsExpressionStatement(JsExpression.Assign(JsExpression.MemberAccess(typeRef, Prototype), JsExpression.ObjectLiteral(e.Values.Select(v => new JsObjectLiteralProperty(v.Name, (_metadataImporter.IsNamedValues(t.CSharpTypeDefinition) ? JsExpression.String(v.Name) : JsExpression.Number(v.Value))))))));
                        result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.MemberAccess(typeRef, RegisterEnum), JsExpression.String(t.Name), JsExpression.Boolean(flags))));
                    }
                }
                catch (Exception ex) {
                    _errorReporter.Region = t.CSharpTypeDefinition.Region;
                    _errorReporter.InternalError(ex, "Error formatting type " + t.CSharpTypeDefinition.FullName);
                }
            }

            var typesToRegister = orderedTypes.OfType<JsClass>()
                                        .Where(c =>    c.TypeArgumentNames.Count == 0
                                                    && _metadataImporter.GetGlobalMethodsPrefix(c.CSharpTypeDefinition) == null
                                                    && !_metadataImporter.IsResources(c.CSharpTypeDefinition))
                                        .ToList();

            result.AddRange(TopologicalSortTypesByInheritance(typesToRegister)
                            .Select(c => {
                                             try {
                                                 var typeRef = new JsTypeReferenceExpression(compilation.MainAssembly, c.Name);
                                                 if (c.ClassType == JsClass.ClassTypeEnum.Interface) {
                                                     return JsExpression.Invocation(JsExpression.MemberAccess(typeRef, RegisterInterface), JsExpression.String(c.Name), JsExpression.ArrayLiteral(c.ImplementedInterfaces));
                                                 }
                                                 else {
                                                     return CreateRegisterClassCall(JsExpression.String(c.Name), c.BaseClass, c.ImplementedInterfaces, typeRef);
                                                 }
                                             }
                                             catch (Exception ex) {
                                                 _errorReporter.Region = c.CSharpTypeDefinition.Region;
                                                 _errorReporter.InternalError(ex, "Error formatting type " + c.CSharpTypeDefinition.FullName);
                                                 return JsExpression.Number(0);
                                             }
                                         })
                            .Select(expr => new JsExpressionStatement(expr)));
            result.AddRange(orderedTypes.OfType<JsClass>().Where(c => c.TypeArgumentNames.Count == 0 && !_metadataImporter.IsResources(c.CSharpTypeDefinition)).SelectMany(t => t.StaticInitStatements));

            return result;
        }
Esempio n. 24
0
 public IType GetFunctionPointerType(SRM.MethodSignature <IType> signature)
 {
     return(compilation.FindType(KnownTypeCode.IntPtr));
 }
Esempio n. 25
0
		public void StructImplementingIEquatable()
		{
			// struct S : IEquatable<S> {}
			// don't use a Cecil-loaded struct for this test; we're testing the implicit addition of System.ValueType
			var s = new DefaultUnresolvedTypeDefinition(string.Empty, "S");
			s.Kind = TypeKind.Struct;
			s.BaseTypes.Add(new ParameterizedTypeReference(typeof(IEquatable<>).ToTypeReference(), new[] { s }));
			compilation = TypeSystemHelper.CreateCompilation(s);
			ITypeDefinition resolvedS = Resolve(s);
			IType[] expected = {
				resolvedS,
				s.BaseTypes[0].Resolve(new SimpleTypeResolveContext(resolvedS)),
				compilation.FindType(typeof(object)),
				compilation.FindType(typeof(ValueType))
			};
			Assert.AreEqual(expected,
			                resolvedS.GetAllBaseTypes().OrderBy(t => t.ReflectionName).ToArray());
		}
Esempio n. 26
0
        public override string VisitConversionResolveResult(ConversionResolveResult rr, object data)
        {
            var input = VisitResolveResult(rr.Input, null);

            if (rr.Conversion.IsIdentityConversion)
            {
                return(input);
            }
            else if (rr.Conversion.IsAnonymousFunctionConversion)
            {
                var result = input;
                if (rr.Type.Name == "Expression")
                {
                    result = CompileFactoryCall("Quote", new[] { typeof(Expression) }, new[] { result });
                }
                return(result);
            }
            else if (rr.Conversion.IsNullLiteralConversion)
            {
                return(CompileFactoryCall("Constant", new[] { typeof(object), typeof(Type) }, new[] { input, ExpressionTreeBuilder.GetTypeName(rr.Type, this._emitter) }));
            }
            else if (rr.Conversion.IsMethodGroupConversion)
            {
                var methodInfo = _compilation.FindType(typeof(MethodInfo));
                return(CompileFactoryCall("Convert", new[] { typeof(Expression), typeof(Type) }, new[] {
                    CompileFactoryCall("Call", new[] { typeof(Expression), typeof(MethodInfo), typeof(Expression[]) }, new[] {
                        CompileFactoryCall("Constant", new[] { typeof(object), typeof(Type) }, new[] { this.GetMember(rr.Conversion.Method), ExpressionTreeBuilder.GetTypeName(methodInfo, this._emitter) }),
                        this.GetMember(methodInfo.GetMethods().Single(m => m.Name == "CreateDelegate" && m.Parameters.Count == 2 && m.Parameters[0].Type.FullName == typeof(Type).FullName && m.Parameters[1].Type.FullName == typeof(object).FullName)),
                        this._emitter.ToJavaScript(new [] {
                            new JRaw(ExpressionTreeBuilder.GetTypeName(rr.Type, this._emitter)),
                            new JRaw(rr.Conversion.Method.IsStatic ? "null" : VisitResolveResult(((MethodGroupResolveResult)rr.Input).TargetResult, null))
                        })
                    }),
                    ExpressionTreeBuilder.GetTypeName(rr.Type, this._emitter)
                }));
            }
            else
            {
                string methodName;
                if (rr.Conversion.IsTryCast)
                {
                    methodName = "TypeAs";
                }
                else if (rr.CheckForOverflow)
                {
                    methodName = "ConvertChecked";
                }
                else
                {
                    methodName = "Convert";
                }
                if (rr.Conversion.IsUserDefined)
                {
                    return(CompileFactoryCall(methodName, new[] { typeof(Expression), typeof(Type), typeof(MethodInfo) }, new[] { input, ExpressionTreeBuilder.GetTypeName(rr.Type, this._emitter), this.GetMember(rr.Conversion.Method) }));
                }
                else
                {
                    return(CompileFactoryCall(methodName, new[] { typeof(Expression), typeof(Type) }, new[] { input, ExpressionTreeBuilder.GetTypeName(rr.Type, this._emitter) }));
                }
            }
        }