File indexing completed on 2024-05-12 04:38:43
0001 /* 0002 SPDX-FileCopyrightText: 2012 Olivier de Gaalon <olivier.jg@gmail.com> 0003 0004 SPDX-License-Identifier: LGPL-2.0-only 0005 */ 0006 0007 #include "declarationvalidator.h" 0008 0009 #include "language/duchain/declaration.h" 0010 #include "testsuite.h" 0011 #include "jsondeclarationtests.h" 0012 0013 #include <QJsonDocument> 0014 0015 #include <utility> 0016 0017 namespace KDevelop { 0018 class DeclarationValidatorPrivate 0019 { 0020 public: 0021 DeclarationValidator::TestDataEditor testDataAdjuster{}; 0022 bool testsPassed = true; 0023 }; 0024 0025 QByteArray preprocess(QByteArray json) 0026 { 0027 int commentIndex = json.indexOf('#', 0); 0028 while (commentIndex > -1) { 0029 int commentEnd = json.indexOf('\n', commentIndex); 0030 if (commentEnd == -1) { 0031 json.truncate(commentIndex); 0032 break; 0033 } 0034 json.remove(commentIndex, commentEnd - commentIndex); 0035 commentIndex = json.indexOf('#', commentIndex); 0036 } 0037 0038 return '{' + json + '}'; 0039 } 0040 0041 DeclarationValidator::DeclarationValidator(TestDataEditor testDataAdjuster) 0042 : d_ptr(new DeclarationValidatorPrivate{std::move(testDataAdjuster)}) 0043 { 0044 } 0045 DeclarationValidator::~DeclarationValidator() 0046 { 0047 } 0048 0049 bool DeclarationValidator::testsPassed() const 0050 { 0051 Q_D(const DeclarationValidator); 0052 0053 return d->testsPassed; 0054 } 0055 0056 void DeclarationValidator::visit(DUContext*) { } 0057 void DeclarationValidator::visit(Declaration* declaration) 0058 { 0059 Q_D(DeclarationValidator); 0060 0061 QJsonParseError error; 0062 const auto json = preprocess(declaration->comment()); 0063 QJsonDocument doc = QJsonDocument::fromJson(json, &error); 0064 0065 if (error.error == 0) { 0066 QVariantMap testData = doc.toVariant().toMap(); 0067 if (d->testDataAdjuster) { 0068 d->testDataAdjuster(testData); 0069 } 0070 if (!KDevelop::runTests(testData, declaration)) 0071 d->testsPassed = false; 0072 } else 0073 { 0074 d->testsPassed = false; 0075 QMessageLogger logger(declaration->topContext()->url().byteArray().constData(), 0076 declaration->range().start.line, nullptr); 0077 logger.warning() << "Error parsing JSON test data:" << error.errorString() << "at offset" << error.offset << 0078 "JSON input was:\n" << json; 0079 } 0080 } 0081 }