Merge pull request #409 from Alkarex/patch-1
[mono.git] / mcs / class / System.Runtime.Serialization / System.Runtime.Serialization / KnownTypeCollection.cs
1 //
2 // KnownTypeCollection.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2005 Novell, Inc.  http://www.novell.com
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 //
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 //
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 #if NET_2_0
29 using System;
30 using System.Collections;
31 using System.Collections.Generic;
32 using System.Collections.ObjectModel;
33 using System.Linq;
34 using System.Reflection;
35 using System.Xml;
36 using System.Xml.Schema;
37
38 using QName = System.Xml.XmlQualifiedName;
39 using System.Xml.Serialization;
40
41 namespace System.Runtime.Serialization
42 {
43 /*
44         XmlFormatter implementation design inference:
45
46         type definitions:
47         - No XML Schema types are directly used. There are some maps from
48           xs:blahType to ms:blahType where the namespaceURI for prefix "ms" is
49           "http://schemas.microsoft.com/2003/10/Serialization/" .
50
51         serializable types:
52         - An object being serialized 1) must be of type System.Object, or
53           2) must be null, or 3) must have either a [DataContract] attribute
54           or a [Serializable] attribute to be serializable.
55         - When the object is either of type System.Object or null, then the
56           XML type is "anyType".
57         - When the object is [Serializable], then the runtime-serialization
58           compatible object graph is written.
59         - Otherwise the serialization is based on contract attributes.
60           ([Serializable] takes precedence).
61
62         type derivation:
63         - For type A to be serializable, the base type B of A must be
64           serializable.
65         - If a type which is [Serializable] and whose base type has a
66           [DataContract], then for base type members [DataContract] is taken.
67         - It is vice versa i.e. if the base type is [Serializable] and the
68           derived type has a [DataContract], then [Serializable] takes place
69           for base members.
70
71         known type collection:
72         - It internally manages mapping store keyed by contract QNames.
73           KnownTypeCollection.Add() checks if the same QName contract already
74           exists (and raises InvalidOperationException if required).
75
76 */
77         internal static class TypeExtensions
78         {
79                 public static T GetCustomAttribute<T> (this MemberInfo type, bool inherit)
80                 {
81                         var arr = type.GetCustomAttributes (typeof (T), inherit);
82                         return arr != null && arr.Length == 1 ? (T) arr [0] : default (T);
83                 }
84
85                 public static IEnumerable<Type> GetInterfacesOrSelfInterface (this Type type)
86                 {
87                         if (type.IsInterface)
88                                 yield return type;
89                         foreach (var t in type.GetInterfaces ())
90                                 yield return t;
91                 }
92
93                 public static bool ImplementsInterface (this Type type, Type iface)
94                 {
95                         foreach (var t in type.GetInterfacesOrSelfInterface ()) {
96                                 if (t == iface)
97                                         return true;
98                         }
99
100                         var baseType = type.BaseType;
101                         if (baseType != null)
102                                 return baseType.ImplementsInterface (iface);
103                         
104                         return false;
105                 }
106         }
107
108         internal sealed class KnownTypeCollection : Collection<Type>
109         {
110                 internal const string MSSimpleNamespace =
111                         "http://schemas.microsoft.com/2003/10/Serialization/";
112                 internal const string MSArraysNamespace =
113                         "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
114                 internal const string DefaultClrNamespaceBase =
115                         "http://schemas.datacontract.org/2004/07/";
116                 internal const string DefaultClrNamespaceSystem =
117                         "http://schemas.datacontract.org/2004/07/System";
118
119
120                 static QName any_type, bool_type,
121                         byte_type, date_type, decimal_type, double_type,
122                         float_type, string_type,
123                         short_type, int_type, long_type,
124                         ubyte_type, ushort_type, uint_type, ulong_type,
125                         // non-TypeCode
126                         any_uri_type, base64_type, duration_type, qname_type,
127                         // custom in ms nsURI schema
128                         char_type, guid_type,
129                         // not in ms nsURI schema
130                         dbnull_type, date_time_offset_type;
131
132                 // XmlSchemaType.GetBuiltInPrimitiveType() does not exist in moonlight, so I had to explicitly add them. And now that we have it, it does not make much sense to use #if MOONLIGHT ... #endif for XmlSchemaType anymore :-(
133                 static Dictionary<string,Type> xs_predefined_types = new Dictionary<string,Type> ();
134
135                 static KnownTypeCollection ()
136                 {
137                         string s = MSSimpleNamespace;
138                         any_type = new QName ("anyType", s);
139                         any_uri_type = new QName ("anyURI", s);
140                         bool_type = new QName ("boolean", s);
141                         base64_type = new QName ("base64Binary", s);
142                         date_type = new QName ("dateTime", s);
143                         duration_type = new QName ("duration", s);
144                         qname_type = new QName ("QName", s);
145                         decimal_type = new QName ("decimal", s);
146                         double_type = new QName ("double", s);
147                         float_type = new QName ("float", s);
148                         byte_type = new QName ("byte", s);
149                         short_type = new QName ("short", s);
150                         int_type = new QName ("int", s);
151                         long_type = new QName ("long", s);
152                         ubyte_type = new QName ("unsignedByte", s);
153                         ushort_type = new QName ("unsignedShort", s);
154                         uint_type = new QName ("unsignedInt", s);
155                         ulong_type = new QName ("unsignedLong", s);
156                         string_type = new QName ("string", s);
157                         guid_type = new QName ("guid", s);
158                         char_type = new QName ("char", s);
159
160                         dbnull_type = new QName ("DBNull", DefaultClrNamespaceBase + "System");
161                         date_time_offset_type = new QName ("DateTimeOffset", DefaultClrNamespaceBase + "System");
162
163                         xs_predefined_types.Add ("string", typeof (string));
164                         xs_predefined_types.Add ("boolean", typeof (bool));
165                         xs_predefined_types.Add ("float", typeof (float));
166                         xs_predefined_types.Add ("double", typeof (double));
167                         xs_predefined_types.Add ("decimal", typeof (decimal));
168                         xs_predefined_types.Add ("duration", typeof (TimeSpan));
169                         xs_predefined_types.Add ("dateTime", typeof (DateTime));
170                         xs_predefined_types.Add ("date", typeof (DateTime));
171                         xs_predefined_types.Add ("time", typeof (DateTime));
172                         xs_predefined_types.Add ("gYearMonth", typeof (DateTime));
173                         xs_predefined_types.Add ("gYear", typeof (DateTime));
174                         xs_predefined_types.Add ("gMonthDay", typeof (DateTime));
175                         xs_predefined_types.Add ("gDay", typeof (DateTime));
176                         xs_predefined_types.Add ("gMonth", typeof (DateTime));
177                         xs_predefined_types.Add ("hexBinary", typeof (byte []));
178                         xs_predefined_types.Add ("base64Binary", typeof (byte []));
179                         xs_predefined_types.Add ("anyURI", typeof (Uri));
180                         xs_predefined_types.Add ("QName", typeof (QName));
181                         xs_predefined_types.Add ("NOTATION", typeof (string));
182
183                         xs_predefined_types.Add ("normalizedString", typeof (string));
184                         xs_predefined_types.Add ("token", typeof (string));
185                         xs_predefined_types.Add ("language", typeof (string));
186                         xs_predefined_types.Add ("IDREFS", typeof (string []));
187                         xs_predefined_types.Add ("ENTITIES", typeof (string []));
188                         xs_predefined_types.Add ("NMTOKEN", typeof (string));
189                         xs_predefined_types.Add ("NMTOKENS", typeof (string []));
190                         xs_predefined_types.Add ("Name", typeof (string));
191                         xs_predefined_types.Add ("NCName", typeof (string));
192                         xs_predefined_types.Add ("ID", typeof (string));
193                         xs_predefined_types.Add ("IDREF", typeof (string));
194                         xs_predefined_types.Add ("ENTITY", typeof (string));
195
196                         xs_predefined_types.Add ("integer", typeof (decimal));
197                         xs_predefined_types.Add ("nonPositiveInteger", typeof (int));
198                         xs_predefined_types.Add ("negativeInteger", typeof (int));
199                         xs_predefined_types.Add ("long", typeof (long));
200                         xs_predefined_types.Add ("int", typeof (int));
201                         xs_predefined_types.Add ("short", typeof (short));
202                         xs_predefined_types.Add ("byte", typeof (sbyte));
203                         xs_predefined_types.Add ("nonNegativeInteger", typeof (decimal));
204                         xs_predefined_types.Add ("unsignedLong", typeof (ulong));
205                         xs_predefined_types.Add ("unsignedInt", typeof (uint));
206                         xs_predefined_types.Add ("unsignedShort", typeof (ushort));
207                         xs_predefined_types.Add ("unsignedByte", typeof (byte));
208                         xs_predefined_types.Add ("positiveInteger", typeof (decimal));
209
210                         xs_predefined_types.Add ("anyType", typeof (object));
211                 }
212
213                 // FIXME: find out how QName and guid are processed
214
215                 internal QName GetXmlName (Type type)
216                 {
217                         SerializationMap map = FindUserMap (type);
218                         if (map != null)
219                                 return map.XmlName;
220                         return GetPredefinedTypeName (type);
221                 }
222
223                 internal static QName GetPredefinedTypeName (Type type)
224                 {
225                         QName name = GetPrimitiveTypeName (type);
226                         if (name != QName.Empty)
227                                 return name;
228                         if (type == typeof (DBNull))
229                                 return dbnull_type;
230                         return QName.Empty;
231                 }
232
233                 internal static QName GetPrimitiveTypeName (Type type)
234                 {
235                         if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>))
236                                 return GetPrimitiveTypeName (type.GetGenericArguments () [0]);
237
238                         if (type.IsEnum)
239                                 return QName.Empty;
240
241                         switch (Type.GetTypeCode (type)) {
242                         case TypeCode.Object: // other than System.Object
243                         case TypeCode.DBNull: // it is natively mapped, but not in ms serialization namespace.
244                         case TypeCode.Empty:
245                         default:
246                                 if (type == typeof (object))
247                                         return any_type;
248                                 if (type == typeof (Guid))
249                                         return guid_type;
250                                 if (type == typeof (TimeSpan))
251                                         return duration_type;
252                                 if (type == typeof (byte []))
253                                         return base64_type;
254                                 if (type == typeof (Uri))
255                                         return any_uri_type;
256                                 if (type == typeof (DateTimeOffset))
257                                         return date_time_offset_type;
258                                 return QName.Empty;
259                         case TypeCode.Boolean:
260                                 return bool_type;
261                         case TypeCode.Byte:
262                                 return ubyte_type;
263                         case TypeCode.Char:
264                                 return char_type;
265                         case TypeCode.DateTime:
266                                 return date_type;
267                         case TypeCode.Decimal:
268                                 return decimal_type;
269                         case TypeCode.Double:
270                                 return double_type;
271                         case TypeCode.Int16:
272                                 return short_type;
273                         case TypeCode.Int32:
274                                 return int_type;
275                         case TypeCode.Int64:
276                                 return long_type;
277                         case TypeCode.SByte:
278                                 return byte_type;
279                         case TypeCode.Single:
280                                 return float_type;
281                         case TypeCode.String:
282                                 return string_type;
283                         case TypeCode.UInt16:
284                                 return ushort_type;
285                         case TypeCode.UInt32:
286                                 return uint_type;
287                         case TypeCode.UInt64:
288                                 return ulong_type;
289                         }
290                 }
291
292                 internal static string PredefinedTypeObjectToString (object obj)
293                 {
294                         Type type = obj.GetType ();
295                         switch (Type.GetTypeCode (type)) {
296                         case TypeCode.Object: // other than System.Object
297                         case TypeCode.Empty:
298                         default:
299                                 if (type == typeof (object))
300                                         return String.Empty;
301                                 if (type == typeof (Guid))
302                                         return XmlConvert.ToString ((Guid) obj);
303                                 if (type == typeof (TimeSpan))
304                                         return XmlConvert.ToString ((TimeSpan) obj);
305                                 if (type == typeof (byte []))
306                                         return Convert.ToBase64String ((byte []) obj);
307                                 if (type == typeof (Uri))
308                                         return ((Uri) obj).ToString ();
309                                 throw new Exception ("Internal error: missing predefined type serialization for type " + type.FullName);
310                         case TypeCode.DBNull: // predefined, but not primitive
311                                 return String.Empty;
312                         case TypeCode.Boolean:
313                                 return XmlConvert.ToString ((bool) obj);
314                         case TypeCode.Byte:
315                                 return XmlConvert.ToString ((int)((byte) obj));
316                         case TypeCode.Char:
317                                 return XmlConvert.ToString ((uint) (char) obj);
318                         case TypeCode.DateTime:
319                                 return XmlConvert.ToString ((DateTime) obj, XmlDateTimeSerializationMode.RoundtripKind);
320                         case TypeCode.Decimal:
321                                 return XmlConvert.ToString ((decimal) obj);
322                         case TypeCode.Double:
323                                 return XmlConvert.ToString ((double) obj);
324                         case TypeCode.Int16:
325                                 return XmlConvert.ToString ((short) obj);
326                         case TypeCode.Int32:
327                                 return XmlConvert.ToString ((int) obj);
328                         case TypeCode.Int64:
329                                 return XmlConvert.ToString ((long) obj);
330                         case TypeCode.SByte:
331                                 return XmlConvert.ToString ((sbyte) obj);
332                         case TypeCode.Single:
333                                 return XmlConvert.ToString ((float) obj);
334                         case TypeCode.String:
335                                 return (string) obj;
336                         case TypeCode.UInt16:
337                                 return XmlConvert.ToString ((int) (ushort) obj);
338                         case TypeCode.UInt32:
339                                 return XmlConvert.ToString ((uint) obj);
340                         case TypeCode.UInt64:
341                                 return XmlConvert.ToString ((ulong) obj);
342                         }
343                 }
344
345                 internal static Type GetPrimitiveTypeFromName (QName name)
346                 {
347                         switch (name.Namespace) {
348                         case DefaultClrNamespaceSystem:
349                                 switch (name.Name) {
350                                 case "DBNull":
351                                         return typeof (DBNull);
352                                 case "DateTimeOffset":
353                                         return typeof (DateTimeOffset);
354                                 }
355                                 break;
356                         case XmlSchema.Namespace:
357                                 return xs_predefined_types.FirstOrDefault (p => p.Key == name.Name).Value;
358                         case MSSimpleNamespace:
359                                 switch (name.Name) {
360                                 case "anyURI":
361                                         return typeof (Uri);
362                                 case "boolean":
363                                         return typeof (bool);
364                                 case "base64Binary":
365                                         return typeof (byte []);
366                                 case "dateTime":
367                                         return typeof (DateTime);
368                                 case "duration":
369                                         return typeof (TimeSpan);
370                                 case "QName":
371                                         return typeof (QName);
372                                 case "decimal":
373                                         return typeof (decimal);
374                                 case "double":
375                                         return typeof (double);
376                                 case "float":
377                                         return typeof (float);
378                                 case "byte":
379                                         return typeof (sbyte);
380                                 case "short":
381                                         return typeof (short);
382                                 case "int":
383                                         return typeof (int);
384                                 case "long":
385                                         return typeof (long);
386                                 case "unsignedByte":
387                                         return typeof (byte);
388                                 case "unsignedShort":
389                                         return typeof (ushort);
390                                 case "unsignedInt":
391                                         return typeof (uint);
392                                 case "unsignedLong":
393                                         return typeof (ulong);
394                                 case "string":
395                                         return typeof (string);
396                                 case "anyType":
397                                         return typeof (object);
398                                 case "guid":
399                                         return typeof (Guid);
400                                 case "char":
401                                         return typeof (char);
402                                 }
403                                 break;
404                         }
405                         return null;
406                 }
407
408
409                 internal static object PredefinedTypeStringToObject (string s,
410                         string name, XmlReader reader)
411                 {
412                         switch (name) {
413                         case "anyURI":
414                                 return new Uri(s,UriKind.RelativeOrAbsolute);
415                         case "boolean":
416                                 return XmlConvert.ToBoolean (s);
417                         case "base64Binary":
418                                 return Convert.FromBase64String (s);
419                         case "dateTime":
420                                 return XmlConvert.ToDateTime (s, XmlDateTimeSerializationMode.RoundtripKind);
421                         case "duration":
422                                 return XmlConvert.ToTimeSpan (s);
423                         case "QName":
424                                 int idx = s.IndexOf (':');
425                                 string l = idx < 0 ? s : s.Substring (idx + 1);
426                                 return idx < 0 ? new QName (l) :
427                                         new QName (l, reader.LookupNamespace (
428                                                 s.Substring (0, idx)));
429                         case "decimal":
430                                 return XmlConvert.ToDecimal (s);
431                         case "double":
432                                 return XmlConvert.ToDouble (s);
433                         case "float":
434                                 return XmlConvert.ToSingle (s);
435                         case "byte":
436                                 return XmlConvert.ToSByte (s);
437                         case "short":
438                                 return XmlConvert.ToInt16 (s);
439                         case "int":
440                                 return XmlConvert.ToInt32 (s);
441                         case "long":
442                                 return XmlConvert.ToInt64 (s);
443                         case "unsignedByte":
444                                 return XmlConvert.ToByte (s);
445                         case "unsignedShort":
446                                 return XmlConvert.ToUInt16 (s);
447                         case "unsignedInt":
448                                 return XmlConvert.ToUInt32 (s);
449                         case "unsignedLong":
450                                 return XmlConvert.ToUInt64 (s);
451                         case "string":
452                                 return s;
453                         case "guid":
454                                 return XmlConvert.ToGuid (s);
455                         case "anyType":
456                                 return s;
457                         case "char":
458                                 return (char) XmlConvert.ToUInt32 (s);
459                         default:
460                                 throw new Exception ("Unanticipated primitive type: " + name);
461                         }
462                 }
463
464                 List<SerializationMap> contracts = new List<SerializationMap> ();
465
466                 public KnownTypeCollection ()
467                 {
468                 }
469
470                 protected override void ClearItems ()
471                 {
472                         base.Clear ();
473                 }
474
475                 protected override void InsertItem (int index, Type type)
476                 {
477                         if (ShouldNotRegister (type))
478                                 return;
479                         if (!Contains (type)) {
480                                 TryRegister (type);
481                                 base.InsertItem (index, type);
482                         }
483                 }
484
485                 // FIXME: it could remove other types' dependencies.
486                 protected override void RemoveItem (int index)
487                 {
488                         lock (this)
489                                 DoRemoveItem (index);
490                 }
491
492                 void DoRemoveItem (int index)
493                 {
494                         Type t = base [index];
495                         List<SerializationMap> l = new List<SerializationMap> ();
496                         foreach (SerializationMap m in contracts) {
497                                 if (m.RuntimeType == t)
498                                         l.Add (m);
499                         }
500                         foreach (SerializationMap m in l) {
501                                 contracts.Remove (m);
502                                 base.RemoveItem (index);
503                         }
504                 }
505
506                 protected override void SetItem (int index, Type type)
507                 {
508                         if (ShouldNotRegister (type))
509                                 return;
510
511                         // Since this collection is not assured to be ordered, it ignores the whole Set operation if the type already exists.
512                         if (Contains (type))
513                                 return;
514
515                         if (index != Count)
516                                 RemoveItem (index);
517                         if (TryRegister (type))
518                                 base.InsertItem (index - 1, type);
519                 }
520
521                 internal SerializationMap FindUserMap (Type type)
522                 {
523                         lock (this) {
524                                 for (int i = 0; i < contracts.Count; i++)
525                                         if (type == contracts [i].RuntimeType)
526                                                 return contracts [i];
527                                 return null;
528                         }
529                 }
530
531                 internal SerializationMap FindUserMap (QName qname)
532                 {
533                         lock (this)
534                                 return contracts.FirstOrDefault (c => c.XmlName == qname);
535                 }
536
537                 internal SerializationMap FindUserMap (QName qname, Type type)
538                 {
539                         lock (this)
540                                 return contracts.FirstOrDefault (c => c.XmlName == qname && c.RuntimeType == type);
541                 }
542
543                 internal Type GetSerializedType (Type type)
544                 {
545                         if (IsPrimitiveNotEnum (type))
546                                 return type;
547                         Type element = GetCollectionElementType (type);
548                         if (element == null)
549                                 return type;
550                         QName name = GetQName (type);
551                         var map = FindUserMap (name, type);
552                         if (map != null)
553                                 return map.RuntimeType;
554                         return type;
555                 }
556
557                 internal QName GetQName (Type type)
558                 {
559                         SerializationMap map = FindUserMap (type);
560                         if (map != null)
561                                 // already mapped.
562                                 return map.XmlName;
563                         return GetStaticQName (type);
564                 }
565
566                 public static QName GetStaticQName (Type type)
567                 {
568                         if (IsPrimitiveNotEnum (type))
569                                 return GetPrimitiveTypeName (type);
570
571                         if (type.IsEnum)
572                                 return GetEnumQName (type);
573
574                         QName qname = GetContractQName (type);
575                         if (qname != null)
576                                 return qname;
577
578                         if (type.GetInterface ("System.Xml.Serialization.IXmlSerializable") != null)
579                                 //FIXME: Reusing GetSerializableQName here, since we just
580                                 //need name of the type..
581                                 return GetSerializableQName (type);
582
583                         qname = GetCollectionContractQName (type);
584                         if (qname != null)
585                                 return qname;
586
587                         Type element = GetCollectionElementType (type);
588                         if (element != null) {
589                                 if (type.IsInterface || IsCustomCollectionType (type, element))
590                                         return GetCollectionQName (element);
591                         }
592
593                         if (GetAttribute<SerializableAttribute> (type) != null)
594                                 return GetSerializableQName (type);
595
596                         // default type map - still uses GetContractQName().
597                         return GetContractQName (type, null, null);
598                 }
599
600                 internal static QName GetContractQName (Type type)
601                 {
602                         var a = GetAttribute<DataContractAttribute> (type);
603                         return a == null ? null : GetContractQName (type, a.Name, a.Namespace);
604                 }
605
606                 static QName GetCollectionContractQName (Type type)
607                 {
608                         var a = GetAttribute<CollectionDataContractAttribute> (type);
609                         return a == null ? null : GetContractQName (type, a.Name, a.Namespace);
610                 }
611
612                 static QName GetContractQName (Type type, string name, string ns)
613                 {
614                         if (name == null)
615                                 name = GetDefaultName (type);
616                         else if (type.IsGenericType) {
617                                 var args = type.GetGenericArguments ();
618                                 for (int i = 0; i < args.Length; i++)
619                                         name = name.Replace ("{" + i + "}", GetStaticQName (args [i]).Name);
620                         }
621
622                         if (ns == null)
623                                 ns = GetDefaultNamespace (type);
624                         return new QName (name, ns);
625                 }
626
627                 static QName GetEnumQName (Type type)
628                 {
629                         string name = null, ns = null;
630
631                         if (!type.IsEnum)
632                                 return null;
633
634                         var dca = GetAttribute<DataContractAttribute> (type);
635
636                         if (dca != null) {
637                                 ns = dca.Namespace;
638                                 name = dca.Name;
639                         }
640
641                         if (ns == null)
642                                 ns = GetDefaultNamespace (type);
643
644                         if (name == null)
645                                 name = type.Namespace == null ? type.Name : type.FullName.Substring (type.Namespace.Length + 1).Replace ('+', '.');
646
647                         return new QName (name, ns);
648                 }
649
650                 internal static string GetDefaultName (Type type)
651                 {
652                         // FIXME: there could be decent ways to get
653                         // the same result...
654                         string name = type.Namespace == null || type.Namespace.Length == 0 ? type.Name : type.FullName.Substring (type.Namespace.Length + 1).Replace ('+', '.');
655                         if (type.IsGenericType) {
656                                 name = name.Substring (0, name.IndexOf ('`')) + "Of";
657                                 foreach (var t in type.GetGenericArguments ())
658                                         name += t.Name; // FIXME: check namespaces too
659                         }
660                         return name;
661                 }
662
663                 internal static string GetDefaultNamespace (Type type)
664                 {
665                         foreach (ContractNamespaceAttribute a in type.Assembly.GetCustomAttributes (typeof (ContractNamespaceAttribute), true))
666                                 if (a.ClrNamespace == type.Namespace)
667                                         return a.ContractNamespace;
668                         return DefaultClrNamespaceBase + type.Namespace;
669                 }
670
671                 static QName GetCollectionQName (Type element)
672                 {
673                         QName eqname = GetStaticQName (element);
674
675                         string ns = eqname.Namespace;
676                         if (eqname.Namespace == MSSimpleNamespace)
677                                 //Arrays of Primitive types
678                                 ns = MSArraysNamespace;
679
680                         return new QName (
681                                 "ArrayOf" + XmlConvert.EncodeLocalName (eqname.Name),
682                                 ns);
683                 }
684
685                 static QName GetSerializableQName (Type type)
686                 {
687 #if !MOONLIGHT
688                         // First, check XmlSchemaProviderAttribute and try GetSchema() to see if it returns a schema in the expected format.
689                         var xpa = type.GetCustomAttribute<XmlSchemaProviderAttribute> (true);
690                         if (xpa != null) {
691                                 var mi = type.GetMethod (xpa.MethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
692                                 if (mi != null) {
693                                         try {
694                                                 var xss = new XmlSchemaSet ();
695                                                 return (XmlQualifiedName) mi.Invoke (null, new object [] {xss});
696                                         } catch {
697                                                 // ignore.
698                                         }
699                                 }
700                         }
701 #endif
702
703                         string xmlName = type.Name;
704                         if (type.IsGenericType) {
705                                 xmlName = xmlName.Substring (0, xmlName.IndexOf ('`')) + "Of";
706                                 foreach (var t in type.GetGenericArguments ())
707                                         xmlName += GetStaticQName (t).Name; // FIXME: check namespaces too
708                         }
709                         string xmlNamespace = GetDefaultNamespace (type);
710                         var x = GetAttribute<XmlRootAttribute> (type);
711                         if (x != null) {
712                                 xmlName = x.ElementName;
713                                 xmlNamespace = x.Namespace;
714                         }
715                         return new QName (XmlConvert.EncodeLocalName (xmlName), xmlNamespace);
716                 }
717
718                 static bool IsPrimitiveNotEnum (Type type)
719                 {
720                         if (type.IsEnum)
721                                 return false;
722                         if (Type.GetTypeCode (type) != TypeCode.Object) // explicitly primitive
723                                 return true;
724                         if (type == typeof (Guid) || type == typeof (object) || type == typeof(TimeSpan) || type == typeof(byte[]) || type == typeof(Uri) || type == typeof(DateTimeOffset)) // special primitives
725                                 return true;
726 #if !MOONLIGHT
727                         // DOM nodes
728                         if (type == typeof (XmlElement) || type == typeof (XmlNode []))
729                                 return true;
730 #endif
731                         // nullable
732                         if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>))
733                                 return IsPrimitiveNotEnum (type.GetGenericArguments () [0]);
734                         return false;
735                 }
736
737                 bool ShouldNotRegister (Type type)
738                 {
739                         return IsPrimitiveNotEnum (type);
740                 }
741
742                 internal bool TryRegister (Type type)
743                 {
744                         lock (this) {
745                                 return DoTryRegister (type);
746                         }
747                 }
748
749                 bool DoTryRegister (Type type)
750                 {
751                         // exclude predefined maps
752                         if (ShouldNotRegister (type))
753                                 return false;
754
755                         if (FindUserMap (type) != null)
756                                 return false;
757
758                         if (RegisterEnum (type) != null)
759                                 return true;
760
761                         if (RegisterDictionary (type) != null)
762                                 return true;
763
764                         if (RegisterCollectionContract (type) != null)
765                                 return true;
766
767                         if (RegisterContract (type) != null)
768                                 return true;
769
770                         if (RegisterIXmlSerializable (type) != null)
771                                 return true;
772
773                         if (RegisterCollection (type) != null)
774                                 return true;
775
776                         if (GetAttribute<SerializableAttribute> (type) != null) {
777                                 RegisterSerializable (type);
778                                 return true;
779                         }
780
781                         RegisterDefaultTypeMap (type);
782                         return true;
783                 }
784
785                 static Type GetCollectionElementType (Type type)
786                 {
787                         if (type.IsArray)
788                                 return type.GetElementType ();
789                         var ifaces = type.GetInterfacesOrSelfInterface ();
790                         foreach (Type i in ifaces)
791                                 if (i.IsGenericType && i.GetGenericTypeDefinition ().Equals (typeof (IEnumerable<>)))
792                                         return i.GetGenericArguments () [0];
793                         foreach (Type i in ifaces)
794                                 if (i == typeof (IEnumerable))
795                                         return typeof (object);
796                         return null;
797                 }
798
799                 internal static T GetAttribute<T> (ICustomAttributeProvider ap) where T : Attribute
800                 {
801                         object [] atts = ap.GetCustomAttributes (typeof (T), false);
802                         return atts.Length == 0 ? null : (T) atts [0];
803                 }
804
805                 private CollectionContractTypeMap RegisterCollectionContract (Type type)
806                 {
807                         var cdca = GetAttribute<CollectionDataContractAttribute> (type);
808                         if (cdca == null)
809                                 return null;
810
811                         Type element = GetCollectionElementType (type);
812                         if (element == null)
813                                 throw new InvalidDataContractException (String.Format ("Type '{0}' is marked as collection contract, but it is not a collection", type));
814                         if (type.GetMethod ("Add", new Type[] { element }) == null)
815                                 throw new InvalidDataContractException (String.Format ("Type '{0}' is marked as collection contract, but missing a public \"Add\" method", type));
816
817                         TryRegister (element); // must be registered before the name conflict check.
818
819                         QName qname = GetCollectionContractQName (type);
820                         CheckStandardQName (qname);
821                         var map = FindUserMap (qname, type);
822                         if (map != null) {
823                                 var cmap = map as CollectionContractTypeMap;
824                                 if (cmap == null) // The runtime type may still differ (between array and other IList; see bug #670560)
825                                         throw new InvalidOperationException (String.Format ("Failed to add type {0} to known type collection. There already is a registered type for XML name {1}", type, qname));
826                         }
827
828                         var ret = new CollectionContractTypeMap (type, cdca, element, qname, this);
829                         contracts.Add (ret);
830                         return ret;
831                 }
832
833                 private CollectionTypeMap RegisterCollection (Type type)
834                 {
835                         Type element = GetCollectionElementType (type);
836                         if (element == null)
837                                 return null;
838
839                         TryRegister (element);
840
841                         /*
842                          * To qualify as a custom collection type, a type must have
843                          * a public parameterless constructor and an "Add" method
844                          * with the correct parameter type in addition to implementing
845                          * one of the collection interfaces.
846                          * 
847                          */
848
849                         if (!type.IsArray && type.IsClass && !IsCustomCollectionType (type, element))
850                                 return null;
851
852                         QName qname = GetCollectionQName (element);
853
854                         var map = FindUserMap (qname, element);
855                         if (map != null) {
856                                 var cmap = map as CollectionTypeMap;
857                                 if (cmap == null) // The runtime type may still differ (between array and other IList; see bug #670560)
858                                         throw new InvalidOperationException (String.Format ("Failed to add type {0} to known type collection. There already is a registered type for XML name {1}", type, qname));
859                                 return cmap;
860                         }
861
862                         CollectionTypeMap ret =
863                                 new CollectionTypeMap (type, element, qname, this);
864                         contracts.Add (ret);
865                         return ret;
866                 }
867
868                 static bool IsCustomCollectionType (Type type, Type elementType)
869                 {
870                         if (!type.IsClass)
871                                 return false;
872                         if (type.GetConstructor (new Type [0]) == null)
873                                 return false;
874                         if (type.GetMethod ("Add", new Type[] { elementType }) == null)
875                                 return false;
876
877                         return true;
878                 }
879
880                 internal static bool IsInterchangeableCollectionType (Type contractType, Type graphType,
881                                                                       out QName collectionQName)
882                 {
883                         collectionQName = null;
884                         if (GetAttribute<CollectionDataContractAttribute> (contractType) != null)
885                                 return false;
886
887                         var type = contractType;
888                         if (type.IsGenericType)
889                                 type = type.GetGenericTypeDefinition ();
890
891                         var elementType = GetCollectionElementType (contractType);
892                         if (elementType == null)
893                                 return false;
894                         
895                         if (contractType.IsArray) {
896                                 if (!graphType.IsArray || !elementType.Equals (graphType.GetElementType ()))
897                                         throw new InvalidCastException (String.Format ("Type '{0}' cannot be converted into '{1}'.", graphType.GetElementType (), elementType));
898                         } else if (!contractType.IsInterface) {
899                                 if (GetAttribute<SerializableAttribute> (contractType) == null)
900                                         return false;
901
902                                 var graphElementType = GetCollectionElementType (graphType);
903                                 if (elementType != graphElementType)
904                                         return false;
905
906                                 if (!IsCustomCollectionType (contractType, elementType))
907                                         return false;
908                         } else if (type.Equals (typeof (IEnumerable)) || type.Equals (typeof (IList)) ||
909                                    type.Equals (typeof (ICollection))) {
910                                 if (!graphType.ImplementsInterface (contractType))
911                                         return false;
912                         } else if (type.Equals (typeof (IEnumerable<>)) || type.Equals (typeof (IList<>)) ||
913                                    type.Equals (typeof (ICollection<>))) {
914                                 var graphElementType = GetCollectionElementType (graphType);
915                                 if (graphElementType != elementType)
916                                         throw new InvalidCastException (String.Format (
917                                                 "Cannot convert type '{0}' into '{1}'.", graphType, contractType));
918
919                                 if (!graphType.ImplementsInterface (contractType))
920                                         return false;
921                         } else {
922                                 return false;
923                         }
924
925                         collectionQName = GetCollectionQName (elementType);
926                         return true;
927                 }
928
929                 static bool ImplementsInterface (Type type, Type iface)
930                 {
931                         foreach (var i in type.GetInterfacesOrSelfInterface ())
932                                 if (iface == i)
933                                         return true;
934                                         
935                         return false;
936                 }
937
938
939                 static bool TypeImplementsIEnumerable (Type type)
940                 {
941                         foreach (var iface in type.GetInterfacesOrSelfInterface ())
942                                 if (iface == typeof (IEnumerable) || (iface.IsGenericType && iface.GetGenericTypeDefinition () == typeof (IEnumerable<>)))
943                                         return true;
944                         
945                         return false;
946                 }
947
948                 static bool TypeImplementsIDictionary (Type type)
949                 {
950                         foreach (var iface in type.GetInterfacesOrSelfInterface ())
951                                 if (iface == typeof (IDictionary) || (iface.IsGenericType && iface.GetGenericTypeDefinition () == typeof (IDictionary<,>)))
952                                         return true;
953
954                         return false;
955                 }
956
957                 // it also supports contract-based dictionary.
958                 private DictionaryTypeMap RegisterDictionary (Type type)
959                 {
960                         if (!TypeImplementsIDictionary (type))
961                                 return null;
962
963                         var cdca = GetAttribute<CollectionDataContractAttribute> (type);
964
965                         DictionaryTypeMap ret =
966                                 new DictionaryTypeMap (type, cdca, this);
967
968                         TryRegister (ret.KeyType);
969                         TryRegister (ret.ValueType);
970
971                         var map = FindUserMap (ret.XmlName, type);
972                         if (map != null) {
973                                 var dmap = map as DictionaryTypeMap;
974                                 if (dmap == null) // The runtime type may still differ (between array and other IList; see bug #670560)
975                                         throw new InvalidOperationException (String.Format ("Failed to add type {0} to known type collection. There already is a registered type for XML name {1}", type, ret.XmlName));
976                         }
977                         contracts.Add (ret);
978
979                         return ret;
980                 }
981
982                 private SerializationMap RegisterSerializable (Type type)
983                 {
984                         QName qname = GetSerializableQName (type);
985
986                         if (FindUserMap (qname, type) != null)
987                                 throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
988
989                         SharedTypeMap ret = new SharedTypeMap (type, qname, this);
990                         contracts.Add (ret);
991                         ret.Initialize ();
992                         return ret;
993                 }
994
995                 private SerializationMap RegisterIXmlSerializable (Type type)
996                 {
997                         if (type.GetInterface ("System.Xml.Serialization.IXmlSerializable") == null)
998                                 return null;
999
1000                         QName qname = GetSerializableQName (type);
1001
1002                         if (FindUserMap (qname, type) != null)
1003                                 throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
1004
1005                         XmlSerializableMap ret = new XmlSerializableMap (type, qname, this);
1006                         contracts.Add (ret);
1007
1008                         return ret;
1009                 }
1010
1011                 void CheckStandardQName (QName qname)
1012                 {
1013                         switch (qname.Namespace) {
1014                         case XmlSchema.Namespace:
1015                         case XmlSchema.InstanceNamespace:
1016                         case MSSimpleNamespace:
1017                         case MSArraysNamespace:
1018                                 throw new InvalidOperationException (String.Format ("Namespace {0} is reserved and cannot be used for user serialization", qname.Namespace));
1019                         }
1020
1021                 }
1022
1023                 private SharedContractMap RegisterContract (Type type)
1024                 {
1025                         QName qname = GetContractQName (type);
1026                         if (qname == null)
1027                                 return null;
1028                         CheckStandardQName (qname);
1029                         if (FindUserMap (qname, type) != null)
1030                                 throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
1031
1032                         SharedContractMap ret = new SharedContractMap (type, qname, this);
1033                         contracts.Add (ret);
1034                         ret.Initialize ();
1035
1036                         if (type.BaseType != typeof (object)) {
1037                                 TryRegister (type.BaseType);
1038                                 if (!FindUserMap (type.BaseType).IsContractAllowedType)
1039                                         throw new InvalidDataContractException (String.Format ("To be serializable by data contract, type '{0}' cannot inherit from non-contract and non-Serializable type '{1}'", type, type.BaseType));
1040                         }
1041
1042                         object [] attrs = type.GetCustomAttributes (typeof (KnownTypeAttribute), true);
1043                         for (int i = 0; i < attrs.Length; i++) {
1044                                 KnownTypeAttribute kt = (KnownTypeAttribute) attrs [i];
1045                                 foreach (var t in kt.GetTypes (type))
1046                                         TryRegister (t);
1047                         }
1048
1049                         return ret;
1050                 }
1051
1052                 DefaultTypeMap RegisterDefaultTypeMap (Type type)
1053                 {
1054                         DefaultTypeMap ret = new DefaultTypeMap (type, this);
1055                         contracts.Add (ret);
1056                         ret.Initialize ();
1057                         return ret;
1058                 }
1059
1060                 private EnumMap RegisterEnum (Type type)
1061                 {
1062                         QName qname = GetEnumQName (type);
1063                         if (qname == null)
1064                                 return null;
1065
1066                         if (FindUserMap (qname, type) != null)
1067                                 throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
1068
1069                         EnumMap ret =
1070                                 new EnumMap (type, qname, this);
1071                         contracts.Add (ret);
1072                         return ret;
1073                 }
1074         }
1075 }
1076 #endif