2f87760bb7d42f6f39e1f48e491edc742f1afbb4
[mono.git] / mcs / class / System.XML / System.Xml.Serialization / TypeTranslator.cs
1 //
2 // System.Xml.Serialization.TypeTranslator
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //      Erik LeBel (eriklebel@yahoo.ca)
7 //  Lluis Sanchez Gual (lluis@ximian.com)
8 //
9 // (C) 2002 Ximian, Inc (http://www.ximian.com)
10 // (C) 2003 Erik Lebel
11 //
12
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System;
35 using System.Collections;
36 using System.Globalization;
37 using System.Xml.Schema;
38
39 namespace System.Xml.Serialization
40 {
41         internal class TypeTranslator
42         {
43                 static Hashtable nameCache;
44                 static Hashtable primitiveTypes;
45                 static Hashtable primitiveArrayTypes;
46                 static Hashtable primitiveNullableTypes;
47
48 #if TARGET_JVM
49                 const string AppDomainCacheName = "System.Xml.Serialization.TypeTranslator.AppDomainCache";
50                 static Hashtable AppDomainCache {
51                         get {
52                                 Hashtable res = (Hashtable)AppDomain.CurrentDomain.GetData(AppDomainCacheName);
53
54                                 if(res == null) {
55                                         lock(AppDomainCacheName) {
56                                                 res = (Hashtable)AppDomain.CurrentDomain.GetData(AppDomainCacheName);
57                                                 if (res == null) {
58                                                         res = new Hashtable();
59                                                         AppDomain.CurrentDomain.SetData(AppDomainCacheName, res);
60                                                 }
61                                         }
62                                 }
63
64                                 return res;
65                         }
66                 }
67 #endif
68
69                 static TypeTranslator ()
70                 {
71                         nameCache = new Hashtable ();
72                         primitiveArrayTypes = new Hashtable ();
73
74                         // XSD Types with direct map to CLR types
75
76                         nameCache.Add (typeof (bool), new TypeData (typeof (bool), "boolean", true));
77                         nameCache.Add (typeof (short), new TypeData (typeof (short), "short", true));
78                         nameCache.Add (typeof (ushort), new TypeData (typeof (ushort), "unsignedShort", true));
79                         nameCache.Add (typeof (int), new TypeData (typeof (int), "int", true));
80                         nameCache.Add (typeof (uint), new TypeData (typeof (uint), "unsignedInt", true));
81                         nameCache.Add (typeof (long), new TypeData (typeof (long), "long", true));
82                         nameCache.Add (typeof (ulong), new TypeData (typeof (ulong), "unsignedLong", true));
83                         nameCache.Add (typeof (float), new TypeData (typeof (float), "float", true));
84                         nameCache.Add (typeof (double), new TypeData (typeof (double), "double", true));
85                         nameCache.Add (typeof (DateTime), new TypeData (typeof (DateTime), "dateTime", true));  // TODO: timeInstant, Xml date, xml time
86                         nameCache.Add (typeof (decimal), new TypeData (typeof (decimal), "decimal", true));
87                         nameCache.Add (typeof (XmlQualifiedName), new TypeData (typeof (XmlQualifiedName), "QName", true));
88                         nameCache.Add (typeof (string), new TypeData (typeof (string), "string", true));
89                         XmlSchemaPatternFacet guidFacet = new XmlSchemaPatternFacet();
90                         guidFacet.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
91                         nameCache.Add (typeof (Guid), new TypeData (typeof (Guid), "guid", true, (TypeData)nameCache[typeof (string)], guidFacet));
92                         nameCache.Add (typeof (byte), new TypeData (typeof (byte), "unsignedByte", true));
93                         nameCache.Add (typeof (sbyte), new TypeData (typeof (sbyte), "byte", true));
94                         nameCache.Add (typeof (char), new TypeData (typeof (char), "char", true, (TypeData)nameCache[typeof (ushort)], null));
95                         nameCache.Add (typeof (object), new TypeData (typeof (object), "anyType", false));
96                         nameCache.Add (typeof (byte[]), new TypeData (typeof (byte[]), "base64Binary", true));
97                         nameCache.Add (typeof (XmlNode), new TypeData (typeof (XmlNode), "XmlNode", false));
98                         nameCache.Add (typeof (XmlElement), new TypeData (typeof (XmlElement), "XmlElement", false));
99                         nameCache.Add (typeof (TimeSpan), new TypeData (typeof (TimeSpan), "duration", true));
100
101                         primitiveTypes = new Hashtable();
102                         ICollection types = nameCache.Values;
103                         foreach (TypeData td in types)
104                                 primitiveTypes.Add (td.XmlType, td);
105
106                         // Additional XSD types
107
108                         primitiveTypes.Add ("date", new TypeData (typeof (DateTime), "date", true));    // TODO: timeInstant
109                         primitiveTypes.Add ("time", new TypeData (typeof (DateTime), "time", true));
110                         primitiveTypes.Add ("timePeriod", new TypeData (typeof (DateTime), "timePeriod", true));
111                         primitiveTypes.Add ("gDay", new TypeData (typeof (string), "gDay", true));
112                         primitiveTypes.Add ("gMonthDay", new TypeData (typeof (string), "gMonthDay", true));
113                         primitiveTypes.Add ("gYear", new TypeData (typeof (string), "gYear", true));
114                         primitiveTypes.Add ("gYearMonth", new TypeData (typeof (string), "gYearMonth", true));
115                         primitiveTypes.Add ("month", new TypeData (typeof (DateTime), "month", true));
116                         primitiveTypes.Add ("NMTOKEN", new TypeData (typeof (string), "NMTOKEN", true));
117                         primitiveTypes.Add ("NMTOKENS", new TypeData (typeof (string), "NMTOKENS", true));
118                         primitiveTypes.Add ("Name", new TypeData (typeof (string), "Name", true));
119                         primitiveTypes.Add ("NCName", new TypeData (typeof (string), "NCName", true));
120                         primitiveTypes.Add ("language", new TypeData (typeof (string), "language", true));
121                         primitiveTypes.Add ("integer", new TypeData (typeof (string), "integer", true));
122                         primitiveTypes.Add ("positiveInteger", new TypeData (typeof (string), "positiveInteger", true));
123                         primitiveTypes.Add ("nonPositiveInteger", new TypeData (typeof (string), "nonPositiveInteger", true));
124                         primitiveTypes.Add ("negativeInteger", new TypeData (typeof (string), "negativeInteger", true));
125                         primitiveTypes.Add ("nonNegativeInteger", new TypeData (typeof (string), "nonNegativeInteger", true));
126                         primitiveTypes.Add ("ENTITIES", new TypeData (typeof (string), "ENTITIES", true));
127                         primitiveTypes.Add ("ENTITY", new TypeData (typeof (string), "ENTITY", true));
128                         primitiveTypes.Add ("hexBinary", new TypeData (typeof (byte[]), "hexBinary", true));
129                         primitiveTypes.Add ("ID", new TypeData (typeof (string), "ID", true));
130                         primitiveTypes.Add ("IDREF", new TypeData (typeof (string), "IDREF", true));
131                         primitiveTypes.Add ("IDREFS", new TypeData (typeof (string), "IDREFS", true));
132                         primitiveTypes.Add ("NOTATION", new TypeData (typeof (string), "NOTATION", true));
133                         primitiveTypes.Add ("token", new TypeData (typeof (string), "token", true));
134                         primitiveTypes.Add ("normalizedString", new TypeData (typeof (string), "normalizedString", true));
135                         primitiveTypes.Add ("anyURI", new TypeData (typeof (string), "anyURI", true));
136                         primitiveTypes.Add ("base64", new TypeData (typeof (byte[]), "base64", true));
137
138 #if NET_2_0
139                         primitiveNullableTypes = new Hashtable ();
140                         foreach (DictionaryEntry de in primitiveTypes) {
141                                 TypeData td = (TypeData) de.Value;
142                                 TypeData ntd = new TypeData (td.Type, td.XmlType, true);
143                                 td.IsGenericNullable = true;
144                                 primitiveNullableTypes.Add (de.Key, td);
145                         }
146 #endif
147                 }
148
149                 public static TypeData GetTypeData (Type type)
150                 {
151                         return GetTypeData (type, null);
152                 }
153
154                 public static TypeData GetTypeData (Type runtimeType, string xmlDataType)
155                 {
156                         Type type = runtimeType;
157                         bool isNullableRuntimeType = false;
158
159 #if NET_2_0
160                         // Nullable<T> is serialized as T
161                         if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>)) {
162                                 isNullableRuntimeType = true;
163                                 type = type.GetGenericArguments () [0];
164
165                                 TypeData pt = GetTypeData (type); // beware this recursive call btw ...
166                                 if (pt != null) {
167                                         lock (primitiveNullableTypes) {
168                                                 TypeData tt = (TypeData) primitiveNullableTypes [pt.XmlType];
169                                                 if (tt == null) {
170                                                         tt = new TypeData (type, pt.XmlType, true);
171                                                         primitiveNullableTypes [pt.XmlType] = tt;
172                                                 }
173                                                 return tt;
174                                         }
175                                 }
176                         }
177 #endif
178
179                         if ((xmlDataType != null) && (xmlDataType.Length != 0)) {
180                                 // If the type is an array, xmlDataType specifies the type for the array elements,
181                                 // not for the whole array. The exception is base64Binary, since it is a byte[],
182                                 // that's why the following check is needed.
183                                 TypeData at = GetPrimitiveTypeData (xmlDataType);
184                                 if (type.IsArray && type != at.Type) {
185                                         lock (primitiveArrayTypes) {
186                                                 TypeData tt = (TypeData) primitiveArrayTypes [xmlDataType];
187                                                 if (tt != null)
188                                                         return tt;
189                                                 if (at.Type == type.GetElementType ()) {
190                                                         tt = new TypeData (type, GetArrayName (at.XmlType), false);
191                                                         primitiveArrayTypes [xmlDataType] = tt;
192                                                         return tt;
193                                                 }
194                                                 else
195                                                         throw new InvalidOperationException ("Cannot convert values of type '" + type.GetElementType () + "' to '" + xmlDataType + "'");
196                                         }
197                                 }
198                                 return at;
199                         }
200
201                         lock (nameCache) {
202                                 TypeData typeData = nameCache[runtimeType] as TypeData;
203                                 if (typeData != null) return typeData;
204
205 #if TARGET_JVM
206                                 Hashtable dynamicCache = AppDomainCache;
207                                 typeData = dynamicCache[runtimeType] as TypeData;
208                                 if (typeData != null) return typeData;
209 #endif
210                                 
211                                 string name;
212                                 if (type.IsArray) {
213                                         string sufix = GetTypeData (type.GetElementType ()).XmlType;
214                                         name = GetArrayName (sufix);
215                                 }
216                                 else 
217                                         name = XmlConvert.EncodeLocalName (type.Name);
218
219                                 typeData = new TypeData (type, name, false);
220                                 if (isNullableRuntimeType)
221                                         typeData.IsGenericNullable = true;
222 #if TARGET_JVM
223                                 dynamicCache[runtimeType] = typeData;
224 #else
225                                 nameCache[runtimeType] = typeData;
226 #endif
227                                 return typeData;
228                         }
229                 }
230
231                 public static bool IsPrimitive (Type type)
232                 {
233                         return GetTypeData (type).SchemaType == SchemaTypes.Primitive;
234                 }
235
236                 public static TypeData GetPrimitiveTypeData (string typeName)
237                 {
238                         TypeData td = (TypeData) primitiveTypes[typeName];
239                         if (td == null) throw new NotSupportedException ("Data type '" + typeName + "' not supported");
240                         return td;
241                 }
242
243                 public static TypeData FindPrimitiveTypeData (string typeName)
244                 {
245                         return (TypeData) primitiveTypes[typeName];
246                 }
247
248                 public static TypeData GetDefaultPrimitiveTypeData (TypeData primType)
249                 {
250                         // Returns the TypeData that is mapped by default to the clr type
251                         // that primType represents
252                         
253                         if (primType.SchemaType == SchemaTypes.Primitive)
254                         {
255                                 TypeData newPrim = GetTypeData (primType.Type);
256                                 if (newPrim != primType) return newPrim;
257                         }
258                         return primType;
259                 }
260
261                 public static bool IsDefaultPrimitiveTpeData (TypeData primType)
262                 {
263                         return GetDefaultPrimitiveTypeData (primType) == primType;
264                 }
265
266                 public static TypeData CreateCustomType (string typeName, string fullTypeName, string xmlType, SchemaTypes schemaType, TypeData listItemTypeData)
267                 {
268                         TypeData td = new TypeData (typeName, fullTypeName, xmlType, schemaType, listItemTypeData);
269                         return td;
270                 }
271
272                 public static string GetArrayName (string elemName)
273                 {
274                         return "ArrayOf" + Char.ToUpper (elemName [0], CultureInfo.InvariantCulture) + elemName.Substring (1);
275                 }
276                 
277                 public static string GetArrayName (string elemName, int dimensions)
278                 {
279                         string aname = GetArrayName (elemName);
280                         for ( ; dimensions > 1; dimensions--)
281                                 aname = "ArrayOf" + aname;
282                         return aname;
283                 }
284                 
285                 public static void ParseArrayType (string arrayType, out string type, out string ns, out string dimensions)
286                 {
287                         int i = arrayType.LastIndexOf (":");
288                         if (i == -1) ns = "";
289                         else ns = arrayType.Substring (0,i);
290                         
291                         int j = arrayType.IndexOf ("[", i+1);
292                         if (j == -1) throw new InvalidOperationException ("Cannot parse WSDL array type: " + arrayType);
293                         type = arrayType.Substring (i+1, j-i-1);
294                         dimensions = arrayType.Substring (j);
295                 }
296         }
297 }