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