2009-03-16 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                 // LAMESPEC: XmlValueGetter is bogus by design because there
157                 // is no way to get associated schema type for current value.
158                 // Here XmlSchemaValidatingReader needs "current type"
159                 // information to validate attribute values.
160                 internal XmlSchemaDatatype CurrentAttributeType;
161
162                 #endregion
163
164                 #region Public properties
165
166                 // Settable Properties
167
168                 // IMHO It should just be an event that fires another event.
169                 public event ValidationEventHandler ValidationEventHandler;
170
171                 public object ValidationEventSender {
172                         get { return nominalEventSender; }
173                         set { nominalEventSender = value; }
174                 }
175
176                 // (kinda) Construction Properties
177
178                 public IXmlLineInfo LineInfoProvider {
179                         get { return lineInfo; }
180                         set { lineInfo = value; }
181                 }
182
183                 public XmlResolver XmlResolver {
184                         set { xmlResolver = value; }
185                 }
186
187                 public Uri SourceUri {
188                         get { return sourceUri; }
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                                 .ReportValidationWarnings) == 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 defaultAttributeList)
262                 {
263                         if (defaultAttributeList == null)
264                                 throw new ArgumentNullException ("defaultAttributeList");
265
266                         if (transition != Transition.StartTag)
267                                 throw new InvalidOperationException ("Method 'GetUnsoecifiedDefaultAttributes' works only when the validator state is inside a start tag.");
268                         foreach (XmlSchemaAttribute attr
269                                 in GetExpectedAttributes ())
270                                 if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
271                                         defaultAttributeList.Add (attr);
272
273                         defaultAttributeList.AddRange (defaultAttributes);
274                 }
275
276                 // State Controller
277
278                 public void AddSchema (XmlSchema schema)
279                 {
280                         if (schema == null)
281                                 throw new ArgumentNullException ("schema");
282                         schemas.Add (schema);
283                         schemas.Compile ();
284                 }
285
286                 public void Initialize ()
287                 {
288                         transition = Transition.Content;
289                         state = new XsdParticleStateManager ();
290                         if (!schemas.IsCompiled)
291                                 schemas.Compile ();
292                 }
293
294                 public void Initialize (SOMObject partialValidationType)
295                 {
296                         if (partialValidationType == null)
297                                 throw new ArgumentNullException ("partialValidationType");
298                         this.startType = partialValidationType;
299                         Initialize ();
300                 }
301
302                 // It must be called at the end of the validation (to check
303                 // identity constraints etc.).
304                 public void EndValidation ()
305                 {
306                         CheckState (Transition.Content);
307                         transition = Transition.Finished;
308
309                         if (schemas.Count == 0)
310                                 return;
311
312                         if (depth > 0)
313                                 throw new InvalidOperationException (String.Format ("There are {0} open element(s). ValidateEndElement() must be called for each open element.", depth));
314
315                         // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
316                         if (!IgnoreIdentity &&
317                                 idManager.HasMissingIDReferences ())
318                                 HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
319                 }
320
321                 // I guess it is for validation error recovery
322                 [MonoTODO] // FIXME: Find out how XmlSchemaInfo is used.
323                 public void SkipToEndElement (XmlSchemaInfo info)
324                 {
325                         CheckState (Transition.Content);
326                         if (schemas.Count == 0)
327                                 return;
328                         state.PopContext ();
329                 }
330
331                 public object ValidateAttribute (
332                         string localName,
333                         string ns,
334                         string attributeValue,
335                         XmlSchemaInfo info)
336                 {
337                         if (attributeValue == null)
338                                 throw new ArgumentNullException ("attributeValue");
339                         return ValidateAttribute (localName, ns, delegate () { return attributeValue; }, info);
340                 }
341
342                 // I guess this weird XmlValueGetter is for such case that
343                 // value might not be required (and thus it improves 
344                 // performance in some cases. Doh).
345
346                 // The return value is typed primitive, if possible.
347                 // AttDeriv
348                 public object ValidateAttribute (
349                         string localName,
350                         string ns,
351                         XmlValueGetter attributeValue,
352                         XmlSchemaInfo info)
353                 {
354                         if (localName == null)
355                                 throw new ArgumentNullException ("localName");
356                         if (ns == null)
357                                 throw new ArgumentNullException ("ns");
358                         if (attributeValue == null)
359                                 throw new ArgumentNullException ("attributeValue");
360
361                         CheckState (Transition.StartTag);
362
363                         QName qname = new QName (localName, ns);
364                         if (occuredAtts.Contains (qname))
365                                 throw new InvalidOperationException (String.Format ("Attribute '{0}' has already been validated in the same element.", qname));
366                         occuredAtts.Add (qname);
367
368                         if (ns == XmlNamespaceManager.XmlnsXmlns)
369                                 return null;
370
371                         if (schemas.Count == 0)
372                                 return null;
373
374                         if (Context.Element != null && Context.XsiType == null) {
375
376                                 // 3.3.4 Element Locally Valid (Type) - attribute
377                                 if (Context.ActualType is ComplexType)
378                                         return AssessAttributeElementLocallyValidType (localName, ns, attributeValue, info);
379                                 else
380                                         HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
381                         }
382                         return null;
383                 }
384
385                 // StartTagOpenDeriv
386                 public void ValidateElement (
387                         string localName,
388                         string ns,
389                         XmlSchemaInfo info)
390                 {
391                         ValidateElement (localName, ns, info, null, null, null, null);
392                 }
393
394                 public void ValidateElement (
395                         string localName,
396                         string ns,
397                         XmlSchemaInfo info,
398                         string xsiType,
399                         string xsiNil,
400                         string schemaLocation,
401                         string noNsSchemaLocation)
402                 {
403                         if (localName == null)
404                                 throw new ArgumentNullException ("localName");
405                         if (ns == null)
406                                 throw new ArgumentNullException ("ns");
407
408                         CheckState (Transition.Content);
409                         transition = Transition.StartTag;
410
411                         if (schemaLocation != null)
412                                 HandleSchemaLocation (schemaLocation);
413                         if (noNsSchemaLocation != null)
414                                 HandleNoNSSchemaLocation (noNsSchemaLocation);
415
416                         elementQNameStack.Add (new XmlQualifiedName (localName, ns));
417
418                         if (schemas.Count == 0)
419                                 return;
420
421 #region ID Constraints
422                         if (!IgnoreIdentity)
423                                 idManager.OnStartElement ();
424 #endregion
425                         defaultAttributes = emptyAttributeArray;
426
427                         // If there is no schema information, then no validation is performed.
428                         if (skipValidationDepth < 0 || depth <= skipValidationDepth) {
429                                 if (shouldValidateCharacters)
430                                         ValidateEndSimpleContent (null);
431
432                                 AssessOpenStartElementSchemaValidity (localName, ns);
433                         }
434
435                         if (xsiNil != null)
436                                 HandleXsiNil (xsiNil, info);
437                         if (xsiType != null)
438                                 HandleXsiType (xsiType);
439
440                         if (xsiNilDepth < depth)
441                                 shouldValidateCharacters = true;
442
443                         if (info != null) {
444                                 info.IsNil = xsiNilDepth >= 0;
445                                 info.SchemaElement = Context.Element;
446                                 info.SchemaType = Context.ActualSchemaType;
447                                 info.SchemaAttribute = null;
448                                 info.IsDefault = false;
449                                 info.MemberType = null;
450                                 // FIXME: supply Validity (really useful?)
451                         }
452                 }
453
454                 public object ValidateEndElement (XmlSchemaInfo info)
455                 {
456                         return ValidateEndElement (info, null);
457                 }
458
459                 // The return value is typed primitive, if supplied.
460                 // Parameter 'var' seems to be converted into the type
461                 // represented by current simple content type. (try passing
462                 // some kind of object to this method to check the behavior.)
463                 // EndTagDeriv
464                 [MonoTODO] // FIXME: Handle 'var' parameter.
465                 public object ValidateEndElement (XmlSchemaInfo info,
466                         object var)
467                 {
468                         // If it is going to validate an empty element, then
469                         // first validate end of attributes.
470                         if (transition == Transition.StartTag)
471                                 ValidateEndOfAttributes (info);
472
473                         CheckState (Transition.Content);
474
475                         elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
476
477                         if (schemas.Count == 0)
478                                 return null;
479                         if (depth == 0)
480                                 throw new InvalidOperationException ("There was no corresponding call to 'ValidateElement' method.");
481
482                         depth--;
483
484                         object ret = null;
485                         if (depth == skipValidationDepth)
486                                 skipValidationDepth = -1;
487                         else if (skipValidationDepth < 0 || depth <= skipValidationDepth)
488                                 ret = AssessEndElementSchemaValidity (info);
489                         return ret;
490                 }
491
492                 // StartTagCloseDeriv
493                 // FIXME: fill validity inside this invocation.
494                 public void ValidateEndOfAttributes (XmlSchemaInfo info)
495                 {
496                         try {
497                                 CheckState (Transition.StartTag);
498                                 transition = Transition.Content;
499                                 if (schemas.Count == 0)
500                                         return;
501
502                                 if (skipValidationDepth < 0 || depth <= skipValidationDepth)
503                                         AssessCloseStartElementSchemaValidity (info);
504                                 depth++;
505                         } finally {
506                                 occuredAtts.Clear ();
507                         }
508                 }
509
510                 // LAMESPEC: It should also receive XmlSchemaInfo so that
511                 // a validator application can receive simple type or
512                 // or content type validation errors.
513                 public void ValidateText (string value)
514                 {
515                         if (value == null)
516                                 throw new ArgumentNullException ("value");
517                         ValidateText (delegate () { return value; });
518                 }
519
520                 // TextDeriv ... without text. Maybe typed check is done by
521                 // ValidateAtomicValue().
522                 public void ValidateText (XmlValueGetter getter)
523                 {
524                         if (getter == null)
525                                 throw new ArgumentNullException ("getter");
526
527                         CheckState (Transition.Content);
528                         if (schemas.Count == 0)
529                                 return;
530
531                         if (skipValidationDepth >= 0 && depth > skipValidationDepth)
532                                 return;
533
534                         ComplexType ct = Context.ActualType as ComplexType;
535                         if (ct != null) {
536                                 switch (ct.ContentType) {
537                                 case XmlSchemaContentType.Empty:
538                                         HandleError ("Not allowed character content was found.");
539                                         break;
540                                 case XmlSchemaContentType.ElementOnly:
541                                         string s = storedCharacters.ToString ();
542                                         if (s.Length > 0 && !XmlChar.IsWhitespace (s))
543                                                 HandleError ("Not allowed character content was found.");
544                                         break;
545                                 }
546                         }
547
548                         ValidateCharacters (getter);
549                 }
550
551                 public void ValidateWhitespace (string value)
552                 {
553                         if (value == null)
554                                 throw new ArgumentNullException ("value");
555                         ValidateWhitespace (delegate () { return value; });
556                 }
557
558                 // TextDeriv. It should do the same as ValidateText() in our actual implementation (whitespaces are conditioned).
559                 public void ValidateWhitespace (XmlValueGetter getter)
560                 {
561                         ValidateText (getter);
562                 }
563
564                 #endregion
565
566                 #region Error handling
567
568                 private void HandleError (string message)
569                 {
570                         HandleError (message, null, false);
571                 }
572
573                 private void HandleError (
574                         string message, Exception innerException)
575                 {
576                         HandleError (message, innerException, false);
577                 }
578
579                 private void HandleError (string message,
580                         Exception innerException, bool isWarning)
581                 {
582                         if (isWarning && IgnoreWarnings)
583                                 return;
584
585                         ValException vex = new ValException (
586                                 message, nominalEventSender, BaseUri,
587                                 null, innerException);
588                         HandleError (vex, isWarning);
589                 }
590
591                 private void HandleError (ValException exception)
592                 {
593                         HandleError (exception, false);
594                 }
595
596                 private void HandleError (ValException exception, bool isWarning)
597                 {
598                         if (isWarning && IgnoreWarnings)
599                                 return;
600
601                         if (ValidationEventHandler == null)
602                                 throw exception;
603
604                         ValidationEventArgs e = new ValidationEventArgs (
605                                 exception,
606                                 exception.Message,
607                                 isWarning ? XmlSeverityType.Warning :
608                                         XmlSeverityType.Error);
609                         ValidationEventHandler (nominalEventSender, e);
610                 }
611
612                 #endregion
613
614                 private void CheckState (Transition expected)
615                 {
616                         if (transition != expected) {
617                                 if (transition == Transition.None)
618                                         throw new InvalidOperationException ("Initialize() must be called before processing validation.");
619                                 else
620                                         throw new InvalidOperationException (
621                                                 String.Format ("Unexpected attempt to validate state transition from {0} to {1}.",
622                                                         transition,
623                                                         expected));
624                         }
625                 }
626
627                 private XsElement FindElement (string name, string ns)
628                 {
629                         return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
630                 }
631
632                 private XmlSchemaType FindType (XmlQualifiedName qname)
633                 {
634                         return (XmlSchemaType) schemas.GlobalTypes [qname];
635                 }
636
637                 #region Type Validation
638
639                 private void ValidateStartElementParticle (
640                         string localName, string ns)
641                 {
642                         if (Context.State == null)
643                                 return;
644                         Context.XsiType = null;
645                         state.CurrentElement = null;
646                         Context.EvaluateStartElement (localName,
647                                 ns);
648                         if (Context.IsInvalid)
649                                 HandleError ("Invalid start element: " + ns + ":" + localName);
650
651                         Context.PushCurrentElement (state.CurrentElement);
652                 }
653
654                 private void AssessOpenStartElementSchemaValidity (
655                         string localName, string ns)
656                 {
657                         // If the reader is inside xsi:nil (and failed
658                         // on validation), then simply skip its content.
659                         if (xsiNilDepth >= 0 && xsiNilDepth < depth)
660                                 HandleError ("Element item appeared, while current element context is nil.");
661
662                         ValidateStartElementParticle (localName, ns);
663
664                         // Create Validation Root, if not exist.
665                         // [Schema Validity Assessment (Element) 1.1]
666                         if (Context.Element == null) {
667                                 state.CurrentElement = FindElement (localName, ns);
668                                 Context.PushCurrentElement (state.CurrentElement);
669                         }
670
671 #region Key Constraints
672                         if (!IgnoreIdentity) {
673                                 ValidateKeySelectors ();
674                                 ValidateKeyFields (false, xsiNilDepth == depth,
675                                         Context.ActualType, null, null, null);
676                         }
677 #endregion
678                 }
679
680                 private void AssessCloseStartElementSchemaValidity (XmlSchemaInfo info)
681                 {
682                         if (Context.XsiType != null)
683                                 AssessCloseStartElementLocallyValidType (info);
684                         else if (Context.Element != null) {
685                                 // element locally valid is checked only when
686                                 // xsi:type does not exist.
687                                 AssessElementLocallyValidElement ();
688                                 if (Context.Element.ElementType != null)
689                                         AssessCloseStartElementLocallyValidType (info);
690                         }
691
692                         if (Context.Element == null) {
693                                 switch (state.ProcessContents) {
694                                 case ContentProc.Skip:
695                                         break;
696                                 case ContentProc.Lax:
697                                         break;
698                                 default:
699                                         QName current = (QName) elementQNameStack [elementQNameStack.Count - 1];
700                                         if (Context.XsiType == null &&
701                                                 (schemas.Contains (current.Namespace) ||
702                                                 !schemas.MissedSubComponents (current.Namespace)))
703                                                 HandleError ("Element declaration for " + current + " is missing.");
704                                         break;
705                                 }
706                         }
707
708                         // Proceed to the next depth.
709
710                         state.PushContext ();
711
712                         XsdValidationState next = null;
713                         if (state.ProcessContents == ContentProc.Skip)
714                                 skipValidationDepth = depth;
715                         else {
716                                 // create child particle state.
717                                 ComplexType xsComplexType = Context.ActualType as ComplexType;
718                                 if (xsComplexType != null)
719                                         next = state.Create (xsComplexType.ValidatableParticle);
720                                 else if (state.ProcessContents == ContentProc.Lax)
721                                         next = state.Create (XmlSchemaAny.AnyTypeContent);
722                                 else
723                                         next = state.Create (XmlSchemaParticle.Empty);
724                         }
725                         Context.State = next;
726                 }
727
728                 // It must be invoked after xsi:nil turned out not to be in
729                 // this element.
730                 private void AssessElementLocallyValidElement ()
731                 {
732                         XsElement element = Context.Element;
733                         XmlQualifiedName qname = (XmlQualifiedName) elementQNameStack [elementQNameStack.Count - 1];
734                         // 1.
735                         if (element == null)
736                                 HandleError ("Element declaration is required for " + qname);
737                         // 2.
738                         if (element.ActualIsAbstract)
739                                 HandleError ("Abstract element declaration was specified for " + qname);
740                         // 3. is checked inside ValidateAttribute().
741                 }
742
743                 // 3.3.4 Element Locally Valid (Type)
744                 private void AssessCloseStartElementLocallyValidType (XmlSchemaInfo info)
745                 {
746                         object schemaType = Context.ActualType;
747                         if (schemaType == null) {       // 1.
748                                 HandleError ("Schema type does not exist.");
749                                 return;
750                         }
751                         ComplexType cType = schemaType as ComplexType;
752                         SimpleType sType = schemaType as SimpleType;
753                         if (sType != null) {
754                                 // 3.1.1.
755                                 // Attributes are checked in ValidateAttribute().
756                         } else if (cType != null) {
757                                 // 3.2. Also, 2. is checked there.
758                                 AssessCloseStartElementLocallyValidComplexType (cType, info);
759                         }
760                 }
761
762                 // 3.4.4 Element Locally Valid (Complex Type)
763                 // FIXME: use SchemaInfo for somewhere (? it is passed to ValidateEndOfAttributes() for some reason)
764                 private void AssessCloseStartElementLocallyValidComplexType (ComplexType cType, XmlSchemaInfo info)
765                 {
766                         // 1.
767                         if (cType.IsAbstract) {
768                                 HandleError ("Target complex type is abstract.");
769                                 return;
770                         }
771
772                         // 2 (xsi:nil and content prohibition)
773                         // See AssessStartElementSchemaValidity() and ValidateCharacters()
774                         // 3. attribute uses and  5. wild IDs are handled at
775                         // ValidateAttribute().
776
777                         // Collect default attributes.
778                         // 4.
779                         foreach (XsAttribute attr in GetExpectedAttributes ()) {
780                                 if (attr.ValidatedUse == XmlSchemaUse.Required && 
781                                         attr.ValidatedFixedValue == null)
782                                         HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
783                                 else if (attr.ValidatedDefaultValue != null || attr.ValidatedFixedValue != null)
784                                         defaultAttributesCache.Add (attr);
785                         }
786                         if (defaultAttributesCache.Count == 0)
787                                 defaultAttributes = emptyAttributeArray;
788                         else
789                                 defaultAttributes = (XsAttribute []) 
790                                         defaultAttributesCache.ToArray (
791                                                 typeof (XsAttribute));
792                         defaultAttributesCache.Clear ();
793                         // 5. wild IDs was already checked at ValidateAttribute().
794
795                 }
796
797                 private object AssessAttributeElementLocallyValidType (string localName, string ns, XmlValueGetter getter, XmlSchemaInfo info)
798                 {
799                         ComplexType cType = Context.ActualType as ComplexType;
800                         XmlQualifiedName qname = new XmlQualifiedName (localName, ns);
801                         // including 3.10.4 Item Valid (Wildcard)
802                         XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (ns, schemas, cType, qname);
803                         if (attMatch == null)
804                                 HandleError ("Attribute declaration was not found for " + qname);
805                         XsAttribute attdecl = attMatch as XsAttribute;
806                         if (attdecl != null) {
807                                 AssessAttributeLocallyValidUse (attdecl);
808                                 return AssessAttributeLocallyValid (attdecl, info, getter);
809                         } // otherwise anyAttribute or null.
810                         return null;
811                 }
812
813                 // 3.2.4 Attribute Locally Valid and 3.4.4
814                 private object AssessAttributeLocallyValid (XsAttribute attr, XmlSchemaInfo info, XmlValueGetter getter)
815                 {
816                         // 2. - 4.
817                         if (attr.AttributeType == null)
818                                 HandleError ("Attribute type is missing for " + attr.QualifiedName);
819                         XsDatatype dt = attr.AttributeType as XsDatatype;
820                         if (dt == null)
821                                 dt = ((SimpleType) attr.AttributeType).Datatype;
822
823                         object parsedValue = null;
824
825                         // It is a bit heavy process, so let's omit as long as possible ;-)
826                         if (dt != SimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
827                                 try {
828                                         CurrentAttributeType = dt;
829                                         parsedValue = getter ();
830                                 } catch (Exception ex) { // It is inevitable and bad manner.
831                                         HandleError (String.Format ("Attribute value is invalid against its data type {0}", dt != null ? dt.TokenizedType : default (XmlTokenizedType)), ex);
832                                 }
833
834                                 // check part of 3.14.4 StringValid
835                                 SimpleType st = attr.AttributeType as SimpleType;
836                                 if (st != null)
837                                         ValidateRestrictedSimpleTypeValue (st, ref dt, new XmlAtomicValue (parsedValue, attr.AttributeSchemaType).Value);
838
839                                 if (attr.ValidatedFixedValue != null && 
840                                         !XmlSchemaUtil.AreSchemaDatatypeEqual (
841                                         attr.AttributeSchemaType, attr.ValidatedFixedTypedValue, attr.AttributeSchemaType, parsedValue)) {
842                                         HandleError (String.Format ("The value of the attribute {0} does not match with its fixed value '{1}' in the space of type {2}", attr.QualifiedName, attr.ValidatedFixedValue, dt));
843                                         parsedValue = attr.ValidatedFixedTypedValue;
844                                 }
845                         }
846
847 #region ID Constraints
848                         if (!IgnoreIdentity) {
849                                 string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
850                                 if (error != null)
851                                         HandleError (error);
852                         }
853 #endregion
854
855 #region Key Constraints
856                         if (!IgnoreIdentity)
857                                 ValidateKeyFields (
858                                         true,
859                                         false,
860                                         attr.AttributeType,
861                                         attr.QualifiedName.Name,
862                                         attr.QualifiedName.Namespace,
863                                         getter);
864 #endregion
865
866                         return parsedValue;
867                 }
868
869                 private void AssessAttributeLocallyValidUse (XsAttribute attr)
870                 {
871                         // This is extra check than spec 3.5.4
872                         if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
873                                 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
874                 }
875
876                 private object AssessEndElementSchemaValidity (
877                         XmlSchemaInfo info)
878                 {
879                         object ret = ValidateEndSimpleContent (info);
880
881                         ValidateEndElementParticle ();  // validate against childrens' state.
882
883                         // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
884                         // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
885                         // => ValidateEndSimpleContent ().
886
887 #region Key Constraints
888                         if (!IgnoreIdentity)
889                                 ValidateEndElementKeyConstraints ();
890 #endregion
891
892                         // Reset xsi:nil, if required.
893                         if (xsiNilDepth == depth)
894                                 xsiNilDepth = -1;
895                         return ret;
896                 }
897
898                 private void ValidateEndElementParticle ()
899                 {
900                         if (Context.State != null) {
901                                 if (!Context.EvaluateEndElement ()) {
902                                         HandleError ("Invalid end element. There are still required content items.");
903                                 }
904                         }
905                         Context.PopCurrentElement ();
906                         state.PopContext ();
907                 }
908
909                 // Utility for missing validation completion related to child items.
910                 private void ValidateCharacters (XmlValueGetter getter)
911                 {
912                         if (xsiNilDepth >= 0 && xsiNilDepth < depth)
913                                 HandleError ("Element item appeared, while current element context is nil.");
914
915                         if (shouldValidateCharacters) {
916                                 CurrentAttributeType = null;
917                                 storedCharacters.Append (getter ());
918                         }
919                 }
920
921
922                 // Utility for missing validation completion related to child items.
923                 private object ValidateEndSimpleContent (XmlSchemaInfo info)
924                 {
925                         object ret = null;
926                         if (shouldValidateCharacters)
927                                 ret = ValidateEndSimpleContentCore (info);
928                         shouldValidateCharacters = false;
929                         storedCharacters.Length = 0;
930                         return ret;
931                 }
932
933                 private object ValidateEndSimpleContentCore (XmlSchemaInfo info)
934                 {
935                         if (Context.ActualType == null)
936                                 return null;
937
938                         string value = storedCharacters.ToString ();
939                         object ret = null;
940
941                         if (value.Length == 0) {
942                                 // 3.3.4 Element Locally Valid (Element) 5.1.2
943                                 if (Context.Element != null) {
944                                         if (Context.Element.ValidatedDefaultValue != null)
945                                                 value = Context.Element.ValidatedDefaultValue;
946                                 }                                       
947                         }
948
949                         XsDatatype dt = Context.ActualType as XsDatatype;
950                         SimpleType st = Context.ActualType as SimpleType;
951                         if (dt == null) {
952                                 if (st != null) {
953                                         dt = st.Datatype;
954                                 } else {
955                                         ComplexType ct = Context.ActualType as ComplexType;
956                                         dt = ct.Datatype;
957                                         switch (ct.ContentType) {
958                                         case XmlSchemaContentType.ElementOnly:
959                                                 if (value.Length > 0 && !XmlChar.IsWhitespace (value))
960                                                         HandleError ("Character content not allowed in an elementOnly model.");
961                                                 break;
962                                         case XmlSchemaContentType.Empty:
963                                                 if (value.Length > 0)
964                                                         HandleError ("Character content not allowed in an empty model.");
965                                                 break;
966                                         }
967                                 }
968                         }
969                         if (dt != null) {
970                                 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
971                                 if (Context.Element != null && Context.Element.ValidatedFixedValue != null)
972                                         if (value != Context.Element.ValidatedFixedValue)
973                                                 HandleError ("Fixed value constraint was not satisfied.");
974                                 ret = AssessStringValid (st, dt, value);
975                         }
976
977 #region Key Constraints
978                         if (!IgnoreIdentity)
979                                 ValidateSimpleContentIdentity (dt, value);
980 #endregion
981
982                         shouldValidateCharacters = false;
983
984                         if (info != null) {
985                                 info.IsNil = xsiNilDepth >= 0;
986                                 info.SchemaElement = null;
987                                 info.SchemaType = Context.ActualType as XmlSchemaType;
988                                 if (info.SchemaType == null)
989                                         info.SchemaType = XmlSchemaType.GetBuiltInSimpleType (dt.TypeCode);
990                                 info.SchemaAttribute = null;
991                                 info.IsDefault = false; // FIXME: might be true
992                                 info.MemberType = null; // FIXME: check
993                                 // FIXME: supply Validity (really useful?)
994                         }
995
996                         return ret;
997                 }
998
999                 // 3.14.4 String Valid 
1000                 private object AssessStringValid (SimpleType st,
1001                         XsDatatype dt, string value)
1002                 {
1003                         XsDatatype validatedDatatype = dt;
1004                         object ret = null;
1005                         if (st != null) {
1006                                 string normalized = validatedDatatype.Normalize (value);
1007                                 string [] values;
1008                                 XsDatatype itemDatatype;
1009                                 SimpleType itemSimpleType;
1010                                 switch (st.DerivedBy) {
1011                                 case XmlSchemaDerivationMethod.List:
1012                                         SimpleTypeList listContent = st.Content as SimpleTypeList;
1013                                         values = normalized.Split (XmlChar.WhitespaceChars);
1014                                         // LAMESPEC: Types of each element in
1015                                         // the returned list might be 
1016                                         // inconsistent, so basically returning 
1017                                         // value does not make sense without 
1018                                         // explicit runtime type information 
1019                                         // for base primitive type.
1020                                         object [] retValues = new object [values.Length];
1021                                         itemDatatype = listContent.ValidatedListItemType as XsDatatype;
1022                                         itemSimpleType = listContent.ValidatedListItemType as SimpleType;
1023                                         for (int vi = 0; vi < values.Length; vi++) {
1024                                                 string each = values [vi];
1025                                                 if (each == String.Empty)
1026                                                         continue;
1027                                                 // validate against ValidatedItemType
1028                                                 if (itemDatatype != null) {
1029                                                         try {
1030                                                                 retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver);
1031                                                         } catch (Exception ex) { // It is inevitable and bad manner.
1032                                                                 HandleError ("List type value contains one or more invalid values.", ex);
1033                                                                 break;
1034                                                         }
1035                                                 }
1036                                                 else
1037                                                         AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1038                                         }
1039                                         ret = retValues;
1040                                         break;
1041                                 case XmlSchemaDerivationMethod.Union:
1042                                         SimpleTypeUnion union = st.Content as SimpleTypeUnion;
1043                                         {
1044                                                 string each = normalized;
1045                                                 // validate against ValidatedItemType
1046                                                 bool passed = false;
1047                                                 foreach (object eachType in union.ValidatedTypes) {
1048                                                         itemDatatype = eachType as XsDatatype;
1049                                                         itemSimpleType = eachType as SimpleType;
1050                                                         if (itemDatatype != null) {
1051                                                                 try {
1052                                                                         ret = itemDatatype.ParseValue (each, nameTable, nsResolver);
1053                                                                 } catch (Exception) { // It is inevitable and bad manner.
1054                                                                         continue;
1055                                                                 }
1056                                                         }
1057                                                         else {
1058                                                                 try {
1059                                                                         ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1060                                                                 } catch (ValException) {
1061                                                                         continue;
1062                                                                 }
1063                                                         }
1064                                                         passed = true;
1065                                                         break;
1066                                                 }
1067                                                 if (!passed) {
1068                                                         HandleError ("Union type value contains one or more invalid values.");
1069                                                         break;
1070                                                 }
1071                                         }
1072                                         break;
1073                                 case XmlSchemaDerivationMethod.Restriction:
1074                                         SimpleTypeRest str = st.Content as SimpleTypeRest;
1075                                         // facet validation
1076                                         if (str != null) {
1077                                                 /* Don't forget to validate against inherited type's facets 
1078                                                  * Could we simplify this by assuming that the basetype will also
1079                                                  * be restriction?
1080                                                  * */
1081                                                  // mmm, will check later.
1082                                                 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1083                                                 if (baseType != null) {
1084                                                          ret = AssessStringValid (baseType, dt, value);
1085                                                 }
1086                                                 if (!str.ValidateValueWithFacets (value, nameTable, nsResolver)) {
1087                                                         HandleError ("Specified value was invalid against the facets.");
1088                                                         break;
1089                                                 }
1090                                         }
1091                                         validatedDatatype = st.Datatype;
1092                                         break;
1093                                 }
1094                         }
1095                         if (validatedDatatype != null) {
1096                                 try {
1097                                         ret = validatedDatatype.ParseValue (value, nameTable, nsResolver);
1098                                 } catch (Exception ex) { // It is inevitable and bad manner.
1099                                         HandleError (String.Format ("Invalidly typed data was specified."), ex);
1100                                 }
1101                         }
1102                         return ret;
1103                 }
1104
1105                 private void ValidateRestrictedSimpleTypeValue (SimpleType st, ref XsDatatype dt, string normalized)
1106                 {
1107                         {
1108                                 string [] values;
1109                                 XsDatatype itemDatatype;
1110                                 SimpleType itemSimpleType;
1111                                 switch (st.DerivedBy) {
1112                                 case XmlSchemaDerivationMethod.List:
1113                                         SimpleTypeList listContent = st.Content as SimpleTypeList;
1114                                         values = normalized.Split (XmlChar.WhitespaceChars);
1115                                         itemDatatype = listContent.ValidatedListItemType as XsDatatype;
1116                                         itemSimpleType = listContent.ValidatedListItemType as SimpleType;
1117                                         for (int vi = 0; vi < values.Length; vi++) {
1118                                                 string each = values [vi];
1119                                                 if (each == String.Empty)
1120                                                         continue;
1121                                                 // validate against ValidatedItemType
1122                                                 if (itemDatatype != null) {
1123                                                         try {
1124                                                                 itemDatatype.ParseValue (each, nameTable, nsResolver);
1125                                                         } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
1126                                                                 HandleError ("List type value contains one or more invalid values.", ex);
1127                                                                 break;
1128                                                         }
1129                                                 }
1130                                                 else
1131                                                         AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1132                                         }
1133                                         break;
1134                                 case XmlSchemaDerivationMethod.Union:
1135                                         SimpleTypeUnion union = st.Content as SimpleTypeUnion;
1136                                         {
1137                                                 string each = normalized;
1138                                                 // validate against ValidatedItemType
1139                                                 bool passed = false;
1140                                                 foreach (object eachType in union.ValidatedTypes) {
1141                                                         itemDatatype = eachType as XsDatatype;
1142                                                         itemSimpleType = eachType as SimpleType;
1143                                                         if (itemDatatype != null) {
1144                                                                 try {
1145                                                                         itemDatatype.ParseValue (each, nameTable, nsResolver);
1146                                                                 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
1147                                                                         continue;
1148                                                                 }
1149                                                         }
1150                                                         else {
1151                                                                 try {
1152                                                                         AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
1153                                                                 } catch (ValException) {
1154                                                                         continue;
1155                                                                 }
1156                                                         }
1157                                                         passed = true;
1158                                                         break;
1159                                                 }
1160                                                 if (!passed) {
1161                                                         HandleError ("Union type value contains one or more invalid values.");
1162                                                         break;
1163                                                 }
1164                                         }
1165                                         break;
1166                                 case XmlSchemaDerivationMethod.Restriction:
1167                                         SimpleTypeRest str = st.Content as SimpleTypeRest;
1168                                         // facet validation
1169                                         if (str != null) {
1170                                                 /* Don't forget to validate against inherited type's facets 
1171                                                  * Could we simplify this by assuming that the basetype will also
1172                                                  * be restriction?
1173                                                  * */
1174                                                  // mmm, will check later.
1175                                                 SimpleType baseType = st.BaseXmlSchemaType as SimpleType;
1176                                                 if (baseType != null) {
1177                                                          AssessStringValid(baseType, dt, normalized);
1178                                                 }
1179                                                 if (!str.ValidateValueWithFacets (normalized, nameTable, nsResolver)) {
1180                                                         HandleError ("Specified value was invalid against the facets.");
1181                                                         break;
1182                                                 }
1183                                         }
1184                                         dt = st.Datatype;
1185                                         break;
1186                                 }
1187                         }
1188                 }
1189
1190                 #endregion
1191
1192                 #region Key Constraints Validation
1193                 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1194                 {
1195                         XsdKeyTable seq = new XsdKeyTable (ident);
1196                         seq.StartDepth = depth;
1197                         this.keyTables.Add (seq);
1198                         return seq;
1199                 }
1200
1201                 // 3.11.4 Identity Constraint Satisfied
1202                 private void ValidateKeySelectors ()
1203                 {
1204                         if (tmpKeyrefPool != null)
1205                                 tmpKeyrefPool.Clear ();
1206                         if (Context.Element != null && Context.Element.Constraints.Count > 0) {
1207                                 // (a) Create new key sequences, if required.
1208                                 for (int i = 0; i < Context.Element.Constraints.Count; i++) {
1209                                         XmlSchemaIdentityConstraint ident = (XmlSchemaIdentityConstraint) Context.Element.Constraints [i];
1210                                         XsdKeyTable seq = CreateNewKeyTable (ident);
1211                                         if (ident is XmlSchemaKeyref) {
1212                                                 if (tmpKeyrefPool == null)
1213                                                         tmpKeyrefPool = new ArrayList ();
1214                                                 tmpKeyrefPool.Add (seq);
1215                                         }
1216                                 }
1217                         }
1218
1219                         // (b) Evaluate current key sequences.
1220                         for (int i = 0; i < keyTables.Count; i++) {
1221                                 XsdKeyTable seq  = (XsdKeyTable) keyTables [i];
1222                                 if (seq.SelectorMatches (this.elementQNameStack, depth) != null) {
1223                                         // creates and registers new entry.
1224                                         XsdKeyEntry entry = new XsdKeyEntry (seq, depth, lineInfo);
1225                                         seq.Entries.Add (entry);
1226                                 }
1227                         }
1228                 }
1229
1230                 private void ValidateKeyFields (bool isAttr, bool isNil, object schemaType, string attrName, string attrNs, XmlValueGetter getter)
1231                 {
1232                         // (c) Evaluate field paths.
1233                         for (int i = 0; i < keyTables.Count; i++) {
1234                                 XsdKeyTable seq  = (XsdKeyTable) keyTables [i];
1235                                 // If possible, create new field entry candidates.
1236                                 for (int j = 0; j < seq.Entries.Count; j++) {
1237                                         CurrentAttributeType = null;
1238                                         try {
1239                                                 seq.Entries [j].ProcessMatch (
1240                                                         isAttr,
1241                                                         elementQNameStack,
1242                                                         nominalEventSender,
1243                                                         nameTable,
1244                                                         BaseUri,
1245                                                         schemaType,
1246                                                         nsResolver,
1247                                                         lineInfo,
1248                                                         isAttr ? depth + 1 : depth,
1249                                                         attrName,
1250                                                         attrNs,
1251                                                         getter == null ?
1252                                                                 null :
1253                                                                 getter (),
1254                                                         isNil, 
1255                                                         currentKeyFieldConsumers);
1256                                         } catch (ValException ex) {
1257                                                 HandleError (ex);
1258                                         }
1259                                 }
1260                         }
1261                 }
1262
1263                 private void ValidateEndElementKeyConstraints ()
1264                 {
1265                         // Reset Identity constraints.
1266                         for (int i = 0; i < keyTables.Count; i++) {
1267                                 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1268                                 if (seq.StartDepth == depth) {
1269                                         ValidateEndKeyConstraint (seq);
1270                                 } else {
1271                                         for (int k = 0; k < seq.Entries.Count; k++) {
1272                                                 XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
1273                                                 // Remove finished (maybe key not found) entries.
1274                                                 if (entry.StartDepth == depth) {
1275                                                         if (entry.KeyFound)
1276                                                                 seq.FinishedEntries.Add (entry);
1277                                                         else if (seq.SourceSchemaIdentity is XmlSchemaKey)
1278                                                                 HandleError ("Key sequence is missing.");
1279                                                         seq.Entries.RemoveAt (k);
1280                                                         k--;
1281                                                 }
1282                                                 // Pop validated key depth to find two or more fields.
1283                                                 else {
1284                                                         for (int j = 0; j < entry.KeyFields.Count; j++) {
1285                                                                 XsdKeyEntryField kf = entry.KeyFields [j];
1286                                                                 if (!kf.FieldFound && kf.FieldFoundDepth == depth) {
1287                                                                         kf.FieldFoundDepth = 0;
1288                                                                         kf.FieldFoundPath = null;
1289                                                                 }
1290                                                         }
1291                                                 }
1292                                         }
1293                                 }
1294                         }
1295                         for (int i = 0; i < keyTables.Count; i++) {
1296                                 XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
1297                                 if (seq.StartDepth == depth) {
1298                                         keyTables.RemoveAt (i);
1299                                         i--;
1300                                 }
1301                         }
1302                 }
1303
1304                 private void ValidateEndKeyConstraint (XsdKeyTable seq)
1305                 {
1306                         ArrayList errors = new ArrayList ();
1307                         for (int i = 0; i < seq.Entries.Count; i++) {
1308                                 XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
1309                                 if (entry.KeyFound)
1310                                         continue;
1311                                 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1312                                         errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1313                         }
1314                         if (errors.Count > 0)
1315                                 HandleError ("Invalid identity constraints were found. Key was not found. "
1316                                         + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1317
1318                         errors.Clear ();
1319                         // Find reference target
1320                         XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1321                         if (xsdKeyref != null) {
1322                                 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1323                                         XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1324                                         if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1325                                                 seq.ReferencedKey = target;
1326                                                 for (int j = 0; j < seq.FinishedEntries.Count; j++) {
1327                                                         XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
1328                                                         for (int k = 0; k < target.FinishedEntries.Count; k++) {
1329                                                                 XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
1330                                                                 if (entry.CompareIdentity (targetEntry)) {
1331                                                                         entry.KeyRefFound = true;
1332                                                                         break;
1333                                                                 }
1334                                                         }
1335                                                 }
1336                                         }
1337                                 }
1338                                 if (seq.ReferencedKey == null)
1339                                         HandleError ("Target key was not found.");
1340                                 for (int i = 0; i < seq.FinishedEntries.Count; i++) {
1341                                         XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
1342                                         if (!entry.KeyRefFound)
1343                                                 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1344                                 }
1345                                 if (errors.Count > 0)
1346                                         HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1347                                                 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1348                         }
1349                 }
1350
1351                 private void ValidateSimpleContentIdentity (
1352                         XmlSchemaDatatype dt, string value)
1353                 {
1354                         // Identity field value
1355                         if (currentKeyFieldConsumers != null) {
1356                                 while (this.currentKeyFieldConsumers.Count > 0) {
1357                                         XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
1358                                         if (field.Identity != null)
1359                                                 HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
1360                                         object identity = null; // This means empty value
1361                                         if (dt != null) {
1362                                                 try {
1363                                                         identity = dt.ParseValue (value, nameTable, nsResolver);
1364                                                 } catch (Exception ex) { // It is inevitable and bad manner.
1365                                                         HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
1366                                                 }
1367                                         }
1368                                         if (identity == null)
1369                                                 identity = value;
1370
1371                                         if (!field.SetIdentityField (identity, depth == xsiNilDepth, dt as XsdAnySimpleType, depth, lineInfo))
1372                                                 HandleError ("Two or more identical key value was found: '" + value + "' .");
1373                                         this.currentKeyFieldConsumers.RemoveAt (0);
1374                                 }
1375                         }
1376                 }
1377                 #endregion
1378
1379                 #region xsi:type
1380                 private object GetXsiType (string name)
1381                 {
1382                         object xsiType = null;
1383                         XmlQualifiedName typeQName =
1384                                 XmlQualifiedName.Parse (name, nsResolver);
1385                         if (typeQName == ComplexType.AnyTypeName)
1386                                 xsiType = ComplexType.AnyType;
1387                         else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
1388                                 xsiType = XsDatatype.FromName (typeQName);
1389                         else
1390                                 xsiType = FindType (typeQName);
1391                         return xsiType;
1392                 }
1393
1394                 private void HandleXsiType (string typename)
1395                 {
1396                         XsElement element = Context.Element;
1397                         object xsiType = GetXsiType (typename);
1398                         if (xsiType == null) {
1399                                 HandleError ("The instance type was not found: " + typename);
1400                                 return;
1401                         }
1402                         XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1403                         if (xsiSchemaType != null && Context.Element != null) {
1404                                 XmlSchemaType elemBaseType = element.ElementType as XmlSchemaType;
1405                                 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
1406                                         HandleError ("The instance type is prohibited by the type of the context element.");
1407                                 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & element.BlockResolved) != 0)
1408                                         HandleError ("The instance type is prohibited by the context element.");
1409                         }
1410                         ComplexType xsiComplexType = xsiType as ComplexType;
1411                         if (xsiComplexType != null && xsiComplexType.IsAbstract)
1412                                 HandleError ("The instance type is abstract: " + typename);
1413                         else {
1414                                 // If current schema type exists, then this xsi:type must be
1415                                 // valid extension of that type. See 1.2.1.2.4.
1416                                 if (element != null) {
1417                                         AssessLocalTypeDerivationOK (xsiType, element.ElementType, element.BlockResolved);
1418                                 }
1419                                 // See also ValidateEndOfAttributes().
1420                                 Context.XsiType = xsiType;
1421                         }
1422                 }
1423
1424                 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
1425                 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
1426                 {
1427                         XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
1428                         ComplexType baseComplexType = baseType as ComplexType;
1429                         ComplexType xsiComplexType = xsiSchemaType as ComplexType;
1430                         if (xsiType != baseType) {
1431                                 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
1432                                 if (baseComplexType != null)
1433                                         flag |= baseComplexType.BlockResolved;
1434                                 if (flag == XmlSchemaDerivationMethod.All) {
1435                                         HandleError ("Prohibited element type substitution.");
1436                                         return;
1437                                 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
1438                                         HandleError ("Prohibited element type substitution.");
1439                                         return;
1440                                 }
1441                         }
1442
1443                         if (xsiComplexType != null)
1444                                 try {
1445                                         xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
1446                                 } catch (ValException ex) {
1447                                         HandleError (ex);
1448                                 }
1449                         else {
1450                                 SimpleType xsiSimpleType = xsiType as SimpleType;
1451                                 if (xsiSimpleType != null) {
1452                                         try {
1453                                                 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
1454                                         } catch (ValException ex) {
1455                                                 HandleError (ex);
1456                                         }
1457                                 }
1458                                 else if (xsiType is XsDatatype) {
1459                                         // do nothing
1460                                 }
1461                                 else
1462                                         HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
1463                         }
1464                 }
1465                 #endregion
1466
1467                 private void HandleXsiNil (string value, XmlSchemaInfo info)
1468                 {
1469                         XsElement element = Context.Element;
1470                         if (!element.ActualIsNillable) {
1471                                 HandleError (String.Format ("Current element '{0}' is not nillable and thus does not allow occurence of 'nil' attribute.", Context.Element.QualifiedName));
1472                                 return;
1473                         }
1474                         value = value.Trim (XmlChar.WhitespaceChars);
1475                         // 3.2.
1476                         // Note that 3.2.1 xsi:nil constraints are to be 
1477                         // validated in AssessElementSchemaValidity() and 
1478                         // ValidateCharacters().
1479                         if (value == "true") {
1480                                 if (element.ValidatedFixedValue != null)
1481                                         HandleError ("Schema instance nil was specified, where the element declaration for " + element.QualifiedName + "has fixed value constraints.");
1482                                 xsiNilDepth = depth;
1483                                 if (info != null)
1484                                         info.IsNil = true;
1485                         }
1486                 }
1487
1488                 #region External schema resolution
1489
1490                 private XmlSchema ReadExternalSchema (string uri)
1491                 {
1492                         Uri absUri = new Uri (SourceUri, uri.Trim (XmlChar.WhitespaceChars));
1493                         XmlTextReader xtr = null;
1494                         try {
1495                                 xtr = new XmlTextReader (absUri.ToString (),
1496                                         (Stream) xmlResolver.GetEntity (
1497                                                 absUri, null, typeof (Stream)),
1498                                         nameTable);
1499                                 return XmlSchema.Read (
1500                                         xtr, ValidationEventHandler);
1501                         } finally {
1502                                 if (xtr != null)
1503                                         xtr.Close ();
1504                         }
1505                 }
1506
1507                 private void HandleSchemaLocation (string schemaLocation)
1508                 {
1509                         if (xmlResolver == null)
1510                                 return;
1511                         XmlSchema schema = null;
1512                         bool schemaAdded = false;
1513                         string [] tmp = null;
1514                         try {
1515                                 schemaLocation = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Token).Datatype.ParseValue (schemaLocation, null, null) as string;
1516                                 tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
1517                         } catch (Exception ex) {
1518                                 HandleError ("Invalid schemaLocation attribute format.", ex, true);
1519                                 tmp = new string [0];
1520                         }
1521                         if (tmp.Length % 2 != 0)
1522                                 HandleError ("Invalid schemaLocation attribute format.");
1523                         for (int i = 0; i < tmp.Length; i += 2) {
1524                                 try {
1525                                         schema = ReadExternalSchema (tmp [i + 1]);
1526                                 } catch (Exception ex) { // It is inevitable and bad manner.
1527                                         HandleError ("Could not resolve schema location URI: " + schemaLocation, ex, true);
1528                                         continue;
1529                                 }
1530                                 if (schema.TargetNamespace == null)
1531                                         schema.TargetNamespace = tmp [i];
1532                                 else if (schema.TargetNamespace != tmp [i])
1533                                         HandleError ("Specified schema has different target namespace.");
1534
1535                                 if (schema != null) {
1536                                         if (!schemas.Contains (schema.TargetNamespace)) {
1537                                                 schemaAdded = true;
1538                                                 schemas.Add (schema);
1539                                         }
1540                                 }
1541                         }
1542                         if (schemaAdded)
1543                                 schemas.Compile ();
1544                 }
1545
1546                 private void HandleNoNSSchemaLocation (string noNsSchemaLocation)
1547                 {
1548                         if (xmlResolver == null)
1549                                 return;
1550                         XmlSchema schema = null;
1551                         bool schemaAdded = false;
1552
1553                         try {
1554                                 schema = ReadExternalSchema (noNsSchemaLocation);
1555                         } catch (Exception ex) { // It is inevitable and bad manner.
1556                                 HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, ex, true);
1557                         }
1558                         if (schema != null && schema.TargetNamespace != null)
1559                                 HandleError ("Specified schema has different target namespace.");
1560
1561                         if (schema != null) {
1562                                 if (!schemas.Contains (schema.TargetNamespace)) {
1563                                         schemaAdded = true;
1564                                         schemas.Add (schema);
1565                                 }
1566                         }
1567                         if (schemaAdded)
1568                                 schemas.Compile ();
1569                 }
1570
1571                 #endregion
1572         }
1573 }
1574
1575 #endif