2 // Copyright (C) 2010 Novell Inc. http://novell.com
4 // Permission is hereby granted, free of charge, to any person obtaining
5 // a copy of this software and associated documentation files (the
6 // "Software"), to deal in the Software without restriction, including
7 // without limitation the rights to use, copy, modify, merge, publish,
8 // distribute, sublicense, and/or sell copies of the Software, and to
9 // permit persons to whom the Software is furnished to do so, subject to
10 // the following conditions:
12 // The above copyright notice and this permission notice shall be
13 // included in all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 using System.Collections;
25 using System.Collections.Generic;
26 using System.ComponentModel;
28 using System.Reflection;
29 using System.Windows.Markup;
30 using System.Xaml.Schema;
31 using System.Xml.Serialization;
35 public class XamlType : IEquatable<XamlType>
37 public XamlType (Type underlyingType, XamlSchemaContext schemaContext)
38 : this (underlyingType, schemaContext, null)
42 // static readonly Type [] predefined_types = {
43 // typeof (XData), typeof (Uri), typeof (TimeSpan), typeof (PropertyDefinition), typeof (MemberDefinition), typeof (Reference)
46 public XamlType (Type underlyingType, XamlSchemaContext schemaContext, XamlTypeInvoker invoker)
47 : this (schemaContext, invoker)
49 if (underlyingType == null)
50 throw new ArgumentNullException ("underlyingType");
51 type = underlyingType;
52 underlying_type = type;
55 if (XamlLanguage.InitializingTypes) {
56 // These are special. Only XamlLanguage members are with shorthand name.
57 if (type == typeof (PropertyDefinition))
59 else if (type == typeof (MemberDefinition))
62 Name = GetXamlName (type);
63 PreferredXamlNamespace = XamlLanguage.Xaml2006Namespace;
64 } else if ((xt = XamlLanguage.AllTypes.FirstOrDefault (t => t.UnderlyingType == type)) != null) {
66 PreferredXamlNamespace = XamlLanguage.Xaml2006Namespace;
68 Name = GetXamlName (type);
69 PreferredXamlNamespace = String.Format ("clr-namespace:{0};assembly={1}", type.Namespace, type.Assembly.GetName ().Name);
71 if (type.IsGenericType) {
72 TypeArguments = new List<XamlType> ();
73 foreach (var gta in type.GetGenericArguments ())
74 TypeArguments.Add (schemaContext.GetXamlType (gta));
78 public XamlType (string unknownTypeNamespace, string unknownTypeName, IList<XamlType> typeArguments, XamlSchemaContext schemaContext)
79 : this (schemaContext, null)
81 if (unknownTypeNamespace == null)
82 throw new ArgumentNullException ("unknownTypeNamespace");
83 if (unknownTypeName == null)
84 throw new ArgumentNullException ("unknownTypeName");
85 if (schemaContext == null)
86 throw new ArgumentNullException ("schemaContext");
88 type = typeof (object);
89 Name = unknownTypeName;
90 PreferredXamlNamespace = unknownTypeNamespace;
91 TypeArguments = typeArguments != null && typeArguments.Count == 0 ? null : typeArguments;
92 explicit_ns = unknownTypeNamespace;
95 protected XamlType (string typeName, IList<XamlType> typeArguments, XamlSchemaContext schemaContext)
96 : this (String.Empty, typeName, typeArguments, schemaContext)
100 XamlType (XamlSchemaContext schemaContext, XamlTypeInvoker invoker)
102 if (schemaContext == null)
103 throw new ArgumentNullException ("schemaContext");
104 SchemaContext = schemaContext;
105 this.invoker = invoker ?? new XamlTypeInvoker (this);
108 Type type, underlying_type;
112 // populated properties
114 XamlTypeInvoker invoker;
116 internal EventHandler<XamlSetMarkupExtensionEventArgs> SetMarkupExtensionHandler {
117 get { return LookupSetMarkupExtensionHandler (); }
120 internal EventHandler<XamlSetTypeConverterEventArgs> SetTypeConverterHandler {
121 get { return LookupSetTypeConverterHandler (); }
124 public IList<XamlType> AllowedContentTypes {
125 get { return LookupAllowedContentTypes (); }
128 public XamlType BaseType {
129 get { return LookupBaseType (); }
132 public bool ConstructionRequiresArguments {
133 get { return LookupConstructionRequiresArguments (); }
136 public XamlMember ContentProperty {
137 get { return LookupContentProperty (); }
140 public IList<XamlType> ContentWrappers {
141 get { return LookupContentWrappers (); }
144 public XamlValueConverter<XamlDeferringLoader> DeferringLoader {
145 get { return LookupDeferringLoader (); }
148 public XamlTypeInvoker Invoker {
149 get { return LookupInvoker (); }
152 public bool IsAmbient {
153 get { return LookupIsAmbient (); }
156 public bool IsArray {
157 get { return LookupCollectionKind () == XamlCollectionKind.Array; }
160 // it somehow treats array as not a collection...
161 public bool IsCollection {
162 get { return LookupCollectionKind () == XamlCollectionKind.Collection; }
165 public bool IsConstructible {
166 get { return LookupIsConstructible (); }
169 public bool IsDictionary {
170 get { return LookupCollectionKind () == XamlCollectionKind.Dictionary; }
173 public bool IsGeneric {
174 get { return type.IsGenericType; }
177 public bool IsMarkupExtension {
178 get { return LookupIsMarkupExtension (); }
180 public bool IsNameScope {
181 get { return LookupIsNameScope (); }
183 public bool IsNameValid {
184 get { return XamlLanguage.IsValidXamlName (Name); }
187 public bool IsNullable {
188 get { return LookupIsNullable (); }
191 public bool IsPublic {
192 get { return LookupIsPublic (); }
195 public bool IsUnknown {
196 get { return LookupIsUnknown (); }
199 public bool IsUsableDuringInitialization {
200 get { return LookupUsableDuringInitialization (); }
203 public bool IsWhitespaceSignificantCollection {
204 get { return LookupIsWhitespaceSignificantCollection (); }
207 public bool IsXData {
208 get { return LookupIsXData (); }
211 public XamlType ItemType {
212 get { return LookupItemType (); }
215 public XamlType KeyType {
216 get { return LookupKeyType (); }
219 public XamlType MarkupExtensionReturnType {
220 get { return LookupMarkupExtensionReturnType (); }
223 public string Name { get; private set; }
225 public string PreferredXamlNamespace { get; private set; }
227 public XamlSchemaContext SchemaContext { get; private set; }
229 public bool TrimSurroundingWhitespace {
230 get { return LookupTrimSurroundingWhitespace (); }
233 public IList<XamlType> TypeArguments { get; private set; }
235 public XamlValueConverter<TypeConverter> TypeConverter {
236 get { return LookupTypeConverter (); }
239 public Type UnderlyingType {
240 get { return LookupUnderlyingType (); }
243 public XamlValueConverter<ValueSerializer> ValueSerializer {
244 get { return LookupValueSerializer (); }
247 internal string GetInternalXmlName ()
249 if (IsMarkupExtension && Name.EndsWith ("Extension", StringComparison.Ordinal))
250 return Name.Substring (0, Name.Length - 9);
251 var stn = XamlLanguage.SpecialNames.FirstOrDefault (s => s.Type == this);
252 return stn != null ? stn.Name : Name;
255 public static bool operator == (XamlType left, XamlType right)
257 return IsNull (left) ? IsNull (right) : left.Equals (right);
260 static bool IsNull (XamlType a)
262 return Object.ReferenceEquals (a, null);
265 public static bool operator != (XamlType left, XamlType right)
267 return !(left == right);
270 public bool Equals (XamlType other)
272 // It does not compare XamlSchemaContext.
273 return !IsNull (other) &&
274 UnderlyingType == other.UnderlyingType &&
275 Name == other.Name &&
276 PreferredXamlNamespace == other.PreferredXamlNamespace && TypeArguments.ListEquals (other.TypeArguments);
279 public override bool Equals (object obj)
281 var a = obj as XamlType;
285 public override int GetHashCode ()
287 if (UnderlyingType != null)
288 return UnderlyingType.GetHashCode ();
289 int x = Name.GetHashCode () << 7 + PreferredXamlNamespace.GetHashCode ();
290 if (TypeArguments != null)
291 foreach (var t in TypeArguments)
292 x = t.GetHashCode () + x << 5;
296 public override string ToString ()
298 return new XamlTypeName (this).ToString ();
299 //return String.IsNullOrEmpty (PreferredXamlNamespace) ? Name : String.Concat ("{", PreferredXamlNamespace, "}", Name);
302 public virtual bool CanAssignTo (XamlType xamlType)
304 if (this.UnderlyingType == null)
305 return xamlType == XamlLanguage.Object;
306 var ut = xamlType.UnderlyingType ?? typeof (object);
307 return ut.IsAssignableFrom (UnderlyingType);
310 public XamlMember GetAliasedProperty (XamlDirective directive)
312 return LookupAliasedProperty (directive);
315 public ICollection<XamlMember> GetAllAttachableMembers ()
317 return new List<XamlMember> (LookupAllAttachableMembers ());
320 public ICollection<XamlMember> GetAllMembers ()
322 return new List<XamlMember> (LookupAllMembers ());
325 public XamlMember GetAttachableMember (string name)
327 return LookupAttachableMember (name);
330 public XamlMember GetMember (string name)
332 return LookupMember (name, true);
335 public IList<XamlType> GetPositionalParameters (int parameterCount)
337 return LookupPositionalParameters (parameterCount);
340 public virtual IList<string> GetXamlNamespaces ()
342 throw new NotImplementedException ();
343 /* this does not work like documented!
344 if (explicit_ns != null)
345 return new string [] {explicit_ns};
346 var l = SchemaContext.GetAllXamlNamespaces ();
348 return new List<string> (l);
349 return new string [] {String.Empty};
355 protected virtual XamlMember LookupAliasedProperty (XamlDirective directive)
357 if (directive == XamlLanguage.Key) {
358 var a = this.GetCustomAttribute<DictionaryKeyPropertyAttribute> ();
359 return a != null ? GetMember (a.Name) : null;
361 if (directive == XamlLanguage.Name) {
362 var a = this.GetCustomAttribute<RuntimeNamePropertyAttribute> ();
363 return a != null ? GetMember (a.Name) : null;
365 if (directive == XamlLanguage.Uid) {
366 var a = this.GetCustomAttribute<UidPropertyAttribute> ();
367 return a != null ? GetMember (a.Name) : null;
369 if (directive == XamlLanguage.Lang) {
370 var a = this.GetCustomAttribute<XmlLangPropertyAttribute> ();
371 return a != null ? GetMember (a.Name) : null;
376 protected virtual IEnumerable<XamlMember> LookupAllAttachableMembers ()
378 if (UnderlyingType == null)
379 return BaseType != null ? BaseType.GetAllAttachableMembers () : null;
380 return DoLookupAllAttachableMembers ();
383 IEnumerable<XamlMember> DoLookupAllAttachableMembers ()
385 yield break; // FIXME: what to return here?
388 static readonly XamlMember [] empty_array = new XamlMember [0];
390 protected virtual IEnumerable<XamlMember> LookupAllMembers ()
392 if (UnderlyingType == null)
393 return BaseType != null ? BaseType.GetAllMembers () : empty_array;
394 if (all_members_cache == null) {
395 all_members_cache = new List<XamlMember> (DoLookupAllMembers ());
396 all_members_cache.Sort (TypeExtensionMethods.CompareMembers);
398 return all_members_cache;
401 List<XamlMember> all_members_cache;
403 IEnumerable<XamlMember> DoLookupAllMembers ()
405 // This is a hack that is likely required due to internal implementation difference in System.Uri. Our Uri has two readonly collection properties
406 if (this == XamlLanguage.Uri)
409 var bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
411 foreach (var pi in UnderlyingType.GetProperties (bf))
412 if (pi.CanRead && (pi.CanWrite || IsCollectionType (pi.PropertyType) || typeof (IXmlSerializable).IsAssignableFrom (pi.PropertyType)) && pi.GetIndexParameters ().Length == 0)
413 yield return new XamlMember (pi, SchemaContext);
414 foreach (var ei in UnderlyingType.GetEvents (bf))
415 yield return new XamlMember (ei, SchemaContext);
418 static bool IsPublicAccessor (MethodInfo mi)
420 return mi != null && mi.IsPublic;
423 bool IsCollectionType (Type type)
427 var xt = SchemaContext.GetXamlType (type);
428 return xt.LookupCollectionKind () != XamlCollectionKind.None;
431 protected virtual IList<XamlType> LookupAllowedContentTypes ()
433 // the actual implementation is very different from what is documented :(
437 var l = new List<XamlType> ();
438 if (ContentWrappers != null)
439 l.AddRange (ContentWrappers);
440 if (ContentProperty != null)
441 l.Add (ContentProperty.Type);
442 if (ItemType != null)
444 return l.Count > 0 ? l : null;
448 protected virtual XamlMember LookupAttachableMember (string name)
450 throw new NotImplementedException ();
454 protected virtual XamlType LookupBaseType ()
456 if (base_type == null) {
457 if (UnderlyingType == null)
458 // FIXME: probably something advanced is needed here.
459 base_type = new XamlType (typeof (object), SchemaContext, Invoker);
461 base_type = type.BaseType == null || type.BaseType == typeof (object) ? null : new XamlType (type.BaseType, SchemaContext, Invoker);
466 // This implementation is not verified. (No place to use.)
467 protected virtual XamlCollectionKind LookupCollectionKind ()
469 if (UnderlyingType == null)
470 return BaseType != null ? BaseType.LookupCollectionKind () : XamlCollectionKind.None;
472 return XamlCollectionKind.Array;
474 if (type.ImplementsAnyInterfacesOf (typeof (IDictionary), typeof (IDictionary<,>)))
475 return XamlCollectionKind.Dictionary;
477 if (type.ImplementsAnyInterfacesOf (typeof (IList), typeof (ICollection<>)))
478 return XamlCollectionKind.Collection;
480 return XamlCollectionKind.None;
483 protected virtual bool LookupConstructionRequiresArguments ()
485 if (UnderlyingType == null)
488 // not sure if it is required, but MemberDefinition return true while they are abstract and it makes no sense.
489 if (UnderlyingType.IsAbstract)
492 // FIXME: probably some primitive types are treated as special.
493 switch (Type.GetTypeCode (UnderlyingType)) {
494 case TypeCode.String:
496 case TypeCode.Object:
497 if (UnderlyingType == typeof (TimeSpan))
504 return UnderlyingType.GetConstructor (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null) == null;
507 protected virtual XamlMember LookupContentProperty ()
509 var a = this.GetCustomAttribute<ContentPropertyAttribute> ();
510 return a != null && a.Name != null ? GetMember (a.Name) : null;
513 protected virtual IList<XamlType> LookupContentWrappers ()
515 if (GetCustomAttributeProvider () == null)
518 var arr = GetCustomAttributeProvider ().GetCustomAttributes (typeof (ContentWrapperAttribute), false);
519 if (arr == null || arr.Length == 0)
521 var l = new XamlType [arr.Length];
522 for (int i = 0; i < l.Length; i++)
523 l [i] = SchemaContext.GetXamlType (((ContentWrapperAttribute) arr [i]).ContentWrapper);
527 internal ICustomAttributeProvider GetCustomAttributeProvider ()
529 return LookupCustomAttributeProvider ();
532 protected internal virtual ICustomAttributeProvider LookupCustomAttributeProvider ()
534 return UnderlyingType;
537 protected virtual XamlValueConverter<XamlDeferringLoader> LookupDeferringLoader ()
539 throw new NotImplementedException ();
542 protected virtual XamlTypeInvoker LookupInvoker ()
547 protected virtual bool LookupIsAmbient ()
549 return this.GetCustomAttribute<AmbientAttribute> () != null;
552 // It is documented as if it were to reflect spec. section 5.2,
553 // but the actual behavior shows it is *totally* wrong.
554 // Here I have implemented this based on the nunit test results. sigh.
555 protected virtual bool LookupIsConstructible ()
557 if (UnderlyingType == null)
559 if (IsMarkupExtension)
561 if (UnderlyingType.IsAbstract)
568 protected virtual bool LookupIsMarkupExtension ()
570 return typeof (MarkupExtension).IsAssignableFrom (UnderlyingType);
573 protected virtual bool LookupIsNameScope ()
575 return typeof (INameScope).IsAssignableFrom (UnderlyingType);
578 protected virtual bool LookupIsNullable ()
580 return !type.IsValueType || type.ImplementsInterface (typeof (Nullable<>));
583 protected virtual bool LookupIsPublic ()
585 return underlying_type == null || underlying_type.IsPublic || underlying_type.IsNestedPublic;
588 protected virtual bool LookupIsUnknown ()
590 return UnderlyingType == null;
593 protected virtual bool LookupIsWhitespaceSignificantCollection ()
595 // probably for unknown types, it should preserve whitespaces.
596 return IsUnknown || this.GetCustomAttribute<WhitespaceSignificantCollectionAttribute> () != null;
599 protected virtual bool LookupIsXData ()
601 return CanAssignTo (SchemaContext.GetXamlType (typeof (IXmlSerializable)));
604 protected virtual XamlType LookupItemType ()
607 return new XamlType (type.GetElementType (), SchemaContext);
610 return new XamlType (typeof (object), SchemaContext);
611 return new XamlType (type.GetGenericArguments () [1], SchemaContext);
616 return new XamlType (typeof (object), SchemaContext);
617 return new XamlType (type.GetGenericArguments () [0], SchemaContext);
620 protected virtual XamlType LookupKeyType ()
625 return new XamlType (typeof (object), SchemaContext);
626 return new XamlType (type.GetGenericArguments () [0], SchemaContext);
629 protected virtual XamlType LookupMarkupExtensionReturnType ()
631 var a = this.GetCustomAttribute<MarkupExtensionReturnTypeAttribute> ();
632 return a != null ? new XamlType (a.ReturnType, SchemaContext) : null;
635 protected virtual XamlMember LookupMember (string name, bool skipReadOnlyCheck)
637 // FIXME: verify if this does not filter out events.
638 return GetAllMembers ().FirstOrDefault (m => m.Name == name && (skipReadOnlyCheck || !m.IsReadOnly || m.Type.IsCollection || m.Type.IsDictionary || m.Type.IsArray));
641 protected virtual IList<XamlType> LookupPositionalParameters (int parameterCount)
643 if (UnderlyingType == null/* || !IsMarkupExtension*/) // see nunit tests...
646 // check if there is applicable ConstructorArgumentAttribute.
647 // If there is, then return its type.
648 if (parameterCount == 1) {
649 foreach (var xm in GetAllMembers ()) {
650 var ca = xm.GetCustomAttributeProvider ().GetCustomAttribute<ConstructorArgumentAttribute> (false);
652 return new XamlType [] {xm.Type};
656 var methods = (from m in UnderlyingType.GetConstructors (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) where m.GetParameters ().Length == parameterCount select m).ToArray ();
657 if (methods.Length == 1)
658 return (from p in methods [0].GetParameters () select SchemaContext.GetXamlType (p.ParameterType)).ToArray ();
660 if (SchemaContext.SupportMarkupExtensionsWithDuplicateArity)
661 throw new NotSupportedException ("The default LookupPositionalParameters implementation does not allow duplicate arity of markup extensions");
665 BindingFlags flags_get_static = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
667 protected virtual EventHandler<XamlSetMarkupExtensionEventArgs> LookupSetMarkupExtensionHandler ()
669 var a = this.GetCustomAttribute<XamlSetMarkupExtensionAttribute> ();
672 var mi = type.GetMethod (a.XamlSetMarkupExtensionHandler, flags_get_static);
674 throw new ArgumentException ("Binding to XamlSetMarkupExtensionHandler failed");
675 return (EventHandler<XamlSetMarkupExtensionEventArgs>) Delegate.CreateDelegate (typeof (EventHandler<XamlSetMarkupExtensionEventArgs>), mi);
678 protected virtual EventHandler<XamlSetTypeConverterEventArgs> LookupSetTypeConverterHandler ()
680 var a = this.GetCustomAttribute<XamlSetTypeConverterAttribute> ();
683 var mi = type.GetMethod (a.XamlSetTypeConverterHandler, flags_get_static);
685 throw new ArgumentException ("Binding to XamlSetTypeConverterHandler failed");
686 return (EventHandler<XamlSetTypeConverterEventArgs>) Delegate.CreateDelegate (typeof (EventHandler<XamlSetTypeConverterEventArgs>), mi);
689 protected virtual bool LookupTrimSurroundingWhitespace ()
691 return this.GetCustomAttribute<TrimSurroundingWhitespaceAttribute> () != null;
694 protected virtual XamlValueConverter<TypeConverter> LookupTypeConverter ()
696 var t = UnderlyingType;
700 // equivalent to TypeExtension.
701 // FIXME: not sure if it should be specially handled here.
702 if (t == typeof (Type))
703 t = typeof (TypeExtension);
705 var a = GetCustomAttributeProvider ();
706 var ca = a != null ? a.GetCustomAttribute<TypeConverterAttribute> (false) : null;
708 return SchemaContext.GetValueConverter<TypeConverter> (Type.GetType (ca.ConverterTypeName), this);
710 if (t == typeof (object)) // This is a special case. ConverterType is null.
711 return SchemaContext.GetValueConverter<TypeConverter> (null, this);
713 // It's still not decent to check CollectionConverter.
714 var tct = TypeDescriptor.GetConverter (t).GetType ();
715 if (tct != typeof (TypeConverter) && tct != typeof (CollectionConverter) && tct != typeof (ReferenceConverter))
716 return SchemaContext.GetValueConverter<TypeConverter> (tct, this);
720 protected virtual Type LookupUnderlyingType ()
722 return underlying_type;
725 protected virtual bool LookupUsableDuringInitialization ()
727 var a = this.GetCustomAttribute<UsableDuringInitializationAttribute> ();
728 return a != null && a.Usable;
731 static XamlValueConverter<ValueSerializer> string_value_serializer;
733 protected virtual XamlValueConverter<ValueSerializer> LookupValueSerializer ()
735 return LookupValueSerializer (this, GetCustomAttributeProvider ());
738 internal static XamlValueConverter<ValueSerializer> LookupValueSerializer (XamlType targetType, ICustomAttributeProvider provider)
740 if (provider == null)
743 var a = provider.GetCustomAttribute<ValueSerializerAttribute> (true);
745 return new XamlValueConverter<ValueSerializer> (a.ValueSerializerType ?? Type.GetType (a.ValueSerializerTypeName), targetType);
747 if (targetType.BaseType != null) {
748 var ret = targetType.BaseType.LookupValueSerializer ();
753 if (targetType.UnderlyingType == typeof (string)) {
754 if (string_value_serializer == null)
755 string_value_serializer = new XamlValueConverter<ValueSerializer> (typeof (StringValueSerializer), targetType);
756 return string_value_serializer;
762 static string GetXamlName (Type type)
768 n = GetXamlName (type.DeclaringType) + "+" + type.Name;
769 if (type.IsGenericType && !type.ContainsGenericParameters) // the latter condition is to filter out "nested non-generic type within generic type".
770 return n.Substring (0, n.IndexOf ('`'));