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