2005-11-07 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mcs / class / System.XML / System.Xml.Schema / XmlSchemaValidator.cs
1 //
2 // XmlSchemaValidator.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // (C)2004 Novell Inc,
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 //
32 // LAMESPEC:
33 //      - There is no assurance that xsi:type precedes to any other attributes,
34 //        or xsi:type is not handled.
35 //      - There is no SourceUri provision.
36 //
37
38 #if NET_2_0
39
40 using System;
41 using System.Collections;
42 using System.IO;
43 using System.Text;
44 using System.Xml;
45 using Mono.Xml.Schema;
46
47 using QName = System.Xml.XmlQualifiedName;
48 using Form = System.Xml.Schema.XmlSchemaForm;
49 using Use = System.Xml.Schema.XmlSchemaUse;
50 using ContentType = System.Xml.Schema.XmlSchemaContentType;
51 using Validity = System.Xml.Schema.XmlSchemaValidity;
52 using ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags;
53 using ContentProc = System.Xml.Schema.XmlSchemaContentProcessing;
54 using SOMList = System.Xml.Schema.XmlSchemaObjectCollection;
55 using SOMObject = System.Xml.Schema.XmlSchemaObject;
56 using XsElement = System.Xml.Schema.XmlSchemaElement;
57 using XsAttribute = System.Xml.Schema.XmlSchemaAttribute;
58 using AttrGroup = System.Xml.Schema.XmlSchemaAttributeGroup;
59 using AttrGroupRef = System.Xml.Schema.XmlSchemaAttributeGroupRef;
60 using XsDatatype = System.Xml.Schema.XmlSchemaDatatype;
61 using SimpleType = System.Xml.Schema.XmlSchemaSimpleType;
62 using ComplexType = System.Xml.Schema.XmlSchemaComplexType;
63 using SimpleModel = System.Xml.Schema.XmlSchemaSimpleContent;
64 using SimpleExt = System.Xml.Schema.XmlSchemaSimpleContentExtension;
65 using SimpleRst = System.Xml.Schema.XmlSchemaSimpleContentRestriction;
66 using ComplexModel = System.Xml.Schema.XmlSchemaComplexContent;
67 using ComplexExt = System.Xml.Schema.XmlSchemaComplexContentExtension;
68 using ComplexRst = System.Xml.Schema.XmlSchemaComplexContentRestriction;
69 using SimpleTypeRest = System.Xml.Schema.XmlSchemaSimpleTypeRestriction;
70 using SimpleTypeList = System.Xml.Schema.XmlSchemaSimpleTypeList;
71 using SimpleTypeUnion = System.Xml.Schema.XmlSchemaSimpleTypeUnion;
72 using SchemaFacet = System.Xml.Schema.XmlSchemaFacet;
73 using LengthFacet = System.Xml.Schema.XmlSchemaLengthFacet;
74 using MinLengthFacet = System.Xml.Schema.XmlSchemaMinLengthFacet;
75 using Particle = System.Xml.Schema.XmlSchemaParticle;
76 using Sequence = System.Xml.Schema.XmlSchemaSequence;
77 using Choice = System.Xml.Schema.XmlSchemaChoice;
78 using ValException = System.Xml.Schema.XmlSchemaValidationException;
79
80
81 namespace System.Xml.Schema
82 {
83         public sealed class XmlSchemaValidator
84         {
85                 enum Transition {
86                         None,
87                         Content,
88                         StartTag,
89                         Finished
90                 }
91
92                 static readonly XsAttribute [] emptyAttributeArray =
93                         new XsAttribute [0];
94
95                 public XmlSchemaValidator (
96                         XmlNameTable nameTable,
97                         XmlSchemaSet schemas,
98                         IXmlNamespaceResolver nsResolver,
99                         ValidationFlags options)
100                 {
101                         this.nameTable = nameTable;
102                         this.schemas = schemas;
103                         this.nsResolver = nsResolver;
104                         this.options = options;
105                 }
106
107                 #region Fields
108
109                 // XmlReader/XPathNavigator themselves
110                 object nominalEventSender;
111                 IXmlLineInfo lineInfo;
112                 IXmlNamespaceResolver nsResolver;
113                 Uri sourceUri;
114
115                 // These fields will be from XmlReaderSettings or 
116                 // XPathNavigator.CheckValidity(). BTW, I think we could
117                 // implement XPathNavigator.CheckValidity() with
118                 // XsdValidatingReader.
119                 XmlNameTable nameTable;
120                 XmlSchemaSet schemas;
121                 XmlResolver xmlResolver = new XmlUrlResolver ();
122
123                 // "partialValidationType". but not sure how it will be used.
124                 SOMObject startType;
125
126                 // It is perhaps from XmlReaderSettings, but XPathNavigator
127                 // does not have it.
128                 ValidationFlags options;
129
130                 // Validation state
131                 Transition transition;
132                 XsdParticleStateManager state;
133
134                 ArrayList occuredAtts = new ArrayList ();
135                 XsAttribute [] defaultAttributes = emptyAttributeArray;
136                 ArrayList defaultAttributesCache = new ArrayList ();
137
138 #region ID Constraints
139                 XsdIDManager idManager = new XsdIDManager ();
140 #endregion
141
142 #region Key Constraints
143                 ArrayList keyTables = new ArrayList ();
144                 ArrayList currentKeyFieldConsumers = new ArrayList ();
145                 ArrayList tmpKeyrefPool;
146 #endregion
147                 ArrayList elementQNameStack = new ArrayList ();
148
149                 StringBuilder storedCharacters = new StringBuilder ();
150                 bool shouldValidateCharacters;
151
152                 int depth;
153                 int xsiNilDepth = -1;
154                 int skipValidationDepth = -1;
155
156                 SOMObject currentType;
157
158
159                 #endregion
160
161                 #region Public properties
162
163                 // Settable Properties
164
165                 // IMHO It should just be an event that fires another event.
166                 public event ValidationEventHandler ValidationEventHandler;
167
168                 public object ValidationEventSender {
169                         get { return nominalEventSender; }
170                         set { nominalEventSender = value; }
171                 }
172
173                 // (kinda) Construction Properties
174
175                 public IXmlLineInfo LineInfoProvider {
176                         get { return lineInfo; }
177                         set { lineInfo = value; }
178                 }
179
180                 public XmlResolver XmlResolver {
181                         set { xmlResolver = value; }
182                 }
183
184                 [MonoTODO]
185                 public Uri SourceUri {
186                         get { return sourceUri; }
187                         // FIXME: actually there seems no setter, but then
188                         // it will never make sense.
189                         set { sourceUri = value; }
190                 }
191                 #endregion
192
193                 #region Private properties
194
195                 private string BaseUri {
196                         get { return sourceUri != null ? sourceUri.AbsoluteUri : String.Empty; }
197                 }
198
199                 private XsdValidationContext Context {
200                         get { return state.Context; }
201                 }
202
203                 private bool IgnoreWarnings {
204                         get { return (options & ValidationFlags
205                                 .ProcessValidationWarnings) == 0; }
206                 }
207
208                 private bool IgnoreIdentity {
209                         get { return (options & ValidationFlags
210                                 .ProcessIdentityConstraints) == 0; }
211                 }
212
213                 #endregion
214
215                 #region Public methods
216
217                 // State Monitor
218
219                 public XmlSchemaAttribute [] GetExpectedAttributes ()
220                 {
221                         ComplexType cType = Context.ActualType as ComplexType;
222                         if (cType == null)
223                                 return emptyAttributeArray;
224                         ArrayList al = new ArrayList ();
225                         foreach (DictionaryEntry entry in cType.AttributeUses)
226                                 if (!occuredAtts.Contains ((QName) entry.Key))
227                                         al.Add (entry.Value);
228                         return (XsAttribute [])
229                                 al.ToArray (typeof (XsAttribute));
230                 }
231
232                 private void CollectAtomicParticles (XmlSchemaParticle p,
233                         ArrayList al)
234                 {
235                         if (p is XmlSchemaGroupBase) {
236                                 foreach (XmlSchemaParticle c in 
237                                         ((XmlSchemaGroupBase) p).Items)
238                                         CollectAtomicParticles (c, al);
239                         }
240                         else
241                                 al.Add (p);
242                 }
243
244                 [MonoTODO ("Need some tests.")]
245                 // Its behavior is not obvious. For example, it does not
246                 // contain groups (xs:sequence/xs:choice/xs:all). Since it
247                 // might contain xs:any, it could not be of type element[].
248                 public XmlSchemaParticle [] GetExpectedParticles ()
249                 {
250                         ArrayList al = new ArrayList ();
251                         Context.State.GetExpectedParticles (al);
252                         ArrayList ret = new ArrayList ();
253
254                         foreach (XmlSchemaParticle p in al)
255                                 CollectAtomicParticles (p, ret);
256
257                         return (XmlSchemaParticle []) ret.ToArray (
258                                 typeof (XmlSchemaParticle));
259                 }
260
261                 public void GetUnspecifiedDefaultAttributes (ArrayList list)
262                 {
263                         if (transition != Transition.StartTag)
264                                 throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
265                         foreach (XmlSchemaAttribute attr
266                                 in GetExpectedAttributes ())
267                                 if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
268                                         list.Add (attr);
269
270                         list.AddRange (defaultAttributes);
271                 }
272
273                 // State Controller
274
275                 public void AddSchema (XmlSchema schema)
276                 {
277                         schemas.Add (schema);
278                         schemas.Compile ();
279                 }
280
281                 public void Initialize ()
282                 {
283                         Initialize (null);
284                 }
285
286                 public void Initialize (SOMObject startType)
287                 {
288                         this.startType = startType;
289                         transition = Transition.Content;
290                         state = new XsdParticleStateManager ();
291                         if (!schemas.IsCompiled)
292                                 schemas.Compile ();
293                 }
294
295                 // It must be called at the end of the validation (to check
296                 // identity constraints etc.).
297                 public void EndValidation ()
298                 {
299                         CheckState (Transition.Content);
300                         transition = Transition.Finished;
301
302                         if (schemas.Count == 0)
303                                 return;
304
305                         if (depth > 0)
306                                 throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
307
308                         // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
309                         if (!IgnoreIdentity &&
310                                 idManager.HasMissingIDReferences ())
311                                 HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
312                 }
313
314                 // I guess it is for validation error recovery
315                 [MonoTODO ("Find out how XmlSchemaInfo is used.")]
316                 public void SkipToEndElement (XmlSchemaInfo info)
317                 {
318                         CheckState (Transition.Content);
319                         if (schemas.Count == 0)
320                                 return;
321                         state.PopContext ();
322                 }
323
324                 public object ValidateAttribute (
325                         string localName,
326                         string ns,
327                         string attributeValue,
328                         XmlSchemaInfo info)
329                 {
330                         return ValidateAttribute (localName, ns,
331                                 delegate () { return info.SchemaType.Datatype.ParseValue (attributeValue, nameTable, nsResolver); },
332                                 info);
333                 }
334
335                 // I guess this weird XmlValueGetter is for such case that
336                 // value might not be required (and thus it improves 
337                 // performance in some cases. Doh).
338
339                 // The return value is typed primitive, is possible.
340                 // AttDeriv
341                 public object ValidateAttribute (
342                         string localName,
343                         string ns,
344                         XmlValueGetter attributeValue,
345                         XmlSchemaInfo info)
346                 {
347                         CheckState (Transition.StartTag);
348
349                         QName qname = new QName (localName, ns);
350                         if (occuredAtts.Contains (qname))
351                                 throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
352                         occuredAtts.Add (qname);
353
354                         if (ns == XmlNamespaceManager.XmlnsXmlns)
355                                 return null;
356
357                         if (schemas.Count == 0)
358                                 return null;
359
360                         // 3.3.4 Element Locally Valid (Type) - attribute
361                         if (Context.ActualType is ComplexType)
362                                 return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
363                         else
364                                 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
365                         return null;
366                 }
367
368                 // StartTagOpenDeriv
369                 public void ValidateElement (
370                         string localName,
371                         string ns,
372                         XmlSchemaInfo info)
373                 {
374                         ValidateElement (localName, ns, info, null, null, null, null);
375                 }
376
377                 public void ValidateElement (
378                         string localName,
379                         string ns,
380                         XmlSchemaInfo info,
381                         string xsiType,
382                         string xsiNil,
383                         string schemaLocation,
384                         string noNsSchemaLocation)
385                 {
386                         CheckState (Transition.Content);
387                         transition = Transition.StartTag;
388
389                         if (schemaLocation != null)
390                                 HandleSchemaLocation (schemaLocation);
391                         if (noNsSchemaLocation != null)
392                                 HandleNoNSSchemaLocation (noNsSchemaLocation);
393
394                         elementQNameStack.Add (new XmlQualifiedName (localName, ns));
395
396                         if (schemas.Count == 0)
397                                 return;
398
399 #region ID Constraints
400                         if (!IgnoreIdentity)
401                                 idManager.OnStartElement ();
402 #endregion
403                         defaultAttributes = emptyAttributeArray;
404
405                         // If there is no schema information, then no validation is performed.
406                         if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
407                                 if (shouldValidateCharacters)
408                                         ValidateEndSimpleContent (null);
409
410                                 AssessOpenStartElementSchemaValidity (localName, ns);
411                         }
412
413                         if (xsiNil != null)
414                                 HandleXsiNil (xsiNil, info);
415                         if (xsiType != null)
416                                 HandleXsiType (xsiType);
417
418                         shouldValidateCharacters = true;
419
420                         if (info != null) {
421                                 info.IsNil = xsiNilDepth >= 0;
422                                 info.SchemaElement = Context.Element;
423                                 info.SchemaType = Context.ActualSchemaType;
424                                 info.SchemaAttribute = null;
425                                 info.IsDefault = false;
426                                 info.MemberType = null;
427                                 // FIXME: supply Validity (really useful?)
428                         }
429                 }
430
431                 public object ValidateEndElement (XmlSchemaInfo info)
432                 {
433                         return ValidateEndElement (info, null);
434                 }
435
436                 // The return value is typed primitive, if supplied.
437                 // Parameter 'var' seems to be converted into the type
438                 // represented by current simple content type. (try passing
439                 // some kind of object to this method to check the behavior.)
440                 // EndTagDeriv
441                 [MonoTODO ("Handle 'var' parameter.")]
442                 public object ValidateEndElement (XmlSchemaInfo info,
443                         object var)
444                 {
445                         // If it is going to validate an empty element, then
446                         // first validate end of attributes.
447                         if (transition == Transition.StartTag)
448                                 ValidateEndOfAttributes (info);
449
450                         CheckState (Transition.Content);
451
452                         elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
453
454                         if (schemas.Count == 0)
455                                 return null;
456                         if (depth == 0)
457                                 throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
458
459                         depth--;
460
461                         object ret = null;
462                         if (depth == skipValidationDepth)
463                                 skipValidationDepth = -1;
464                         else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
465                                 ret = AssessEndElementSchemaValidity (info);
466                         return ret;
467                 }
468
469                 // StartTagCloseDeriv
470                 // FIXME: fill validity inside this invocation.
471                 public void ValidateEndOfAttributes (XmlSchemaInfo info)
472                 {
473                         try {
474                                 CheckState (Transition.StartTag);
475                                 transition = Transition.Content;
476                                 if (schemas.Count == 0)
477                                         return;
478
479                                 AssessCloseStartElementSchemaValidity (info);
480                         } finally {
481                                 occuredAtts.Clear ();
482                         }
483                 }
484
485                 // TextDeriv ... without text. Maybe typed check is done by
486                 // ValidateAtomicValue().
487                 public void ValidateText (XmlValueGetter getter)
488                 {
489                         CheckState (Transition.Content);
490                         if (schemas.Count == 0)
491                                 return;
492
493                         ComplexType ct = Context.ActualType as ComplexType;
494                         if (ct != null && storedCharacters.Length > 0) {
495                                 switch (ct.ContentType) {
496                                 case XmlSchemaContentType.ElementOnly:
497                                 case XmlSchemaContentType.Empty:
498                                         HandleError ("Not allowed character content was found.");
499                                         break;
500                                 }
501                         }
502
503                         ValidateCharacters (getter);
504                 }
505
506                 // TextDeriv...?
507                 [MonoTODO]
508                 public void ValidateWhitespace (XmlValueGetter getter)
509                 {
510                         CheckState (Transition.Content);
511                         if (schemas.Count == 0)
512                                 return;
513
514 //                      throw new NotImplementedException ();
515                 }
516
517                 #endregion
518
519                 #region Error handling
520
521                 private void HandleError (string message)
522                 {
523                         HandleError (message, null, false);
524                 }
525
526                 private void HandleError (
527                         string message, Exception innerException)
528                 {
529                         HandleError (message, innerException, false);
530                 }
531
532                 private void HandleError (string message,
533                         Exception innerException, bool isWarning)
534                 {
535                         if (isWarning && IgnoreWarnings)
536                                 return;
537
538                         ValException vex = new ValException (
539                                 message, nominalEventSender, BaseUri,
540                                 null, innerException);
541                         HandleError (vex, isWarning);
542                 }
543
544                 private void HandleError (ValException exception)
545                 {
546                         HandleError (exception, false);
547                 }
548
549                 private void HandleError (ValException exception, bool isWarning)
550                 {
551                         if (isWarning && IgnoreWarnings)
552                                 return;
553
554                         if (ValidationEventHandler == null)
555                                 throw exception;
556
557                         ValidationEventArgs e = new ValidationEventArgs (
558                                 exception,
559                                 exception.Message,
560                                 isWarning ? XmlSeverityType.Warning :
561                                         XmlSeverityType.Error);
562                         ValidationEventHandler (nominalEventSender, e);
563                 }
564
565                 #endregion
566
567                 private void CheckState (Transition expected)
568                 {
569                         if (transition != expected) {
570                                 if (transition == Transition.None)
571                                         throw new InvalidOperationException ("Initialize() must be called before processing validation.");
572                                 else
573                                         throw new InvalidOperationException (
574                                                 String.Format ("Unexpected attempt to validation state transition from {0} to {1} was happened.",
575                                                         transition,
576                                                         expected));
577                         }
578                 }
579
580                 private XsElement FindElement (string name, string ns)
581                 {
582                         return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
583                 }
584
585                 private XmlSchemaType FindType (XmlQualifiedName qname)
586                 {
587                         return (XmlSchemaType) schemas.GlobalTypes [qname];
588                 }
589
590                 #region Type Validation
591
592                 private void ValidateStartElementParticle (
593                         string localName, string ns)
594                 {
595                         if (Context.State == null)
596                                 return;
597                         Context.XsiType = null;
598                         state.CurrentElement = null;
599                         Context.EvaluateStartElement (localName,
600                                 ns);
601                         if (Context.IsInvalid)
602                                 HandleError ("Invalid start element: " + ns + ":" + localName);
603
604                         Context.SetElement (state.CurrentElement);
605                 }
606
607                 private void AssessOpenStartElementSchemaValidity (
608                         string localName, string ns)
609                 {
610                         // If the reader is inside xsi:nil (and failed
611                         // on validation), then simply skip its content.
612                         if (xsiNilDepth >= 0 && xsiNilDepth < depth)
613                                 HandleError ("Element item appeared, while current element context is nil.");
614
615                         ValidateStartElementParticle (localName, ns);
616
617                         // Create Validation Root, if not exist.
618                         // [Schema Validity Assessment (Element) 1.1]
619                         if (Context.Element == null) {
620                                 state.CurrentElement = FindElement (localName, ns);
621                                 Context.SetElement (state.CurrentElement);
622                         }
623
624 #region Key Constraints
625                         if (!IgnoreIdentity)
626                                 ValidateKeySelectors ();
627                                 ValidateKeyFields (false, xsiNilDepth == depth,
628                                         Context.ActualType, null, null, null);
629 #endregion
630                 }
631
632                 private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
633                 {
634                         if (Context.XsiType != null)
635                                 AssessCloseStartElementLocallyValidType (info);
636                         else if (Context.Element != null) {
637                                 // element locally valid is checked only when
638                                 // xsi:type does not exist.
639                                 AssessElementLocallyValidElement ();
640                                 if (Context.Element.ElementType != null)
641                                         AssessCloseStartElementLocallyValidType (info);
642                         }
643
644                         if (Context.Element == null) {
645                                 switch (state.ProcessContents) {
646                                 case ContentProc.Skip:
647                                         break;
648                                 case ContentProc.Lax:
649                                         break;
650                                 default:
651                                         QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
652                                         if (Context.XsiType == null &&
653                                                 (schemas.Contains (current.Namespace) ||
654                                                 !schemas.MissedSubComponents (current.Namespace)))
655                                                 HandleError ("Element declaration for " + current + " is missing.");
656                                         break;
657                                 }
658                         }
659
660                         // Proceed to the next depth.
661
662                         state.PushContext ();
663
664                         XsdValidationState next = null;
665                         if (state.ProcessContents == ContentProc.Skip)
666                                 skipValidationDepth = depth;
667                         else {
668                                 // create child particle state.
669                                 ComplexType xsComplexType = Context.ActualType as ComplexType;
670                                 if (xsComplexType != null)
671                                         next = state.Create (xsComplexType.ValidatableParticle);
672                                 else if (state.ProcessContents == ContentProc.Lax)
673                                         next = state.Create (XmlSchemaAny.AnyTypeContent);
674                                 else
675                                         next = state.Create (XmlSchemaParticle.Empty);
676                         }
677                         Context.State = next;
678
679                         depth++;
680                 }
681
682                 // It must be invoked after xsi:nil turned out not to be in
683                 // this element.
684                 private void AssessElementLocallyValidElement ()
685                 {
686                         XsElement element = Context.Element;
687                         XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
688                         // 1.
689                         if (element == null)
690                                 HandleError ("Element declaration is required for " + qname);
691                         // 2.
692                         if (element.ActualIsAbstract)
693                                 HandleError ("Abstract element declaration was specified for " + qname);
694                         // 3. is checked inside ValidateAttribute().
695                 }
696
697                 // 3.3.4 Element Locally Valid (Type)
698                 private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
699                 {
700                         object schemaType = Context.ActualType;
701                         if (schemaType == null) {       // 1.
702                                 HandleError ("Schema type does not exist.");
703                                 return;
704                         }
705                         ComplexType cType = schemaType as ComplexType;
706                         SimpleType sType = schemaType as SimpleType;
707                         if (sType != null) {
708                                 // 3.1.1.
709                                 // Attributes are checked in ValidateAttribute().
710                         } else if (cType != null) {
711                                 // 3.2. Also, 2. is checked there.
712                                 AssessCloseStartElementLocallyValidComplexType (cType, info);
713                         }
714                 }
715
716                 // 3.4.4 Element Locally Valid (Complex Type)
717                 // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
718                 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
719                 {
720                         // 1.
721                         if (cType.IsAbstract) {
722                                 HandleError ("Target complex type is abstract.");
723                                 return;
724                         }
725
726                         // 2 (xsi:nil and content prohibition)
727                         // See AssessStartElementSchemaValidity() and ValidateCharacters()
728                         // 3. attribute uses and  5. wild IDs are handled at
729                         // ValidateAttribute().
730
731                         // Collect default attributes.
732                         // 4.
733                         foreach (XsAttribute attr in GetExpectedAttributes ()) {
734                                 if (attr.ValidatedUse == XmlSchemaUse.Required && 
735                                         attr.ValidatedFixedValue == null)
736                                         HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
737                                 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
738                                         defaultAttributesCache.Add (attr);
739                         }
740                         if (defaultAttributesCache.Count == 0)
741                                 defaultAttributes = emptyAttributeArray;
742                         else
743                                 defaultAttributes = (XsAttribute []) 
744                                         defaultAttributesCache.ToArray (
745                                                 typeof (XsAttribute));
746                         defaultAttributesCache.Clear ();
747                         // 5. wild IDs was already checked at ValidateAttribute().
748
749                 }
750
751                 private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
752                 {
753                         ComplexType cType = Context.ActualType as ComplexType;
754                         XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
755                         // including 3.10.4 Item Valid (Wildcard)
756                         XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
757                         if (attMatch == null)
758                                 HandleError ("Attribute declaration was not found for " + qname);
759                         XsAttribute attdecl = attMatch as XsAttribute;
760                         if (attdecl != null) {
761                                 AssessAttributeLocallyValidUse (attdecl);
762                                 return AssessAttributeLocallyValid (attdecl, info, getter);
763                         } // otherwise anyAttribute or null.
764                         return null;
765                 }
766
767                 // 3.2.4 Attribute Locally Valid and 3.4.4
768                 private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
769                 {
770                         // 2. - 4.
771                         if (attr.AttributeType == null)
772                                 HandleError ("Attribute type is missing for " + attr.QualifiedName);
773                         XsDatatype dt = attr.AttributeType as XsDatatype;
774                         if (dt == null)
775                                 dt = ((SimpleType) attr.AttributeType).Datatype;
776                         // It is a bit heavy process, so let's omit as long as possible ;-)
777                         if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
778                                 object parsedValue = null;
779                                 try {
780                                         parsedValue = getter ();
781                                 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
782                                         HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
783                                 }
784                                 XmlSchemaType type = info != null ? info.SchemaType : null;
785                                 if (attr.ValidatedFixedValue != null && 
786                                         !XmlSchemaUtil.IsSchemaDatatypeEquals (
787                                         attr.AttributeSchemaType.Datatype as XsdAnySimpleType, attr.ValidatedFixedTypedValue, type != null ? type.Datatype as XsdAnySimpleType : null, parsedValue)) {
788                                         HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
789                                         parsedValue = attr.ValidatedFixedTypedValue;
790                                 }
791 #region ID Constraints
792                                 if (!IgnoreIdentity) {
793                                         string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
794                                         if (error != null)
795                                                 HandleError (error);
796                                 }
797 #endregion
798
799                                 #region Key Constraints
800                                 if (!IgnoreIdentity)
801                                         ValidateKeyFields (
802                                                 true,
803                                                 false,
804                                                 attr.AttributeType,
805                                                 attr.QualifiedName.Name,
806                                                 attr.QualifiedName.Namespace,
807                                                 getter);
808                                 #endregion
809
810                                 return parsedValue;
811                         }
812                         return null;
813                 }
814
815                 private void AssessAttributeLocallyValidUse (XsAttribute attr)
816                 {
817                         // This is extra check than spec 3.5.4
818                         if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
819                                 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
820                 }
821
822                 private object AssessEndElementSchemaValidity (
823                         XmlSchemaInfo info)
824                 {
825                         ValidateEndElementParticle ();  // validate against childrens' state.
826
827                         object ret = ValidateEndSimpleContent (info);
828
829                         // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
830                         // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
831                         // => ValidateEndSimpleContent ().
832
833 #region Key Constraints
834                         if (!IgnoreIdentity)
835                                 ValidateEndElementKeyConstraints ();
836 #endregion
837
838                         // Reset xsi:nil, if required.
839                         if (xsiNilDepth == depth)
840                                 xsiNilDepth = -1;
841                         return ret;
842                 }
843
844                 private void ValidateEndElementParticle ()
845                 {
846                         if (Context.State != null) {
847                                 if (!Context.EvaluateEndElement ()) {
848                                         HandleError ("Invalid end element. There are still required content items.");
849                                 }
850                         }
851                         state.PopContext ();
852                 }
853
854                 // Utility for missing validation completion related to child items.
855                 private void ValidateCharacters (XmlValueGetter getter)
856                 {
857                         if (xsiNilDepth >= 0 && xsiNilDepth < depth)
858                                 HandleError ("Element item appeared, while current element context is nil.");
859
860                         if (shouldValidateCharacters)
861                                 storedCharacters.Append (getter ());
862                 }
863
864
865                 // Utility for missing validation completion related to child items.
866                 private object ValidateEndSimpleContent (XmlSchemaInfo info)
867                 {
868                         object ret = null;
869                         if (shouldValidateCharacters)
870                                 ret = ValidateEndSimpleContentCore (info);
871                         shouldValidateCharacters = false;
872                         storedCharacters.Length = 0;
873                         return ret;
874                 }
875
876                 private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
877                 {
878                         if (Context.ActualType == null)
879                                 return null;
880
881                         string value = storedCharacters.ToString ();
882                         object ret = null;
883
884                         if (value.Length == 0) {
885                                 // 3.3.4 Element Locally Valid (Element) 5.1.2
886                                 if (Context.Element != null) {
887                                         if (Context.Element.ValidatedDefaultValue != null)
888                                                 value = Context.Element.ValidatedDefaultValue;
889                                 }                                       
890                         }
891
892                         XsDatatype dt = Context.ActualType as XsDatatype;
893                         SimpleType st = Context.ActualType as SimpleType;
894                         if (dt == null) {
895                                 if (st != null) {
896                                         dt = st.Datatype;
897                                 } else {
898                                         ComplexType ct = Context.ActualType as ComplexType;
899                                         dt = ct.Datatype;
900                                         switch (ct.ContentType) {
901                                         case XmlSchemaContentType.ElementOnly:
902                                         case XmlSchemaContentType.Empty:
903                                                 if (value.Length > 0)
904                                                         HandleError ("Character content not allowed.");
905                                                 break;
906                                         }
907                                 }
908                         }
909                         if (dt != null) {
910                                 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
911                                 if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
912                                         if (value != Context.Element.ValidatedFixedValue)
913                                                 HandleError ("Fixed value constraint was not satisfied.");
914                                 ret = AssessStringValid (st, dt, value);
915                         }
916
917 #region Key Constraints
918                         if (!IgnoreIdentity)
919                                 ValidateSimpleContentIdentity (dt, value);
920 #endregion
921
922                         shouldValidateCharacters = false;
923
924                         if (info != null) {
925                                 info.IsNil = xsiNilDepth >= 0;
926                                 info.SchemaElement = null;
927                                 info.SchemaType = st;
928                                 if (st == null)
929                                         info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
930                                 info.SchemaAttribute = null;
931                                 info.IsDefault = false; // FIXME: might be true
932                                 info.MemberType = null; // FIXME: check
933                                 // FIXME: supply Validity (really useful?)
934                         }
935
936                         return ret;
937                 }
938
939                 // 3.14.4 String Valid 
940                 private object AssessStringValid (SimpleType st,
941                         XsDatatype dt, string value)
942                 {
943                         XsDatatype validatedDatatype = dt;
944                         object ret = null;
945                         if (st != null) {
946                                 string normalized = validatedDatatype.Normalize (value);
947                                 string [] values;
948                                 XsDatatype itemDatatype;
949                                 SimpleType itemSimpleType;
950                                 switch (st.DerivedBy) {
951                                 case XmlSchemaDerivationMethod.List:
952                                         SimpleTypeList listContent = st.Content as SimpleTypeList;
953                                         values = normalized.Split (XmlChar.WhitespaceChars);
954                                         // LAMESPEC: Types of each element in
955                                         // the returned list might be 
956                                         // inconsistent, so basically returning 
957                                         // value does not make sense without 
958                                         // explicit runtime type information 
959                                         // for base primitive type.
960                                         object [] retValues = new object [values.Length];
961                                         itemDatatype = listContent.ValidatedListItemType as XsDatatype;
962                                         itemSimpleType = listContent.ValidatedListItemType as SimpleType;
963                                         for (int vi = 0; vi < values.Length; vi++) {
964                                                 string each = values [vi];
965                                                 if (each == String.Empty)
966                                                         continue;
967                                                 // validate against ValidatedItemType
968                                                 if (itemDatatype != null) {
969                                                         try {
970                                                                 retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
971                                                         } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
972                                                                 HandleError ("List type value contains one or more invalid values.", ex);
973                                                                 break;
974                                                         }
975                                                 }
976                                                 else
977                                                         AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
978                                         }
979                                         ret = retValues;
980                                         break;
981                                 case XmlSchemaDerivationMethod.Union:
982                                         SimpleTypeUnion union = st.Content as SimpleTypeUnion;
983                                         {
984                                                 string each = normalized;
985                                                 // validate against ValidatedItemType
986                                                 bool passed = false;
987                                                 foreach (object eachType in union.ValidatedTypes) {
988                                                         itemDatatype = eachType as XsDatatype;
989                                                         itemSimpleType = eachType as SimpleType;
990                                                         if (itemDatatype != null) {
991                                                                 try {
992                                                                         ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
993                                                                 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
994                                                                         continue;
995                                                                 }
996                                                         }
997                                                         else {
998                                                                 try {
999                                                                         ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1000                                                                 } catch (ValException) {
1001                                                                         continue;
1002                                                                 }
1003                                                         }
1004                                                         passed = true;
1005                                                         break;
1006                                                 }
1007                                                 if (!passed) {
1008                                                         HandleError ("Union type value contains one or more invalid values.");
1009                                                         break;
1010                                                 }
1011                                         }
1012                                         break;
1013                                 case XmlSchemaDerivationMethod.Restriction:
1014                                         SimpleTypeRest str = st.Content as SimpleTypeRest;
1015                                         // facet validation
1016                                         if (str != null) {
1017                                                 /* Don't forget to validate against inherited type's facets 
1018                                                  * Could we simplify this by assuming that the basetype will also
1019                                                  * be restriction?
1020                                                  * */
1021                                                  // mmm, will check later.
1022                                                 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1023                                                 if (baseType != null) {
1024                                                          ret = AssessStringValid (baseType, dt, normalized);
1025                                                 }
1026                                                 if (!str.ValidateValueWithFacets (normalized, nameTable)) {
1027                                                         HandleError ("Specified value was invalid against the facets.");
1028                                                         break;
1029                                                 }
1030                                         }
1031                                         validatedDatatype = st.Datatype;
1032                                         break;
1033                                 }
1034                         }
1035                         if (validatedDatatype != null) {
1036                                 try {
1037                                         ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
1038                                 } catch (Exception ex) {        // FIXME: (wishlist) It is bad manner ;-(
1039                                         HandleError (String.Format ("Invalidly typed data was specified."), ex);
1040                                 }
1041                         }
1042                         return ret;
1043                 }
1044
1045                 #endregion
1046
1047                 #region Key Constraints Validation
1048                 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1049                 {
1050                         XsdKeyTable seq = new XsdKeyTable (ident);
1051                         seq.StartDepth = depth;
1052                         this.keyTables.Add (seq);
1053                         return seq;
1054                 }
1055
1056                 // 3.11.4 Identity Constraint Satisfied
1057                 private void ValidateKeySelectors ()
1058                 {
1059                         if (tmpKeyrefPool != null)
1060                                 tmpKeyrefPool.Clear ();
1061                         if (Context.Element != null && Context.Element.Constraints.Count > 0) {
1062                                 // (a) Create new key sequences, if required.
1063                                 for (int i = 0; i < Context.Element.Constraints.Count; i++) {
1064                                         XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
1065                                         XsdKeyTable seq = CreateNewKeyTable (ident);
1066                                         if (ident is XmlSchemaKeyref) {
1067                                                 if (tmpKeyrefPool == null)
1068                                                         tmpKeyrefPool = new ArrayList ();
1069                                                 tmpKeyrefPool.Add (seq);
1070                                         }
1071                                 }
1072                         }
1073
1074                         // (b) Evaluate current key sequences.
1075                         for (int i = 0; i < keyTables.Count; i++) {
1076                                 XsdKeyTable seq  = (XsdKeyTable) keyTables [i];
1077                                 if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
1078                                         // creates and registers new entry.
1079                                         XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
1080                                         seq.Entries.Add (entry);
1081                                 }
1082                         }
1083                 }
1084
1085                 private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1086                 {
1087                         // (c) Evaluate field paths.
1088                         for (int i = 0; i < keyTables.Count; i++) {
1089                                 XsdKeyTable seq  = (XsdKeyTable) keyTables [i];
1090                                 // If possible, create new field entry candidates.
1091                                 for (int j = 0; j < seq.Entries.Count; j++) {
1092                                         try {
1093                                                 seq.Entries [j].ProcessMatch (
1094                                                         isAttr,
1095                                                         elementQNameStack,
1096                                                         nominalEventSender,
1097                                                         nameTable,
1098                                                         BaseUri,
1099                                                         schemaType,
1100                                                         nsResolver,
1101                                                         lineInfo,
1102                                                         depth,
1103                                                         attrName,
1104                                                         attrNs,
1105                                                         getter == null ?
1106                                                                 null :
1107                                                                 getter (),
1108                                                         isNil, 
1109                                                         currentKeyFieldConsumers);
1110                                         } catch (ValException ex) {
1111                                                 HandleError (ex);
1112                                         }
1113                                 }
1114                         }
1115                 }
1116
1117                 private void ProcessKeyEntryOne (XsdKeyEntry entry, bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1118                 {
1119                 }
1120
1121                 private void ValidateEndElementKeyConstraints ()
1122                 {
1123                         // Reset Identity constraints.
1124                         for (int i = 0; i < keyTables.Count; i++) {
1125                                 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1126                                 if (seq.StartDepth == depth) {
1127                                         ValidateEndKeyConstraint (seq);
1128                                 } else {
1129                                         for (int k = 0; k < seq.Entries.Count; k++) {
1130                                                 XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
1131                                                 // Remove finished (maybe key not found) entries.
1132                                                 if (entry.StartDepth == depth) {
1133                                                         if (entry.KeyFound)
1134                                                                 seq.FinishedEntries.Add (entry);
1135                                                         else if (seq.SourceSchemaIdentity is XmlSchemaKey)
1136                                                                 HandleError ("Key sequence is missing.");
1137                                                         seq.Entries.RemoveAt (k);
1138                                                         k--;
1139                                                 }
1140                                                 // Pop validated key depth to find two or more fields.
1141                                                 else {
1142                                                         for (int j = 0; j < entry.KeyFields.Count; j++) {
1143                                                                 XsdKeyEntryField kf = entry.KeyFields [j];
1144                                                                 if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
1145                                                                         kf.FieldFoundDepth = 0;
1146                                                                         kf.FieldFoundPath = null;
1147                                                                 }
1148                                                         }
1149                                                 }
1150                                         }
1151                                 }
1152                         }
1153                         for (int i = 0; i < keyTables.Count; i++) {
1154                                 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1155                                 if (seq.StartDepth == depth) {
1156                                         keyTables.RemoveAt (i);
1157                                         i--;
1158                                 }
1159                         }
1160                 }
1161
1162                 private void ValidateEndKeyConstraint (XsdKeyTable seq)
1163                 {
1164                         ArrayList errors = new ArrayList ();
1165                         for (int i = 0; i < seq.Entries.Count; i++) {
1166                                 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1167                                 if (entry.KeyFound)
1168                                         continue;
1169                                 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1170                                         errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1171                         }
1172                         if (errors.Count > 0)
1173                                 HandleError ("Invalid identity constraints were found. Key was not found. "
1174                                         + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1175
1176                         errors.Clear ();
1177                         // Find reference target
1178                         XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1179                         if (xsdKeyref != null) {
1180                                 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1181                                         XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1182                                         if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1183                                                 seq.ReferencedKey = target;
1184                                                 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1185                                                         XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1186                                                         for (int k = 0; k < target.FinishedEntries.Count; k++) {
1187                                                                 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1188                                                                 if (entry.CompareIdentity (targetEntry)) {
1189                                                                         entry.KeyRefFound = true;
1190                                                                         break;
1191                                                                 }
1192                                                         }
1193                                                 }
1194                                         }
1195                                 }
1196                                 if (seq.ReferencedKey == null)
1197                                         HandleError ("Target key was not found.");
1198                                 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1199                                         XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1200                                         if (!entry.KeyRefFound)
1201                                                 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1202                                 }
1203                                 if (errors.Count > 0)
1204                                         HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1205                                                 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1206                         }
1207                 }
1208
1209                 private void ValidateSimpleContentIdentity (
1210                         XmlSchemaDatatype dt, string value)
1211                 {
1212                         // Identity field value
1213                         if (currentKeyFieldConsumers != null) {
1214                                 while (this.currentKeyFieldConsumers.Count > 0) {
1215                                         XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
1216                                         if (field.Identity != null)
1217                                                 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
1218                                         object identity = null; // This means empty value
1219                                         if (dt != null) {
1220                                                 try {
1221                                                         identity = dt.ParseValue (value, nameTable, nsResolver);
1222                                                 } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
1223                                                         HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
1224                                                 }
1225                                         }
1226                                         if (identity == null)
1227                                                 identity = value;
1228
1229                                         if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
1230                                                 HandleError ("Two or more identical key value was found: '" + value + "' .");
1231                                         this.currentKeyFieldConsumers.RemoveAt (0);
1232                                 }
1233                         }
1234                 }
1235                 #endregion
1236
1237                 #region xsi:type
1238                 private object GetXsiType (string name)
1239                 {
1240                         object xsiType = null;
1241                         XmlQualifiedName typeQName =
1242                                 XmlQualifiedName.Parse (name, nsResolver);
1243                         if (typeQName == ComplexType.AnyTypeName)
1244                                 xsiType = ComplexType.AnyType;
1245                         else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
1246                                 xsiType = XsDatatype.FromName (typeQName);
1247                         else
1248                                 xsiType = FindType (typeQName);
1249                         return xsiType;
1250                 }
1251
1252                 private void HandleXsiType (string typename)
1253                 {
1254                         XsElement element = Context.Element;
1255                         object xsiType = GetXsiType (typename);
1256                         if (xsiType == null) {
1257                                 HandleError ("The instance type was not found: " + typename);
1258                                 return;
1259                         }
1260                         XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1261                         if (xsiSchemaType != null && Context.Element != null) {
1262                                 XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
1263                                 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
1264                                         HandleError ("The instance type is prohibited by the type of the context element.");
1265                                 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
1266                                         HandleError ("The instance type is prohibited by the context element.");
1267                         }
1268                         ComplexType xsiComplexType = xsiType as ComplexType;
1269                         if (xsiComplexType != null && xsiComplexType.IsAbstract)
1270                                 HandleError ("The instance type is abstract: " + typename);
1271                         else {
1272                                 // If current schema type exists, then this xsi:type must be
1273                                 // valid extension of that type. See 1.2.1.2.4.
1274                                 if (element != null) {
1275                                         AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
1276                                 }
1277                                 // See also ValidateEndOfAttributes().
1278                                 Context.XsiType = xsiType;
1279                         }
1280                 }
1281
1282                 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1283                 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
1284                 {
1285                         XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1286                         ComplexType baseComplexType = baseType as ComplexType;
1287                         ComplexType xsiComplexType = xsiSchemaType as ComplexType;
1288                         if (xsiType != baseType) {
1289                                 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1290                                 if (baseComplexType != null)
1291                                         flag |= baseComplexType.BlockResolved;
1292                                 if (flag == XmlSchemaDerivationMethod.All) {
1293                                         HandleError ("Prohibited element type substitution.");
1294                                         return;
1295                                 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
1296                                         HandleError ("Prohibited element type substitution.");
1297                                         return;
1298                                 }
1299                         }
1300
1301                         if (xsiComplexType != null)
1302                                 try {
1303                                         xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
1304                                 } catch (ValException ex) {
1305                                         HandleError (ex);
1306                                 }
1307                         else {
1308                                 SimpleType xsiSimpleType = xsiType as SimpleType;
1309                                 if (xsiSimpleType != null) {
1310                                         try {
1311                                                 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
1312                                         } catch (ValException ex) {
1313                                                 HandleError (ex);
1314                                         }
1315                                 }
1316                                 else if (xsiType is XsDatatype) {
1317                                         // do nothing
1318                                 }
1319                                 else
1320                                         HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1321                         }
1322                 }
1323                 #endregion
1324
1325                 private void HandleXsiNil (string value, XmlSchemaInfo info)
1326                 {
1327                         XsElement element = Context.Element;
1328                         if (!element.ActualIsNillable) {
1329                                 HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
1330                                 return;
1331                         }
1332                         value = value.Trim (XmlChar.WhitespaceChars);
1333                         // 3.2.
1334                         // Note that 3.2.1 xsi:nil constraints are to be 
1335                         // validated in AssessElementSchemaValidity() and 
1336                         // ValidateCharacters().
1337                         if (value == "true") {
1338                                 if (element.ValidatedFixedValue != null)
1339                                         HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
1340                                 xsiNilDepth = depth;
1341                                 if (info != null)
1342                                         info.IsNil = true;
1343                         }
1344                 }
1345
1346                 #region External schema resolution
1347
1348                 private XmlSchema ReadExternalSchema (string uri)
1349                 {
1350                         Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
1351                         XmlTextReader xtr = null;
1352                         try {
1353                                 xtr = new XmlTextReader (absUri.ToString (),
1354                                         (Stream) xmlResolver.GetEntity (
1355                                                 absUri, null, typeof (Stream)),
1356                                         nameTable);
1357                                 return XmlSchema.Read (
1358                                         xtr, ValidationEventHandler);
1359                         } finally {
1360                                 if (xtr != null)
1361                                         xtr.Close ();
1362                         }
1363                 }
1364
1365                 private void HandleSchemaLocation (string schemaLocation)
1366                 {
1367                         if (xmlResolver == null)
1368                                 return;
1369                         XmlSchema schema = null;
1370                         bool schemaAdded = false;
1371                         string [] tmp = null;
1372                         try {
1373                                 schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
1374                                 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1375                         } catch (Exception ex) {
1376                                 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1377                                 tmp = new string [0];
1378                         }
1379                         if (tmp.Length % 2 != 0)
1380                                 HandleError ("Invalid schemaLocation attribute format.");
1381                         for (int i = 0; i < tmp.Length; i += 2) {
1382                                 try {
1383                                         schema = ReadExternalSchema (tmp [i + 1]);
1384                                 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1385                                         HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
1386                                         continue;
1387                                 }
1388                                 if (schema.TargetNamespace == null)
1389                                         schema.TargetNamespace = tmp [i];
1390                                 else if (schema.TargetNamespace != tmp [i])
1391                                         HandleError ("Specified schema has different target namespace.");
1392
1393                                 if (schema != null) {
1394                                         if (!schemas.Contains (schema.TargetNamespace)) {
1395                                                 schemaAdded = true;
1396                                                 schemas.Add (schema);
1397                                         }
1398                                 }
1399                         }
1400                         if (schemaAdded)
1401                                 schemas.Compile ();
1402                 }
1403
1404                 private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
1405                 {
1406                         if (xmlResolver == null)
1407                                 return;
1408                         XmlSchema schema = null;
1409                         bool schemaAdded = false;
1410
1411                         try {
1412                                 schema = ReadExternalSchema (noNsSchemaLocation);
1413                         } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1414                                 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
1415                         }
1416                         if (schema != null && schema.TargetNamespace != null)
1417                                 HandleError ("Specified schema has different target namespace.");
1418
1419                         if (schema != null) {
1420                                 if (!schemas.Contains (schema.TargetNamespace)) {
1421                                         schemaAdded = true;
1422                                         schemas.Add (schema);
1423                                 }
1424                         }
1425                         if (schemaAdded)
1426                                 schemas.Compile ();
1427                 }
1428
1429                 #endregion
1430         }
1431 }
1432
1433 #endif