1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtXmlPatterns module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "qxsdvalidatinginstancereader_p.h"
44 #include "qabstractdatetime_p.h"
45 #include "qacceltreeresourceloader_p.h"
46 #include "qbase64binary_p.h"
47 #include "qboolean_p.h"
48 #include "qcommonnamespaces_p.h"
49 #include "qderivedinteger_p.h"
50 #include "qduration_p.h"
51 #include "qgenericstaticcontext_p.h"
52 #include "qhexbinary_p.h"
53 #include "qnamespaceresolver_p.h"
54 #include "qpatternplatform_p.h"
55 #include "qqnamevalue_p.h"
56 #include "qsourcelocationreflection_p.h"
57 #include "qvaluefactory_p.h"
58 #include "qxmlnamepool.h"
59 #include "qxmlquery_p.h"
60 #include "qxmlschema_p.h"
61 #include "qxsdschemahelper_p.h"
62 #include "qxsdschemamerger_p.h"
63 #include "qxsdstatemachine_p.h"
64 #include "qxsdstatemachinebuilder_p.h"
65 #include "qxsdtypechecker_p.h"
67 #include "qxsdschemadebugger_p.h"
69 #include <QtCore/QFile>
70 #include <QtXmlPatterns/QXmlQuery>
71 #include <QtXmlPatterns/QXmlResultItems>
75 using namespace QPatternist;
81 bool XsdStateMachine<XsdTerm::Ptr>::inputEqualsTransition<QXmlName>(QXmlName name, XsdTerm::Ptr term) const
83 if (term->isElement()) {
84 return (XsdElement::Ptr(term)->name(m_namePool) == name);
85 } else if (term->isWildcard()) {
86 // wildcards using XsdWildcard::absentNamespace, so we have to fix that here
87 if (name.namespaceURI() == StandardNamespaces::empty) {
88 name.setNamespaceURI(m_namePool->allocateNamespace(XsdWildcard::absentNamespace()));
91 return XsdSchemaHelper::wildcardAllowsExpandedName(name, XsdWildcard::Ptr(term), m_namePool);
98 XsdValidatingInstanceReader::XsdValidatingInstanceReader(XsdValidatedXmlNodeModel *model, const QUrl &documentUri, const XsdSchemaContext::Ptr &context)
99 : XsdInstanceReader(model, context)
101 , m_namePool(m_context->namePool())
102 , m_xsiNilName(m_namePool->allocateQName(CommonNamespaces::XSI, QLatin1String("nil")))
103 , m_xsiTypeName(m_namePool->allocateQName(CommonNamespaces::XSI, QLatin1String("type")))
104 , m_xsiSchemaLocationName(m_namePool->allocateQName(CommonNamespaces::XSI, QLatin1String("schemaLocation")))
105 , m_xsiNoNamespaceSchemaLocationName(m_namePool->allocateQName(CommonNamespaces::XSI, QLatin1String("noNamespaceSchemaLocation")))
106 , m_documentUri(documentUri)
108 m_idRefsType = m_context->schemaTypeFactory()->createSchemaType(m_namePool->allocateQName(CommonNamespaces::WXS, QLatin1String("IDREFS")));
111 void XsdValidatingInstanceReader::addSchema(const XsdSchema::Ptr &schema, const QUrl &locationUrl)
113 if (!m_mergedSchemas.contains(locationUrl)) {
114 m_mergedSchemas.insert(locationUrl, QStringList() << schema->targetNamespace());
116 QStringList &targetNamespaces = m_mergedSchemas[locationUrl];
117 if (targetNamespaces.contains(schema->targetNamespace()))
120 targetNamespaces.append(schema->targetNamespace());
123 const XsdSchemaMerger merger(m_schema, schema);
124 m_schema = merger.mergedSchema();
126 XsdSchemaDebugger dbg(m_namePool);
127 dbg.dumpSchema(m_schema);
131 bool XsdValidatingInstanceReader::read()
139 if (isStartElement()) {
140 const QXmlName elementName = name();
141 const QXmlItem currentItem = item();
142 bool hasStateMachine = false;
143 XsdElement::Ptr processedElement;
145 if (!validate(hasStateMachine, processedElement))
150 if (processedElement) { // for wildcard with 'skip' we have no element
151 m_model->setAssignedElement(currentItem.toNodeModelIndex(), processedElement);
153 // check identity constraints after all child nodes have been
154 // validated, so that we know there assigned types
155 validateIdentityConstraint(processedElement, currentItem);
158 if (!m_stateMachines.isEmpty() && hasStateMachine) {
159 if (!m_stateMachines.top().inEndState()) {
160 error(QtXmlPatterns::tr("Element %1 is missing child element.").arg(formatKeyword(m_namePool->displayName(elementName))));
163 m_stateMachines.pop();
170 // check IDREF occurrences
171 const QStringList ids = m_model->idIdRefBindingIds();
172 QSetIterator<QString> it(m_idRefs);
173 while (it.hasNext()) {
174 const QString id = it.next();
175 if (!ids.contains(id)) {
176 error(QtXmlPatterns::tr("There is one IDREF value with no corresponding ID: %1.").arg(formatKeyword(id)));
184 void XsdValidatingInstanceReader::error(const QString &msg) const
186 m_context.data()->error(msg, XsdSchemaContext::XSDError, sourceLocation());
189 bool XsdValidatingInstanceReader::loadSchema(const QString &targetNamespace, const QUrl &location)
191 const AutoPtr<QNetworkReply> reply(AccelTreeResourceLoader::load(location, m_context->networkAccessManager(),
192 m_context, AccelTreeResourceLoader::ContinueOnError));
196 // we have to create a separated schema context here, that however shares the type factory
197 XsdSchemaContext::Ptr context(new XsdSchemaContext(m_namePool));
198 context->m_schemaTypeFactory = m_context->m_schemaTypeFactory;
200 QXmlSchemaPrivate schema(context);
201 schema.load(reply.data(), location, targetNamespace);
202 if (!schema.isValid()) {
203 error(QtXmlPatterns::tr("Loaded schema file is invalid."));
207 addSchema(schema.m_schemaParserContext->schema(), location);
212 bool XsdValidatingInstanceReader::validate(bool &hasStateMachine, XsdElement::Ptr &processedElement)
214 // first check if a custom schema is defined
215 if (hasAttribute(m_xsiSchemaLocationName)) {
216 const QString schemaLocation = attribute(m_xsiSchemaLocationName);
217 const QStringList parts = schemaLocation.split(QLatin1Char(' '), QString::SkipEmptyParts);
218 if ((parts.count()%2) == 1) {
219 error(QtXmlPatterns::tr("%1 contains invalid data.").arg(formatKeyword(m_namePool, m_xsiSchemaLocationName)));
223 for (int i = 0; i < parts.count(); i += 2) {
224 const QString identifier = QString::fromLatin1("%1 %2").arg(parts.at(i)).arg(parts.at(i + 1));
225 if (m_processedSchemaLocations.contains(identifier))
228 m_processedSchemaLocations.insert(identifier);
230 // check constraint 4) from http://www.w3.org/TR/xmlschema-1/#schema-loc (only valid for XML Schema 1.0?)
231 if (m_processedNamespaces.contains(parts.at(i))) {
232 error(QtXmlPatterns::tr("xsi:schemaLocation namespace %1 has already appeared earlier in the instance document.").arg(formatKeyword(parts.at(i))));
236 QUrl url(parts.at(i + 1));
237 if (url.isRelative()) {
238 Q_ASSERT(m_documentUri.isValid());
240 url = m_documentUri.resolved(url);
243 loadSchema(parts.at(i), url);
247 if (hasAttribute(m_xsiNoNamespaceSchemaLocationName)) {
248 const QString schemaLocation = attribute(m_xsiNoNamespaceSchemaLocationName);
250 if (!m_processedSchemaLocations.contains(schemaLocation)) {
251 m_processedSchemaLocations.insert(schemaLocation);
253 if (m_processedNamespaces.contains(QString())) {
254 error(QtXmlPatterns::tr("xsi:noNamespaceSchemaLocation cannot appear after the first no-namespace element or attribute."));
258 QUrl url(schemaLocation);
259 if (url.isRelative()) {
260 Q_ASSERT(m_documentUri.isValid());
262 url = m_documentUri.resolved(url);
265 loadSchema(QString(), url);
269 m_processedNamespaces.insert(m_namePool->stringForNamespace(name().namespaceURI()));
272 error(QtXmlPatterns::tr("No schema defined for validation."));
276 // check if we are 'inside' a type definition
277 if (m_stateMachines.isEmpty()) {
278 // find out the type of the top-level element
279 XsdElement::Ptr element = elementByName(name());
281 if (!hasAttribute(m_xsiTypeName)) {
282 error(QtXmlPatterns::tr("No definition for element %1 available.").arg(formatKeyword(m_namePool, name())));
286 // This instance document has an element with no definition in the schema
287 // but an explicitly given type, that is fine according to the spec.
288 // We will create an element definition manually here and continue the
289 // normal validation process
290 element = XsdElement::Ptr(new XsdElement());
291 element->setName(name());
292 element->setIsAbstract(false);
293 element->setIsNillable(hasAttribute(m_xsiNilName));
295 const QString type = qNameAttribute(m_xsiTypeName);
296 const QXmlName typeName = convertToQName(type);
298 const SchemaType::Ptr elementType = typeByName(typeName);
300 error(QtXmlPatterns::tr("Specified type %1 is not known to the schema.").arg(formatType(m_namePool, typeName)));
303 element->setType(elementType);
306 // rememeber the element we process
307 processedElement = element;
309 if (!validateElement(element, hasStateMachine)) {
314 if (!m_stateMachines.top().proceed<QXmlName>(name())) {
315 error(QtXmlPatterns::tr("Element %1 is not defined in this scope.").arg(formatKeyword(m_namePool, name())));
319 const XsdTerm::Ptr term = m_stateMachines.top().lastTransition();
320 if (term->isElement()) {
321 const XsdElement::Ptr element(term);
323 // rememeber the element we process
324 processedElement = element;
326 if (!validateElement(element, hasStateMachine))
330 const XsdWildcard::Ptr wildcard(term);
331 if (wildcard->processContents() != XsdWildcard::Skip) {
332 XsdElement::Ptr elementDeclaration = elementByName(name());
333 if (!elementDeclaration) {
334 if (hasAttribute(m_xsiTypeName)) {
335 // This instance document has an element with no definition in the schema
336 // but an explicitly given type, that is fine according to the spec.
337 // We will create an element definition manually here and continue the
338 // normal validation process
339 elementDeclaration = XsdElement::Ptr(new XsdElement());
340 elementDeclaration->setName(name());
341 elementDeclaration->setIsAbstract(false);
342 elementDeclaration->setIsNillable(hasAttribute(m_xsiNilName));
344 const QString type = qNameAttribute(m_xsiTypeName);
345 const QXmlName typeName = convertToQName(type);
347 const SchemaType::Ptr elementType = typeByName(typeName);
349 error(QtXmlPatterns::tr("Specified type %1 is not known to the schema.").arg(formatType(m_namePool, typeName)));
352 elementDeclaration->setType(elementType);
356 if (!elementDeclaration) {
357 if (wildcard->processContents() == XsdWildcard::Strict) {
358 error(QtXmlPatterns::tr("Declaration for element %1 does not exist.").arg(formatKeyword(m_namePool->displayName(name()))));
361 // in this case we put a state machine for the xs:anyType on the statemachine stack,
362 // so we accept every content of this element
364 createAndPushStateMachine(anyType()->contentType()->particle());
365 hasStateMachine = true;
368 if (!validateElement(elementDeclaration, hasStateMachine)) {
369 if (wildcard->processContents() == XsdWildcard::Strict) {
370 error(QtXmlPatterns::tr("Element %1 contains invalid content.").arg(formatKeyword(m_namePool->displayName(name()))));
375 // rememeber the type of that element node
376 m_model->setAssignedType(item().toNodeModelIndex(), elementDeclaration->type());
378 } else { // wildcard process contents type is Skip
379 // in this case we put a state machine for the xs:anyType on the statemachine stack,
380 // so we accept every content of this element
382 const XsdWildcard::Ptr wildcard(new XsdWildcard());
383 wildcard->namespaceConstraint()->setVariety(XsdWildcard::NamespaceConstraint::Any);
384 wildcard->setProcessContents(XsdWildcard::Skip);
386 const XsdParticle::Ptr outerParticle(new XsdParticle());
387 outerParticle->setMinimumOccurs(1);
388 outerParticle->setMaximumOccurs(1);
390 const XsdParticle::Ptr innerParticle(new XsdParticle());
391 innerParticle->setMinimumOccurs(0);
392 innerParticle->setMaximumOccursUnbounded(true);
393 innerParticle->setTerm(wildcard);
395 const XsdModelGroup::Ptr outerModelGroup(new XsdModelGroup());
396 outerModelGroup->setCompositor(XsdModelGroup::SequenceCompositor);
397 outerModelGroup->setParticles(XsdParticle::List() << innerParticle);
398 outerParticle->setTerm(outerModelGroup);
400 createAndPushStateMachine(outerParticle);
401 hasStateMachine = true;
409 void XsdValidatingInstanceReader::createAndPushStateMachine(const XsdParticle::Ptr &particle)
411 XsdStateMachine<XsdTerm::Ptr> stateMachine(m_namePool);
413 XsdStateMachineBuilder builder(&stateMachine, m_namePool, XsdStateMachineBuilder::ValidatingMode);
414 const XsdStateMachine<XsdTerm::Ptr>::StateId endState = builder.reset();
415 const XsdStateMachine<XsdTerm::Ptr>::StateId startState = builder.buildParticle(particle, endState);
416 builder.addStartState(startState);
419 QString fileName = QString("/tmp/foo_%1.dot").arg(m_namePool->displayName(complexType->name(m_namePool)));
420 QString pngFileName = QString("/tmp/foo_%1.png").arg(m_namePool->displayName(complexType->name(m_namePool)));
421 QFile file(fileName);
422 file.open(QIODevice::WriteOnly);
423 stateMachine.outputGraph(&file, "Hello");
425 ::system(QString("dot -Tpng %1 -o%2").arg(fileName).arg(pngFileName).toLatin1().data());
428 stateMachine = stateMachine.toDFA();
430 m_stateMachines.push(stateMachine);
433 bool XsdValidatingInstanceReader::validateElement(const XsdElement::Ptr &declaration, bool &hasStateMachine)
435 // http://www.w3.org/TR/xmlschema11-1/#d0e10998
437 bool isNilled = false;
439 // 1 tested already, 'declaration' corresponds D
442 if (declaration->isAbstract()) {
443 error(QtXmlPatterns::tr("Element %1 is declared as abstract.").arg(formatKeyword(declaration->displayName(m_namePool))));
448 if (!declaration->isNillable()) {
449 if (hasAttribute(m_xsiNilName)) {
450 error(QtXmlPatterns::tr("Element %1 is not nillable.").arg(formatKeyword(declaration->displayName(m_namePool))));
454 if (hasAttribute(m_xsiNilName)) {
455 const QString value = attribute(m_xsiNilName);
456 const Boolean::Ptr nil = Boolean::fromLexical(value);
457 if (nil->hasError()) {
458 error(QtXmlPatterns::tr("Attribute %1 contains invalid data: %2").arg(formatKeyword(QLatin1String("nil."))).arg(formatData(value)));
463 if (nil->as<Boolean>()->value() == true) {
465 if (hasChildElement() || hasChildText()) {
466 error(QtXmlPatterns::tr("Element contains content although it is nillable."));
471 if (declaration->valueConstraint() && declaration->valueConstraint()->variety() == XsdElement::ValueConstraint::Fixed) {
472 error(QtXmlPatterns::tr("Fixed value constraint not allowed if element is nillable."));
477 isNilled = nil->as<Boolean>()->value();
481 SchemaType::Ptr finalElementType = declaration->type();
484 if (hasAttribute(m_xsiTypeName)) {
485 const QString type = qNameAttribute(m_xsiTypeName);
486 const QXmlName typeName = convertToQName(type);
488 const SchemaType::Ptr elementType = typeByName(typeName);
491 error(QtXmlPatterns::tr("Specified type %1 is not known to the schema.").arg(formatType(m_namePool, typeName)));
496 SchemaType::DerivationConstraints constraints = 0;
497 if (declaration->disallowedSubstitutions() & NamedSchemaComponent::ExtensionConstraint)
498 constraints |= SchemaType::ExtensionConstraint;
499 if (declaration->disallowedSubstitutions() & NamedSchemaComponent::RestrictionConstraint)
500 constraints |= SchemaType::RestrictionConstraint;
502 if (!XsdSchemaHelper::isValidlySubstitutable(elementType, declaration->type(), constraints)) {
503 if (declaration->type()->name(m_namePool) != BuiltinTypes::xsAnyType->name(m_namePool)) { // xs:anyType is a valid substitutable type here
504 error(QtXmlPatterns::tr("Specified type %1 is not validly substitutable with element type %2.").arg(formatType(m_namePool, elementType)).arg(formatType(m_namePool, declaration->type())));
509 finalElementType = elementType;
512 if (!validateElementType(declaration, finalElementType, isNilled, hasStateMachine))
518 bool XsdValidatingInstanceReader::validateElementType(const XsdElement::Ptr &declaration, const SchemaType::Ptr &type, bool isNilled, bool &hasStateMachine)
520 // @see http://www.w3.org/TR/xmlschema11-1/#d0e11749
525 if (type->isComplexType() && type->isDefinedBySchema()) {
526 if (XsdComplexType::Ptr(type)->isAbstract()) {
527 error(QtXmlPatterns::tr("Complex type %1 is not allowed to be abstract.").arg(formatType(m_namePool, type)));
533 if (type->isSimpleType())
534 return validateElementSimpleType(declaration, type, isNilled); // 3.1
536 return validateElementComplexType(declaration, type, isNilled, hasStateMachine); // 3.2
539 bool XsdValidatingInstanceReader::validateElementSimpleType(const XsdElement::Ptr &declaration, const SchemaType::Ptr &type, bool isNilled)
541 // @see http://www.w3.org/TR/xmlschema11-1/#d0e11749
544 const QSet<QXmlName> allowedAttributes(QSet<QXmlName>() << m_xsiNilName << m_xsiTypeName << m_xsiSchemaLocationName << m_xsiNoNamespaceSchemaLocationName);
545 QSet<QXmlName> elementAttributes = attributeNames();
546 elementAttributes.subtract(allowedAttributes);
547 if (!elementAttributes.isEmpty()) {
548 error(QtXmlPatterns::tr("Element %1 contains not allowed attributes.").arg(formatKeyword(declaration->displayName(m_namePool))));
553 if (hasChildElement()) {
554 error(QtXmlPatterns::tr("Element %1 contains not allowed child element.").arg(formatKeyword(declaration->displayName(m_namePool))));
560 const XsdFacet::Hash facets = XsdTypeChecker::mergedFacetsForType(type, m_context);
563 if (hasChildText()) {
564 actualValue = XsdTypeChecker::normalizedValue(text(), facets);
566 if (declaration->valueConstraint())
567 actualValue = XsdTypeChecker::normalizedValue(declaration->valueConstraint()->value(), facets);
571 AnySimpleType::Ptr boundType;
573 const XsdTypeChecker checker(m_context, namespaceBindings(item().toNodeModelIndex()), sourceLocation());
574 if (!checker.isValidString(actualValue, type, errorMsg, &boundType)) {
575 error(QtXmlPatterns::tr("Content of element %1 does not match its type definition: %2.").arg(formatKeyword(declaration->displayName(m_namePool))).arg(errorMsg));
580 if (declaration->valueConstraint() && declaration->valueConstraint()->variety() == XsdElement::ValueConstraint::Fixed) {
581 const QString actualConstraintValue = XsdTypeChecker::normalizedValue(declaration->valueConstraint()->value(), facets);
582 if (!text().isEmpty() && !checker.valuesAreEqual(actualValue, actualConstraintValue, type)) {
583 error(QtXmlPatterns::tr("Content of element %1 does not match defined value constraint.").arg(formatKeyword(declaration->displayName(m_namePool))));
589 // 4 checked in validateElement already
591 // rememeber the type of that element node
592 m_model->setAssignedType(item().toNodeModelIndex(), type);
594 const XsdFacet::Hash facets = XsdTypeChecker::mergedFacetsForType(type, m_context);
595 const QString actualValue = XsdTypeChecker::normalizedValue(text(), facets);
597 if (BuiltinTypes::xsID->wxsTypeMatches(type)) {
598 addIdIdRefBinding(actualValue, declaration);
601 if (m_idRefsType->wxsTypeMatches(type)) {
602 const QStringList idRefs = actualValue.split(QLatin1Char(' '), QString::SkipEmptyParts);
603 for (int i = 0; i < idRefs.count(); ++i) {
604 m_idRefs.insert(idRefs.at(i));
606 } else if (BuiltinTypes::xsIDREF->wxsTypeMatches(type)) {
607 m_idRefs.insert(actualValue);
613 static bool hasIDAttributeUse(const XsdAttributeUse::List &uses)
615 const int count = uses.count();
616 for (int i = 0; i < count; ++i) {
617 if (BuiltinTypes::xsID->wxsTypeMatches(uses.at(i)->attribute()->type()))
624 bool XsdValidatingInstanceReader::validateElementComplexType(const XsdElement::Ptr &declaration, const SchemaType::Ptr &type, bool isNilled, bool &hasStateMachine)
626 // @see http://www.w3.org/TR/xmlschema11-1/#cvc-complex-type
630 XsdComplexType::Ptr complexType;
632 if (type->isDefinedBySchema()) {
633 complexType = XsdComplexType::Ptr(type);
635 if (type->name(m_namePool) == BuiltinTypes::xsAnyType->name(m_namePool))
636 complexType = anyType();
641 if (complexType->contentType()->variety() == XsdComplexType::ContentType::Empty) {
642 if (hasChildText() || hasChildElement()) {
643 error(QtXmlPatterns::tr("Element %1 contains not allowed child content.").arg(formatKeyword(declaration->displayName(m_namePool))));
649 if (complexType->contentType()->variety() == XsdComplexType::ContentType::Simple) {
650 if (hasChildElement()) {
651 error(QtXmlPatterns::tr("Element %1 contains not allowed child element.").arg(formatKeyword(declaration->displayName(m_namePool))));
655 const XsdFacet::Hash facets = XsdTypeChecker::mergedFacetsForType(complexType->contentType()->simpleType(), m_context);
657 if (hasChildText()) {
658 actualValue = XsdTypeChecker::normalizedValue(text(), facets);
660 if (declaration->valueConstraint())
661 actualValue = XsdTypeChecker::normalizedValue(declaration->valueConstraint()->value(), facets);
665 AnySimpleType::Ptr boundType;
666 const XsdTypeChecker checker(m_context, namespaceBindings(item().toNodeModelIndex()), sourceLocation());
667 if (!checker.isValidString(actualValue, complexType->contentType()->simpleType(), errorMsg, &boundType)) {
668 error(QtXmlPatterns::tr("Content of element %1 does not match its type definition: %2.").arg(formatKeyword(declaration->displayName(m_namePool))).arg(errorMsg));
673 if (declaration->valueConstraint() && declaration->valueConstraint()->variety() == XsdElement::ValueConstraint::Fixed) {
674 if (!checker.valuesAreEqual(actualValue, declaration->valueConstraint()->value(), boundType)) {
675 error(QtXmlPatterns::tr("Content of element %1 does not match defined value constraint.").arg(formatKeyword(declaration->displayName(m_namePool))));
682 if (complexType->contentType()->variety() == XsdComplexType::ContentType::ElementOnly) {
683 if (!text().simplified().isEmpty()) {
684 error(QtXmlPatterns::tr("Element %1 contains not allowed text content.").arg(formatKeyword(declaration->displayName(m_namePool))));
690 if (complexType->contentType()->variety() == XsdComplexType::ContentType::ElementOnly ||
691 complexType->contentType()->variety() == XsdComplexType::ContentType::Mixed) {
693 if (complexType->contentType()->particle()) {
694 createAndPushStateMachine(complexType->contentType()->particle());
695 hasStateMachine = true;
699 if (complexType->contentType()->variety() == XsdComplexType::ContentType::Mixed) {
700 if (declaration->valueConstraint() && declaration->valueConstraint()->variety() == XsdElement::ValueConstraint::Fixed) {
701 if (hasChildElement()) {
702 error(QtXmlPatterns::tr("Element %1 cannot contain other elements, as it has a fixed content.").arg(formatKeyword(declaration->displayName(m_namePool))));
706 const XsdFacet::Hash facets = XsdTypeChecker::mergedFacetsForType(complexType->contentType()->simpleType(), m_context);
708 if (hasChildText()) {
709 actualValue = XsdTypeChecker::normalizedValue(text(), facets);
711 if (declaration->valueConstraint())
712 actualValue = XsdTypeChecker::normalizedValue(declaration->valueConstraint()->value(), facets);
715 if (actualValue != declaration->valueConstraint()->value()) {
716 error(QtXmlPatterns::tr("Content of element %1 does not match defined value constraint.").arg(formatKeyword(declaration->displayName(m_namePool))));
725 if (type->isDefinedBySchema()) {
726 const XsdComplexType::Ptr complexType(type);
728 // create a lookup hash for faster access
729 QHash<QXmlName, XsdAttributeUse::Ptr> attributeUseHash;
731 const XsdAttributeUse::List attributeUses = complexType->attributeUses();
732 for (int i = 0; i < attributeUses.count(); ++i)
733 attributeUseHash.insert(attributeUses.at(i)->attribute()->name(m_namePool), attributeUses.at(i));
736 const QSet<QXmlName> attributes(attributeNames());
739 QHashIterator<QXmlName, XsdAttributeUse::Ptr> usesIt(attributeUseHash);
740 while (usesIt.hasNext()) {
743 if (usesIt.value()->isRequired()) {
744 if (!attributes.contains(usesIt.key())) {
745 error(QtXmlPatterns::tr("Element %1 is missing required attribute %2.").arg(formatKeyword(declaration->displayName(m_namePool)))
746 .arg(formatKeyword(m_namePool->displayName(usesIt.key()))));
752 bool hasIDAttribute = hasIDAttributeUse(complexType->attributeUses());
755 QSetIterator<QXmlName> it(attributes);
756 while (it.hasNext()) {
757 const QXmlName attributeName = it.next();
759 // skip builtin attributes
760 if (attributeName == m_xsiNilName ||
761 attributeName == m_xsiTypeName ||
762 attributeName == m_xsiSchemaLocationName ||
763 attributeName == m_xsiNoNamespaceSchemaLocationName)
767 if (attributeUseHash.contains(attributeName) && (attributeUseHash.value(attributeName)->useType() != XsdAttributeUse::ProhibitedUse)) {
768 if (!validateAttribute(attributeUseHash.value(attributeName), attribute(attributeName)))
771 if (complexType->attributeWildcard()) {
772 const XsdWildcard::Ptr wildcard(complexType->attributeWildcard());
773 if (!validateAttributeWildcard(attributeName, wildcard)) {
774 error(QtXmlPatterns::tr("Attribute %1 does not match the attribute wildcard.").arg(formatKeyword(m_namePool->displayName(attributeName))));
778 if (wildcard->processContents() != XsdWildcard::Skip) {
779 const XsdAttribute::Ptr attributeDeclaration = attributeByName(attributeName);
781 if (!attributeDeclaration) {
782 if (wildcard->processContents() == XsdWildcard::Strict) {
783 error(QtXmlPatterns::tr("Declaration for attribute %1 does not exist.").arg(formatKeyword(m_namePool->displayName(attributeName))));
787 if (BuiltinTypes::xsID->wxsTypeMatches(attributeDeclaration->type())) {
788 if (hasIDAttribute) {
789 error(QtXmlPatterns::tr("Element %1 contains two attributes of type %2.")
790 .arg(formatKeyword(declaration->displayName(m_namePool)))
791 .arg(formatKeyword("ID")));
795 hasIDAttribute = true;
798 if (!validateAttribute(attributeDeclaration, attribute(attributeName))) {
799 if (wildcard->processContents() == XsdWildcard::Strict) {
800 error(QtXmlPatterns::tr("Attribute %1 contains invalid content.").arg(formatKeyword(m_namePool->displayName(attributeName))));
807 error(QtXmlPatterns::tr("Element %1 contains unknown attribute %2.").arg(formatKeyword(declaration->displayName(m_namePool)))
808 .arg(formatKeyword(m_namePool->displayName(attributeName))));
822 // TODO: check assertions
825 // TODO: check type table restrictions
827 // rememeber the type of that element node
828 m_model->setAssignedType(item().toNodeModelIndex(), type);
833 bool XsdValidatingInstanceReader::validateAttribute(const XsdAttributeUse::Ptr &declaration, const QString &value)
835 const AnySimpleType::Ptr attributeType = declaration->attribute()->type();
836 const XsdFacet::Hash facets = XsdTypeChecker::mergedFacetsForType(attributeType, m_context);
838 const QString actualValue = XsdTypeChecker::normalizedValue(value, facets);
841 AnySimpleType::Ptr boundType;
843 const QXmlNodeModelIndex index = attributeItem(declaration->attribute()->name(m_namePool)).toNodeModelIndex();
845 const XsdTypeChecker checker(m_context, namespaceBindings(index), sourceLocation());
846 if (!checker.isValidString(actualValue, attributeType, errorMsg, &boundType)) {
847 error(QtXmlPatterns::tr("Content of attribute %1 does not match its type definition: %2.").arg(formatKeyword(declaration->attribute()->displayName(m_namePool))).arg(errorMsg));
851 // @see http://www.w3.org/TR/xmlschema11-1/#cvc-au
852 if (declaration->valueConstraint() && declaration->valueConstraint()->variety() == XsdAttributeUse::ValueConstraint::Fixed) {
853 const QString actualConstraintValue = XsdTypeChecker::normalizedValue(declaration->valueConstraint()->value(), facets);
854 if (!checker.valuesAreEqual(actualValue, actualConstraintValue, attributeType)) {
855 error(QtXmlPatterns::tr("Content of attribute %1 does not match defined value constraint.").arg(formatKeyword(declaration->attribute()->displayName(m_namePool))));
860 if (BuiltinTypes::xsID->wxsTypeMatches(declaration->attribute()->type())) {
861 addIdIdRefBinding(actualValue, declaration->attribute());
864 if (m_idRefsType->wxsTypeMatches(declaration->attribute()->type())) {
865 const QStringList idRefs = actualValue.split(QLatin1Char(' '), QString::SkipEmptyParts);
866 for (int i = 0; i < idRefs.count(); ++i)
867 m_idRefs.insert(idRefs.at(i));
868 } else if (BuiltinTypes::xsIDREF->wxsTypeMatches(declaration->attribute()->type())) {
869 m_idRefs.insert(actualValue);
872 m_model->setAssignedType(index, declaration->attribute()->type());
873 m_model->setAssignedAttribute(index, declaration->attribute());
878 //TODO: merge that with the method above
879 bool XsdValidatingInstanceReader::validateAttribute(const XsdAttribute::Ptr &declaration, const QString &value)
881 const AnySimpleType::Ptr attributeType = declaration->type();
882 const XsdFacet::Hash facets = XsdTypeChecker::mergedFacetsForType(attributeType, m_context);
884 const QString actualValue = XsdTypeChecker::normalizedValue(value, facets);
887 AnySimpleType::Ptr boundType;
889 const QXmlNodeModelIndex index = attributeItem(declaration->name(m_namePool)).toNodeModelIndex();
891 const XsdTypeChecker checker(m_context, namespaceBindings(index), sourceLocation());
892 if (!checker.isValidString(actualValue, attributeType, errorMsg, &boundType)) {
893 error(QtXmlPatterns::tr("Content of attribute %1 does not match its type definition: %2.").arg(formatKeyword(declaration->displayName(m_namePool))).arg(errorMsg));
897 // @see http://www.w3.org/TR/xmlschema11-1/#cvc-au
898 if (declaration->valueConstraint() && declaration->valueConstraint()->variety() == XsdAttribute::ValueConstraint::Fixed) {
899 const QString actualConstraintValue = XsdTypeChecker::normalizedValue(declaration->valueConstraint()->value(), facets);
900 if (!checker.valuesAreEqual(actualValue, actualConstraintValue, attributeType)) {
901 error(QtXmlPatterns::tr("Content of attribute %1 does not match defined value constraint.").arg(formatKeyword(declaration->displayName(m_namePool))));
906 if (BuiltinTypes::xsID->wxsTypeMatches(declaration->type())) {
907 addIdIdRefBinding(actualValue, declaration);
910 if (m_idRefsType->wxsTypeMatches(declaration->type())) {
911 const QStringList idRefs = actualValue.split(QLatin1Char(' '), QString::SkipEmptyParts);
912 for (int i = 0; i < idRefs.count(); ++i)
913 m_idRefs.insert(idRefs.at(i));
914 } else if (BuiltinTypes::xsIDREF->wxsTypeMatches(declaration->type())) {
915 m_idRefs.insert(actualValue);
918 m_model->setAssignedType(index, declaration->type());
919 m_model->setAssignedAttribute(index, declaration);
924 bool XsdValidatingInstanceReader::validateAttributeWildcard(const QXmlName &attributeName, const XsdWildcard::Ptr &wildcard)
926 // @see http://www.w3.org/TR/xmlschema11-1/#cvc-wildcard
928 // wildcards using XsdWildcard::absentNamespace, so we have to fix that here
929 QXmlName name(attributeName);
930 if (name.namespaceURI() == StandardNamespaces::empty) {
931 name.setNamespaceURI(m_namePool->allocateNamespace(XsdWildcard::absentNamespace()));
934 return XsdSchemaHelper::wildcardAllowsExpandedName(name, wildcard, m_namePool);
937 bool XsdValidatingInstanceReader::validateIdentityConstraint(const XsdElement::Ptr &element, const QXmlItem ¤tItem)
939 const XsdIdentityConstraint::List constraints = element->identityConstraints();
941 for (int i = 0; i < constraints.count(); ++i) {
942 const XsdIdentityConstraint::Ptr constraint = constraints.at(i);
944 TargetNode::Set targetNodeSet, qualifiedNodeSet;
945 selectNodeSets(element, currentItem, constraint, targetNodeSet, qualifiedNodeSet);
947 if (constraint->category() == XsdIdentityConstraint::Unique) {
948 if (!validateUniqueIdentityConstraint(element, constraint, qualifiedNodeSet))
950 } else if (constraint->category() == XsdIdentityConstraint::Key) {
951 if (!validateKeyIdentityConstraint(element, constraint, targetNodeSet, qualifiedNodeSet))
956 // we do the keyref check in a separated run to make sure that all keys are available
957 for (int i = 0; i < constraints.count(); ++i) {
958 const XsdIdentityConstraint::Ptr constraint = constraints.at(i);
959 if (constraint->category() == XsdIdentityConstraint::KeyReference) {
960 TargetNode::Set targetNodeSet, qualifiedNodeSet;
961 selectNodeSets(element, currentItem, constraint, targetNodeSet, qualifiedNodeSet);
963 if (!validateKeyRefIdentityConstraint(element, constraint, qualifiedNodeSet))
971 bool XsdValidatingInstanceReader::validateUniqueIdentityConstraint(const XsdElement::Ptr&, const XsdIdentityConstraint::Ptr &constraint, const TargetNode::Set &qualifiedNodeSet)
973 // @see http://www.w3.org/TR/xmlschema11-1/#d0e32243
976 const XsdSchemaSourceLocationReflection reflection(sourceLocation());
978 QSetIterator<TargetNode> it(qualifiedNodeSet);
979 while (it.hasNext()) {
980 const TargetNode node = it.next();
981 QSetIterator<TargetNode> innerIt(qualifiedNodeSet);
982 while (innerIt.hasNext()) {
983 const TargetNode innerNode = innerIt.next();
985 if (node == innerNode) // do not compare with ourself
988 if (node.fieldsAreEqual(innerNode, m_namePool, m_context, &reflection)) {
989 error(QtXmlPatterns::tr("Non-unique value found for constraint %1.").arg(formatKeyword(constraint->displayName(m_namePool))));
995 m_idcKeys.insert(constraint->name(m_namePool), qualifiedNodeSet);
1000 bool XsdValidatingInstanceReader::validateKeyIdentityConstraint(const XsdElement::Ptr &element, const XsdIdentityConstraint::Ptr &constraint, const TargetNode::Set &targetNodeSet, const TargetNode::Set &qualifiedNodeSet)
1002 // @see http://www.w3.org/TR/xmlschema11-1/#d0e32243
1005 const XsdSchemaSourceLocationReflection reflection(sourceLocation());
1008 if (targetNodeSet.count() != qualifiedNodeSet.count()) {
1009 error(QtXmlPatterns::tr("Key constraint %1 contains absent fields.").arg(formatKeyword(constraint->displayName(m_namePool))));
1014 if (!validateUniqueIdentityConstraint(element, constraint, qualifiedNodeSet))
1018 QSetIterator<TargetNode> it(qualifiedNodeSet);
1019 while (it.hasNext()) {
1020 const TargetNode node = it.next();
1021 const QVector<QXmlItem> fieldItems = node.fieldItems();
1022 for (int i = 0; i < fieldItems.count(); ++i) {
1023 const QXmlNodeModelIndex index = fieldItems.at(i).toNodeModelIndex();
1024 if (m_model->kind(index) == QXmlNodeModelIndex::Element) {
1025 const XsdElement::Ptr declaration = m_model->assignedElement(index);
1026 if (declaration && declaration->isNillable()) {
1027 error(QtXmlPatterns::tr("Key constraint %1 contains references nillable element %2.")
1028 .arg(formatKeyword(constraint->displayName(m_namePool)))
1029 .arg(formatKeyword(declaration->displayName(m_namePool))));
1036 m_idcKeys.insert(constraint->name(m_namePool), qualifiedNodeSet);
1041 bool XsdValidatingInstanceReader::validateKeyRefIdentityConstraint(const XsdElement::Ptr&, const XsdIdentityConstraint::Ptr &constraint, const TargetNode::Set &qualifiedNodeSet)
1043 // @see http://www.w3.org/TR/xmlschema11-1/#d0e32243
1046 const XsdSchemaSourceLocationReflection reflection(sourceLocation());
1048 const TargetNode::Set keySet = m_idcKeys.value(constraint->referencedKey()->name(m_namePool));
1050 QSetIterator<TargetNode> it(qualifiedNodeSet);
1051 while (it.hasNext()) {
1052 const TargetNode node = it.next();
1054 bool foundMatching = false;
1056 QSetIterator<TargetNode> keyIt(keySet);
1057 while (keyIt.hasNext()) {
1058 const TargetNode keyNode = keyIt.next();
1060 if (node.fieldsAreEqual(keyNode, m_namePool, m_context, &reflection)) {
1061 foundMatching = true;
1066 if (!foundMatching) {
1067 error(QtXmlPatterns::tr("No referenced value found for key reference %1.").arg(formatKeyword(constraint->displayName(m_namePool))));
1075 QXmlQuery XsdValidatingInstanceReader::createXQuery(const QList<QXmlName> &namespaceBindings, const QXmlItem &contextNode, const QString &queryString) const
1077 // create a public name pool from our name pool
1078 QXmlNamePool namePool(m_namePool.data());
1080 // the QXmlQuery shall work with the same name pool as we do
1081 QXmlQuery query(namePool);
1083 // add additional namespace bindings
1084 QXmlQueryPrivate *queryPrivate = query.d;
1086 for (int i = 0; i < namespaceBindings.count(); ++i) {
1087 if (!namespaceBindings.at(i).prefix() == StandardPrefixes::empty)
1088 queryPrivate->addAdditionalNamespaceBinding(namespaceBindings.at(i));
1091 // set the context node for that query and the query string
1092 query.setFocus(contextNode);
1093 query.setQuery(queryString, m_documentUri);
1098 bool XsdValidatingInstanceReader::selectNodeSets(const XsdElement::Ptr&, const QXmlItem ¤tItem, const XsdIdentityConstraint::Ptr &constraint, TargetNode::Set &targetNodeSet, TargetNode::Set &qualifiedNodeSet)
1100 // at first select all target nodes
1101 const XsdXPathExpression::Ptr selector = constraint->selector();
1102 const XsdXPathExpression::List fields = constraint->fields();
1104 QXmlQuery query = createXQuery(selector->namespaceBindings(), currentItem, selector->expression());
1106 QXmlResultItems resultItems;
1107 query.evaluateTo(&resultItems);
1109 // now we iterate over all target nodes and select the fields for each node
1110 QXmlItem item(resultItems.next());
1111 while (!item.isNull()) {
1113 TargetNode targetNode(item);
1115 for (int i = 0; i < fields.count(); ++i) {
1116 const XsdXPathExpression::Ptr field = fields.at(i);
1117 QXmlQuery fieldQuery = createXQuery(field->namespaceBindings(), item, field->expression());
1119 QXmlResultItems fieldResultItems;
1120 fieldQuery.evaluateTo(&fieldResultItems);
1122 // copy result into vetor for better testing...
1123 QVector<QXmlItem> fieldVector;
1124 QXmlItem fieldItem(fieldResultItems.next());
1125 while (!fieldItem.isNull()) {
1126 fieldVector.append(fieldItem);
1127 fieldItem = fieldResultItems.next();
1130 if (fieldVector.count() > 1) {
1131 error(QtXmlPatterns::tr("More than one value found for field %1.").arg(formatData(field->expression())));
1135 if (fieldVector.count() == 1) {
1136 fieldItem = fieldVector.first();
1138 const QXmlNodeModelIndex index = fieldItem.toNodeModelIndex();
1139 const SchemaType::Ptr type = m_model->assignedType(index);
1142 if (type->isComplexType()) {
1143 if (type->isDefinedBySchema()) {
1144 if (XsdComplexType::Ptr(type)->contentType()->variety() != XsdComplexType::ContentType::Simple)
1151 error(QtXmlPatterns::tr("Field %1 has no simple type.").arg(formatData(field->expression())));
1155 SchemaType::Ptr targetType = type;
1156 QString value = m_model->stringValue(fieldItem.toNodeModelIndex());
1158 if (type->isDefinedBySchema()) {
1159 if (type->isSimpleType())
1160 targetType = XsdSimpleType::Ptr(type)->primitiveType();
1162 targetType = XsdComplexType::Ptr(type)->contentType()->simpleType();
1164 if (BuiltinTypes::xsAnySimpleType->name(m_namePool) == type->name(m_namePool)) {
1165 targetType = BuiltinTypes::xsString;
1166 value = QLatin1String("___anySimpleType_value");
1170 // if it is xs:QName derived type, we normalize the name content
1171 // and do a string comparison
1172 if (BuiltinTypes::xsQName->wxsTypeMatches(type)) {
1173 targetType = BuiltinTypes::xsString;
1175 const QXmlName qName = convertToQName(value.trimmed());
1176 value = QString::fromLatin1("%1:%2").arg(m_namePool->stringForNamespace(qName.namespaceURI())).arg(m_namePool->stringForLocalName(qName.localName()));
1179 targetNode.addField(fieldItem, value, targetType);
1181 // we add an empty entry here, that makes comparison easier later on
1182 targetNode.addField(QXmlItem(), QString(), SchemaType::Ptr());
1186 targetNodeSet.insert(targetNode);
1188 item = resultItems.next();
1191 // copy all items from target node set to qualified node set, that have no empty fields
1192 QSetIterator<TargetNode> it(targetNodeSet);
1193 while (it.hasNext()) {
1194 const TargetNode node = it.next();
1195 if (node.emptyFieldsCount() == 0)
1196 qualifiedNodeSet.insert(node);
1202 XsdElement::Ptr XsdValidatingInstanceReader::elementByName(const QXmlName &name) const
1204 return m_schema->element(name);
1207 XsdAttribute::Ptr XsdValidatingInstanceReader::attributeByName(const QXmlName &name) const
1209 return m_schema->attribute(name);
1212 SchemaType::Ptr XsdValidatingInstanceReader::typeByName(const QXmlName &name) const
1214 const SchemaType::Ptr type = m_schema->type(name);
1218 return m_context->schemaTypeFactory()->createSchemaType(name);
1221 void XsdValidatingInstanceReader::addIdIdRefBinding(const QString &id, const NamedSchemaComponent::Ptr &binding)
1223 if (!m_model->idIdRefBindings(id).isEmpty()) {
1224 error(QtXmlPatterns::tr("ID value '%1' is not unique.").arg(formatKeyword(id)));
1228 m_model->addIdIdRefBinding(id, binding);
1231 QString XsdValidatingInstanceReader::qNameAttribute(const QXmlName &attributeName)
1233 const QString value = attribute(attributeName).simplified();
1234 if (!XPathHelper::isQName(value)) {
1235 error(QtXmlPatterns::tr("'%1' attribute contains invalid QName content: %2.").arg(m_namePool->displayName(attributeName)).arg(formatData(value)));
1242 XsdComplexType::Ptr XsdValidatingInstanceReader::anyType()
1247 const XsdWildcard::Ptr wildcard(new XsdWildcard());
1248 wildcard->namespaceConstraint()->setVariety(XsdWildcard::NamespaceConstraint::Any);
1249 wildcard->setProcessContents(XsdWildcard::Lax);
1251 const XsdParticle::Ptr outerParticle(new XsdParticle());
1252 outerParticle->setMinimumOccurs(1);
1253 outerParticle->setMaximumOccurs(1);
1255 const XsdParticle::Ptr innerParticle(new XsdParticle());
1256 innerParticle->setMinimumOccurs(0);
1257 innerParticle->setMaximumOccursUnbounded(true);
1258 innerParticle->setTerm(wildcard);
1260 const XsdModelGroup::Ptr outerModelGroup(new XsdModelGroup());
1261 outerModelGroup->setCompositor(XsdModelGroup::SequenceCompositor);
1262 outerModelGroup->setParticles(XsdParticle::List() << innerParticle);
1263 outerParticle->setTerm(outerModelGroup);
1265 m_anyType = XsdComplexType::Ptr(new XsdComplexType());
1266 m_anyType->setName(BuiltinTypes::xsAnyType->name(m_namePool));
1267 m_anyType->setDerivationMethod(XsdComplexType::DerivationRestriction);
1268 m_anyType->contentType()->setVariety(XsdComplexType::ContentType::Mixed);
1269 m_anyType->contentType()->setParticle(outerParticle);
1270 m_anyType->setAttributeWildcard(wildcard);
1271 m_anyType->setIsAbstract(false);