From df1de50549034547ea82d6e9d027c9f4da552c98 Mon Sep 17 00:00:00 2001 From: Johannes Kalmbach Date: Wed, 3 Dec 2025 12:44:47 +0100 Subject: [PATCH] Reformat the codebase using clang-format-19 Signed-off-by: Johannes Kalmbach --- .clang-format | 38 ++- .github/workflows/format-check.yml | 4 +- .pre-commit-config.yaml | 2 +- benchmark/JoinAlgorithmBenchmark.cpp | 66 ++--- benchmark/infrastructure/Benchmark.h | 6 +- .../BenchmarkMeasurementContainer.h | 38 ++- benchmark/infrastructure/BenchmarkToJson.cpp | 13 +- benchmark/util/ResultTableColumnOperations.h | 32 +- misc/format-check.sh | 4 +- src/backports/StartsWithAndEndsWith.h | 116 +++----- src/backports/iterator.h | 42 ++- src/backports/shift.h | 18 +- src/engine/AddCombinedRowToTable.h | 7 +- src/engine/CallFixedSize.h | 46 ++- src/engine/CartesianProductJoin.cpp | 14 +- src/engine/CartesianProductJoin.h | 13 +- src/engine/ExportQueryExecutionTrees.cpp | 6 +- src/engine/Filter.cpp | 12 +- src/engine/Filter.h | 16 +- src/engine/GraphStoreProtocol.h | 45 +-- src/engine/GroupByHashMapOptimization.h | 6 +- src/engine/Join.cpp | 14 +- src/engine/Join.h | 12 +- src/engine/JoinHelpers.h | 20 +- src/engine/LocalVocab.h | 4 +- src/engine/QueryPlanner.cpp | 16 +- src/engine/Result.h | 16 +- src/engine/Server.cpp | 127 ++++---- src/engine/Server.h | 139 ++++----- src/engine/Service.cpp | 5 +- src/engine/TextIndexScanForEntity.cpp | 4 +- src/engine/TextIndexScanForWord.cpp | 3 +- src/engine/TextLimit.cpp | 4 +- src/engine/TransitivePathBinSearch.cpp | 5 +- src/engine/TransitivePathImpl.h | 8 +- .../idTable/CompressedExternalIdTable.h | 21 +- src/engine/idTable/IdTable.h | 192 ++++++------ src/engine/idTable/IdTableRow.h | 75 +++-- .../sparqlExpressions/AggregateExpression.cpp | 3 +- .../sparqlExpressions/AggregateExpression.h | 8 +- .../sparqlExpressions/BlankNodeExpression.cpp | 13 +- .../ConditionalExpressions.cpp | 13 +- .../ConvertToDtypeConstructor.cpp | 12 +- .../GroupConcatExpression.cpp | 6 +- .../sparqlExpressions/LiteralExpression.h | 10 +- src/engine/sparqlExpressions/NaryExpression.h | 11 +- .../sparqlExpressions/NaryExpressionImpl.h | 17 +- .../NumericBinaryExpressions.cpp | 6 +- .../NumericUnaryExpressions.cpp | 5 +- .../PrefilterExpressionIndex.cpp | 4 +- .../RelationalExpressionHelpers.h | 13 +- .../RelationalExpressions.cpp | 44 +-- .../SparqlExpressionGenerators.h | 54 ++-- .../sparqlExpressions/SparqlExpressionTypes.h | 40 +-- .../SparqlExpressionValueGetters.cpp | 16 +- .../SparqlExpressionValueGetters.h | 16 +- .../sparqlExpressions/StdevExpression.cpp | 6 +- .../sparqlExpressions/StringExpressions.cpp | 15 +- .../StringExpressionsHelper.h | 9 +- src/global/IdTriple.h | 7 +- src/index/CompressedRelation.cpp | 39 ++- src/index/CompressedRelation.h | 16 +- src/index/DeltaTriples.cpp | 6 +- src/index/GraphFilter.h | 5 +- src/index/IndexImpl.cpp | 40 ++- src/index/IndexImpl.h | 32 +- src/index/KeyOrder.h | 8 +- src/index/LocalVocabEntry.h | 5 +- src/index/LocatedTriples.cpp | 16 +- src/index/StringSortComparator.h | 11 +- src/index/TextIndexReadWrite.h | 13 +- src/index/VocabularyMerger.h | 20 +- src/index/VocabularyMergerImpl.h | 31 +- src/index/vocabulary/CompressedVocabulary.h | 6 +- src/libqlever/LibQLeverExample.cpp | 3 +- src/parser/LiteralOrIri.h | 6 +- src/parser/ParallelParseBuffer.h | 7 +- src/parser/PropertyPath.h | 19 +- src/parser/RdfParser.h | 6 +- src/parser/TripleComponent.h | 27 +- src/parser/data/Literal.h | 10 +- .../sparqlParser/SparqlQleverVisitor.cpp | 18 +- src/parser/sparqlParser/SparqlQleverVisitor.h | 19 +- src/rdfTypes/GeoPoint.h | 4 +- src/rdfTypes/GeometryInfo.cpp | 6 +- src/rdfTypes/GeometryInfo.h | 12 +- src/rdfTypes/GeometryInfoHelpersImpl.h | 22 +- src/rdfTypes/Iri.h | 5 +- src/rdfTypes/Literal.h | 4 +- src/rdfTypes/Variable.cpp | 4 +- src/util/Algorithm.h | 48 ++- src/util/AllocatorWithLimit.h | 4 +- src/util/AsioHelpers.h | 31 +- src/util/BlankNodeManager.h | 4 +- src/util/Cache.h | 24 +- src/util/CancellationHandle.cpp | 8 +- src/util/CancellationHandle.h | 37 ++- src/util/ChunkedForLoop.h | 46 ++- src/util/ComparisonWithNan.h | 10 +- src/util/CompressionUsingZstd/ZstdWrapper.h | 14 +- src/util/ConcurrentCache.h | 80 ++--- src/util/ConfigManager/ConfigManager.cpp | 123 ++++---- src/util/ConfigManager/ConfigManager.h | 280 +++++++++--------- src/util/ConfigManager/ConfigOption.h | 38 +-- src/util/ConfigManager/ConfigOptionProxy.h | 9 +- src/util/ConfigManager/Validator.h | 72 +++-- src/util/ConstexprUtils.h | 43 ++- src/util/CopyableUniquePtr.h | 13 +- src/util/DefaultValueSizeGetter.h | 11 +- src/util/Exception.h | 10 +- src/util/ExceptionHandling.h | 35 ++- src/util/FsstCompressor.h | 19 +- src/util/Generator.h | 30 +- src/util/Generators.h | 28 +- src/util/InputRangeUtils.h | 4 +- src/util/Iterators.h | 69 +++-- src/util/JoinAlgorithms/FindUndefRanges.h | 35 ++- src/util/JoinAlgorithms/JoinAlgorithms.h | 64 ++-- src/util/LruCache.h | 8 +- src/util/MemorySize/MemorySize.h | 105 ++++--- src/util/MmapVector.h | 22 +- src/util/MmapVectorImpl.h | 4 +- src/util/NBitInteger.h | 4 +- ...DestructionDontThrowDuringStackUnwinding.h | 11 +- src/util/ParallelMultiwayMerge.h | 65 ++-- src/util/Parameters.h | 11 +- src/util/ProgramOptionsHelpers.h | 6 +- src/util/ProgressBar.h | 12 +- src/util/Random.h | 5 +- src/util/Serializer/SerializeArrayOrTuple.h | 8 +- src/util/Serializer/SerializeVector.h | 5 +- src/util/Serializer/Serializer.h | 27 +- src/util/Serializer/TripleSerializer.h | 60 ++-- src/util/StringUtils.h | 34 +-- src/util/Synchronized.h | 9 +- src/util/TaskQueue.h | 8 +- src/util/ThreadSafeQueue.h | 9 +- src/util/TimeTracer.h | 2 +- src/util/Timer.h | 6 +- src/util/TransparentFunctors.h | 12 +- src/util/TypeTraits.h | 20 +- src/util/UniqueCleanup.h | 7 +- src/util/Views.h | 72 +++-- src/util/antlr/ANTLRErrorHandling.h | 12 +- src/util/http/HttpServer.h | 28 +- src/util/http/HttpUtils.h | 76 ++--- src/util/json.h | 48 ++- src/util/stream_generator.h | 4 +- src/util/views/TakeUntilInclusiveView.h | 15 +- test/AsioHelpersTest.cpp | 3 +- test/BenchmarkMeasurementContainerTest.cpp | 3 +- test/ChunkedForLoopTest.cpp | 6 +- test/ConcurrentCacheTest.cpp | 3 +- test/ConfigManagerTest.cpp | 16 +- test/ConfigOptionProxyTest.cpp | 7 +- test/ConfigOptionTest.cpp | 8 +- test/ConstexprUtilsTest.cpp | 3 +- ...lterExpressionFromSparqlExpressionTest.cpp | 4 +- test/IdTableHelpersTest.cpp | 9 +- test/JsonUtilTest.cpp | 9 +- test/MessageSenderTest.cpp | 4 +- test/PrefilterExpressionTestHelpers.h | 8 +- test/QueryIdTest.cpp | 4 +- test/QueryPlannerTestHelpers.h | 21 +- test/RandomTest.cpp | 40 ++- test/RdfParserTest.cpp | 4 +- test/RelationalExpressionTest.cpp | 13 +- test/SparqlExpressionTest.cpp | 7 +- test/SparqlProtocolTest.cpp | 89 +++--- test/TypeTraitsTest.cpp | 4 +- test/backports/ConceptsTest.cpp | 24 +- .../VocabularyInMemoryBinSearchTest.cpp | 4 +- .../vocabulary/VocabularyInMemoryTest.cpp | 4 +- .../VocabularyInternalExternalTest.cpp | 4 +- .../index/vocabulary/VocabularyOnDiskTest.cpp | 4 +- test/parser/SparqlAntlrParserTestHelpers.h | 8 +- test/util/AsyncTestHelpers.h | 2 +- .../BenchmarkMeasurementContainerHelpers.cpp | 4 +- .../BenchmarkMeasurementContainerHelpers.h | 6 +- test/util/GTestHelpers.h | 17 +- test/util/IdTableHelpers.h | 6 +- test/util/ValidatorHelpers.cpp | 6 +- test/util/ValidatorHelpers.h | 12 +- 183 files changed, 2105 insertions(+), 2122 deletions(-) diff --git a/.clang-format b/.clang-format index bc7beb36a7..312950ad52 100644 --- a/.clang-format +++ b/.clang-format @@ -4,10 +4,40 @@ DerivePointerAlignment: false PointerAlignment: Left LineEnding: LF InsertNewlineAtEOF: true -RequiresClausePosition: SingleLine -IndentRequiresClause: false +RequiresClausePosition: OwnLine +IndentRequiresClause: true AttributeMacros: [CPP_member, CPP_auto_member, CPP_fun, CPP_auto_fun] # TODO Update to Clang-format-17 and then we can have much nicer CPP_... macros. -#Macros: -# - CPP_template_2(x)=template requires +Macros: + - CPP_template(x)=template requires + - CPP_template(x, y)=template requires + - CPP_template(x, y, z)=template requires + - CPP_template(x, y, z, a)=template requires + - CPP_template(a, b, c, d, e)=template requires + - CPP_template(a, b, c, d, e, f)=template requires + # + - CPP_template_def(x)=template requires + - CPP_template_def(x, y)=template requires + - CPP_template_def(x, y, z)=template requires + - CPP_template_def(x, y, z, a)=template requires + - CPP_template_def(a, b, c, d, e)=template requires + - CPP_template_def(a, b, c, d, e, f)=template requires + # + - CPP_variadic_template(x)=template requires + - CPP_variadic_template(x, y)=template requires + - CPP_variadic_template(x, y, z)=template requires + - CPP_variadic_template(x, y, z, a)=template requires + - CPP_variadic_template(a, b, c, d, e)=template requires + - CPP_variadic_template(a, b, c, d, e, f)=template requires + #- requires= + #- CPP_and=and + - CPP_template_2(a)=template requires + - CPP_template_2(a, b)=template requires + - CPP_template_2(a, b, c)=template requires + - CPP_template_2(a, b, c)=template requires + - CPP_template_2(a, b, c, d)=template requires + - CPP_template_2(a, b, c, d, e)=template requires + - CPP_template_2(a, b, c, d, e, f)=template requires + # + - CPP_ret(T)=T requires ... diff --git a/.github/workflows/format-check.yml b/.github/workflows/format-check.yml index 07412916bb..209e7ab43b 100644 --- a/.github/workflows/format-check.yml +++ b/.github/workflows/format-check.yml @@ -24,8 +24,8 @@ jobs: wget https://apt.llvm.org/llvm.sh sudo chmod +x llvm.sh sed 's/apt-key del/echo/' llvm.sh -iy - sudo ./llvm.sh 16 - sudo apt install -y clang-format-16 + sudo ./llvm.sh 19 + sudo apt install -y clang-format-19 - name: Run the format checker run: ${{github.workspace}}/misc/format-check.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 29ee828fa8..d2a7f6d6d3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,7 +10,7 @@ repos: # Uses a packaged version of clang-format from https://github.com/ssciwr/clang-format-wheel - repo: https://github.com/pre-commit/mirrors-clang-format - rev: 'v16.0.6' + rev: 'v19.1.7' hooks: - id: clang-format 'types_or': [ c++, c ] diff --git a/benchmark/JoinAlgorithmBenchmark.cpp b/benchmark/JoinAlgorithmBenchmark.cpp index 40ea305044..d952eb1f8b 100644 --- a/benchmark/JoinAlgorithmBenchmark.cpp +++ b/benchmark/JoinAlgorithmBenchmark.cpp @@ -66,19 +66,18 @@ namespace ad_benchmark { @brief Return true, iff, the given value is unchanged, when casting to type `Target` */ -CPP_template(typename Target, typename Source)( - requires ql::concepts::convertible_to< - Source, - Target>) static constexpr bool isValuePreservingCast(const Source& - source) { +CPP_template( + typename Target, + typename Source) (requires ql::concepts::convertible_to) +static constexpr bool isValuePreservingCast(const Source& source) { return static_cast(static_cast(source)) == source; } /* @brief Return biggest possible value for the given arithmetic type. */ -CPP_template(typename Type)(requires ad_utility::Arithmetic) - QL_CONSTEVAL Type getMaxValue() { +CPP_template(typename Type) (requires ad_utility::Arithmetic) +QL_CONSTEVAL Type getMaxValue() { return std::numeric_limits::max(); } @@ -371,8 +370,8 @@ enum struct GeneratedTableColumn : unsigned long { /* Convert the given enum value into the underlying type. */ -CPP_template(typename Enum)(requires std::is_enum_v) auto toUnderlying( - const Enum& e) { +CPP_template(typename Enum) (requires std::is_enum_v) +auto toUnderlying(const Enum& e) { return static_cast>(e); } @@ -416,12 +415,9 @@ struct IsGrowthFunction { @brief Calculates the smallest whole exponent $n$, so that $base^n$ is equal, or bigger, than the `startingPoint`. */ -CPP_template(typename T)( - requires ql::concepts::convertible_to< - T, - double>) static double calculateNextWholeExponent(const T& base, - const T& - startingPoint) { +CPP_template(typename T) (requires ql::concepts::convertible_to) +static double calculateNextWholeExponent(const T& base, + const T& startingPoint) { // This is a rather simple calculation: We calculate // $log_(base)(startingPoint)$ and round up. AD_CONTRACT_CHECK(isValuePreservingCast(startingPoint)); @@ -434,11 +430,10 @@ CPP_template(typename T)( @brief Generate a sorted, inclusive interval of exponents $base^x$, with $x$ always a natural number. */ -CPP_template(typename T)( - requires ad_utility::Arithmetic CPP_and - ql::concepts::convertible_to) static std:: - vector generateExponentInterval(T base, T inclusiveLowerBound, - T inclusiveUpperBound) { +CPP_template(typename T) (requires ad_utility::Arithmetic CPP_and + ql::concepts::convertible_to) +static std::vector generateExponentInterval(T base, T inclusiveLowerBound, + T inclusiveUpperBound) { std::vector elements{}; /* @@ -467,9 +462,9 @@ CPP_template(typename T)( @brief Generate a sorted,inclusive interval of all natural numbers inside `[inclusiveLowerBound, inclusiveUpperBound]`. */ -CPP_template(typename T)(requires ad_utility::Arithmetic) static std::vector< - T> generateNaturalNumberSequenceInterval(T inclusiveLowerBound, - T inclusiveUpperBound) { +CPP_template(typename T) (requires ad_utility::Arithmetic) +static std::vector generateNaturalNumberSequenceInterval( + T inclusiveLowerBound, T inclusiveUpperBound) { if constexpr (ql::concepts::floating_point) { inclusiveLowerBound = std::ceil(inclusiveLowerBound); inclusiveUpperBound = std::floor(inclusiveUpperBound); @@ -486,8 +481,9 @@ CPP_template(typename T)(requires ad_utility::Arithmetic) static std::vector< // Merge multiple sorted vectors into one sorted vector, where every element is // unique. -CPP_template(typename T)(requires ad_utility::Arithmetic) static std::vector< - T> mergeSortedVectors(const std::vector>& intervals) { +CPP_template(typename T) (requires ad_utility::Arithmetic) +static std::vector mergeSortedVectors( + const std::vector>& intervals) { std::vector mergedVector{}; // Merge. @@ -1652,10 +1648,10 @@ argument of the function and $x$ being $log_base(startingPoint)$ rounded up. CPP_template(typename ReturnType)(requires ql::concepts::convertible_to CPP_and ql::concepts::convertible_to) - // clang-format on - auto createDefaultGrowthLambda(const ReturnType& base, - const ReturnType& startingPoint, - std::vector prefixValues = {}) { +// clang-format on +auto createDefaultGrowthLambda(const ReturnType& base, + const ReturnType& startingPoint, + std::vector prefixValues = {}) { return [base, prefixValues = std::move(prefixValues), startingExponent{calculateNextWholeExponent(base, startingPoint)}]( const size_t& rowIdx) { @@ -2202,12 +2198,12 @@ class BmSmallerTableGrowsBiggerTableRemainsSameSize final given benchmarking table row? @param biggerTableNumRows Number of rows in the bigger table. */ - CPP_template(typename Function)(requires(growthFunction)) - ResultTable& makeSmallerTableGrowsAndBiggerTableSameSizeBenchmarkTable( - BenchmarkResults* results, const std::string& tableDescriptor, - const bool smallerTableSorted, const bool biggerTableSorted, - const Function& smallerTableNumRows, - const size_t biggerTableNumRows) const { + CPP_template(typename Function) (requires(growthFunction)) + ResultTable& makeSmallerTableGrowsAndBiggerTableSameSizeBenchmarkTable( + BenchmarkResults* results, const std::string& tableDescriptor, + const bool smallerTableSorted, const bool biggerTableSorted, + const Function& smallerTableNumRows, + const size_t biggerTableNumRows) const { // For creating a new random seed for every new row. RandomSeedGenerator seedGenerator{getConfigVariables().randomSeed()}; diff --git a/benchmark/infrastructure/Benchmark.h b/benchmark/infrastructure/Benchmark.h index d2be0afa4d..092365f462 100644 --- a/benchmark/infrastructure/Benchmark.h +++ b/benchmark/infrastructure/Benchmark.h @@ -93,9 +93,9 @@ class BenchmarkResults { * Most of the time a lambda, that calls the actual function to benchmark * with the needed parameters. */ - CPP_template(typename Function)(requires(ql::concepts::invocable)) - ResultEntry& addMeasurement(const std::string& descriptor, - const Function& functionToMeasure) { + CPP_template(typename Function) (requires(ql::concepts::invocable)) + ResultEntry& addMeasurement(const std::string& descriptor, + const Function& functionToMeasure) { return addEntryToContainerVector(singleMeasurements_, descriptor, functionToMeasure); } diff --git a/benchmark/infrastructure/BenchmarkMeasurementContainer.h b/benchmark/infrastructure/BenchmarkMeasurementContainer.h index ed65c3a56d..5c4b72ba8e 100644 --- a/benchmark/infrastructure/BenchmarkMeasurementContainer.h +++ b/benchmark/infrastructure/BenchmarkMeasurementContainer.h @@ -32,12 +32,10 @@ namespace ad_benchmark { @param functionToMeasure Must be a function, or callable. @param measurementSubjectName A description/name of what is being measured. */ -CPP_template(typename Function)(requires( - ql::concepts::invocable< - Function>)) static float measureTimeOfFunction(const Function& - functionToMeasure, - std::string_view - measurementSubjectIdentifier) { +CPP_template(typename Function) (requires(ql::concepts::invocable)) +static float measureTimeOfFunction( + const Function& functionToMeasure, + std::string_view measurementSubjectIdentifier) { AD_LOG_INFO << "Running measurement \"" << measurementSubjectIdentifier << "\" ..." << std::endl; @@ -95,8 +93,8 @@ class ResultEntry : public BenchmarkMetadataGetter { @param functionToMeasure The function, who's execution time will be measured and saved. */ - CPP_template(typename F)(requires(ql::concepts::invocable)) - ResultEntry(const std::string& descriptor, const F& functionToMeasure) + CPP_template(typename F) (requires(ql::concepts::invocable)) + ResultEntry(const std::string& descriptor, const F& functionToMeasure) : descriptor_{descriptor}, measuredTime_{measureTimeOfFunction(functionToMeasure, descriptor)} {} @@ -111,9 +109,9 @@ class ResultEntry : public BenchmarkMetadataGetter { @param functionToMeasure The function, who's execution time will be measured and saved. */ - CPP_template(typename F)(requires(ql::concepts::invocable)) - ResultEntry(const std::string& descriptor, - std::string_view descriptorForLog, const F& functionToMeasure) + CPP_template(typename F) (requires(ql::concepts::invocable)) + ResultEntry(const std::string& descriptor, std::string_view descriptorForLog, + const F& functionToMeasure) : descriptor_{descriptor}, measuredTime_{ measureTimeOfFunction(functionToMeasure, descriptorForLog)} {} @@ -199,11 +197,9 @@ class ResultTable : public BenchmarkMetadataGetter { Starts with `(0,0)`. @param functionToMeasure The function, which execution time will be measured. */ - CPP_template(typename Function)(requires( - ql::concepts::invocable< - Function>)) void addMeasurement(const size_t& row, - const size_t& column, - const Function& functionToMeasure) { + CPP_template(typename Function) (requires(ql::concepts::invocable)) + void addMeasurement(const size_t& row, const size_t& column, + const Function& functionToMeasure) { AD_CONTRACT_CHECK(row < numRows() && column < numColumns()); entries_.at(row).at(column) = measureTimeOfFunction( functionToMeasure, @@ -231,8 +227,8 @@ class ResultTable : public BenchmarkMetadataGetter { @param row, column Which table entry to read. Starts with `(0,0)`. */ - CPP_template(typename T)(requires ad_utility::SameAsAnyTypeIn) T - getEntry(const size_t row, const size_t column) const { + CPP_template(typename T) (requires ad_utility::SameAsAnyTypeIn) + T getEntry(const size_t row, const size_t column) const { AD_CONTRACT_CHECK(row < numRows() && column < numColumns()); static_assert(!ad_utility::isSimilar); @@ -331,9 +327,9 @@ class ResultGroup : public BenchmarkMetadataGetter { @param functionToMeasure The function, who's execution time will be measured and saved. */ - CPP_template(typename Function)(requires(ql::concepts::invocable)) - ResultEntry& addMeasurement(const std::string& descriptor, - const Function& functionToMeasure) { + CPP_template(typename Function) (requires(ql::concepts::invocable)) + ResultEntry& addMeasurement(const std::string& descriptor, + const Function& functionToMeasure) { resultEntries_.push_back(ad_utility::make_copyable_unique( descriptor, absl::StrCat(descriptor, " of group ", descriptor_), functionToMeasure)); diff --git a/benchmark/infrastructure/BenchmarkToJson.cpp b/benchmark/infrastructure/BenchmarkToJson.cpp index 63e5e3a8aa..20c6fac30f 100644 --- a/benchmark/infrastructure/BenchmarkToJson.cpp +++ b/benchmark/infrastructure/BenchmarkToJson.cpp @@ -30,12 +30,13 @@ provided translation function for the vector entries. @tparam TranslationFunction Has to be a function, that takes `VectorType` and returns a `nlohmann:json` object. */ -CPP_template(typename VectorType, typename TranslationFunction)( - requires ad_utility::InvocableWithExactReturnType< - TranslationFunction, nlohmann::ordered_json, - VectorType>) static nlohmann::json - transformIntoJsonArray(const std::vector& vec, - TranslationFunction translationFunction) { +CPP_template( + typename VectorType, + typename TranslationFunction) (requires ad_utility::InvocableWithExactReturnType< + TranslationFunction, nlohmann::ordered_json, VectorType>) +static nlohmann::json transformIntoJsonArray( + const std::vector& vec, + TranslationFunction translationFunction) { /* Without explicit instantiation, `nlohmann::nlohmann::ordered_json` is not guaranteed, to always interpret a `push_back` correctly. For instance, diff --git a/benchmark/util/ResultTableColumnOperations.h b/benchmark/util/ResultTableColumnOperations.h index bda8923dd7..c62467ecff 100644 --- a/benchmark/util/ResultTableColumnOperations.h +++ b/benchmark/util/ResultTableColumnOperations.h @@ -21,9 +21,9 @@ Column number together with the type of value, that can be found inside the column. Note, that **all** entries in the column must have the same type, because of `ResultTable::getEntry`. */ -CPP_template(typename Type)( - requires ad_utility::SameAsAnyTypeIn< - Type, ResultTable::EntryType>) struct ColumnNumWithType { +CPP_template( + typename Type) (requires ad_utility::SameAsAnyTypeIn) +struct ColumnNumWithType { using ColumnType = Type; const size_t columnNum_; }; @@ -31,14 +31,14 @@ CPP_template(typename Type)( // clang-format off CPP_variadic_template(typename ColumnReturnType, typename... ColumnInputTypes) (requires(sizeof...(ColumnInputTypes) > 0)) - // clang-format on - void generateColumnWithColumnInput( - ResultTable* const table, - QL_CONCEPT_OR_NOTHING( - ad_utility::InvocableWithSimilarReturnType< - ColumnReturnType, const ColumnInputTypes&...>) auto&& generator, - const ColumnNumWithType& columnToPutResultIn, - const ColumnNumWithType&... inputColumns) { +// clang-format on +void generateColumnWithColumnInput( + ResultTable* const table, + QL_CONCEPT_OR_NOTHING( + ad_utility::InvocableWithSimilarReturnType< + ColumnReturnType, const ColumnInputTypes&...>) auto&& generator, + const ColumnNumWithType& columnToPutResultIn, + const ColumnNumWithType&... inputColumns) { // Using a column more than once is the sign of an error. std::array allColumnNums{ {inputColumns.columnNum_...}}; @@ -63,11 +63,11 @@ CPP_variadic_template(typename ColumnReturnType, typename... ColumnInputTypes) (requires((ql::concepts::same_as> && ...) && sizeof...(ColumnInputTypes) > 1)) - // clang-format on - void sumUpColumns( - ResultTable* const table, - const ColumnNumWithType& columnToPutResultIn, - const ColumnInputTypes&... columnsToSumUp) { +// clang-format on +void sumUpColumns( + ResultTable* const table, + const ColumnNumWithType& columnToPutResultIn, + const ColumnInputTypes&... columnsToSumUp) { // We can simply pass this to `generateColumnWithColumnInput`. generateColumnWithColumnInput( table, diff --git a/misc/format-check.sh b/misc/format-check.sh index afa09d82f2..900c6ed81a 100755 --- a/misc/format-check.sh +++ b/misc/format-check.sh @@ -9,7 +9,7 @@ done /dev/null + clang-format-19 -output-replacements-xml $source | grep " /dev/null HAS_WRONG_FILES=$? if [ $HAS_WRONG_FILES -ne 1 ] ; then # Print an error and exit @@ -17,7 +17,7 @@ for source in "${SOURCE_FILES[@]}" ;do printf "The source file \x1b[m$source\x1b[31m does not match the code style\n" printf "Use clang-format with the .clang-format provided in the QLever\n" printf "repository's root to ensure all code files are formatted " - printf "properly. We currently use clang-format 16\n" + printf "properly. We currently use clang-format 17\n" printf "(See '.github/workflows/format-check.yml' for instructions on how to install it.\n" printf "\x1b[m" ERROR=1 diff --git a/src/backports/StartsWithAndEndsWith.h b/src/backports/StartsWithAndEndsWith.h index a734b47427..70025689a9 100644 --- a/src/backports/StartsWithAndEndsWith.h +++ b/src/backports/StartsWithAndEndsWith.h @@ -22,57 +22,45 @@ namespace ql { // string/string_view as the first parameter. // Overload 1: Does a `string_view` start with a `string_view`. -CPP_template(typename CharT, typename Traits, typename Other)( - requires ql::concepts::convertible_to< - const Other&, - std::basic_string_view< - CharT, Traits>>) constexpr bool starts_with(const std:: - basic_string_view< - CharT, Traits>& - sv, - const Other& - prefixIn) noexcept { +CPP_template( + typename CharT, typename Traits, + typename Other) (requires ql::concepts::convertible_to< + const Other&, std::basic_string_view>) +constexpr bool starts_with(const std::basic_string_view& sv, + const Other& prefixIn) noexcept { std::basic_string_view prefix(prefixIn); return sv.size() >= prefix.size() && Traits::compare(sv.data(), prefix.data(), prefix.size()) == 0; } // Overload 2: Does a `string_view` start with a `char`. -CPP_template(typename CharT, typename Traits, typename Other)( - requires ql::concepts::convertible_to< - const Other&, - CharT>) constexpr bool starts_with(std::basic_string_view - sv, - const Other& prefixIn) noexcept { +CPP_template( + typename CharT, typename Traits, + typename Other) (requires ql::concepts::convertible_to) +constexpr bool starts_with(std::basic_string_view sv, + const Other& prefixIn) noexcept { CharT prefix(prefixIn); return !sv.empty() && Traits::eq(sv.front(), prefix); } // Overload 3: Does a `string` start with a `string_view`. -CPP_template(typename CharT, typename Traits, typename Allocator, - typename Other)( - requires ql::concepts::convertible_to< - const Other&, - std::basic_string_view< - CharT, Traits>>) constexpr bool starts_with(const std:: - basic_string< - CharT, Traits, - Allocator>& str, - const Other& - prefix) noexcept { +CPP_template( + typename CharT, typename Traits, typename Allocator, + typename Other) (requires ql::concepts::convertible_to< + const Other&, std::basic_string_view>) +constexpr bool starts_with( + const std::basic_string& str, + const Other& prefix) noexcept { return starts_with(std::basic_string_view(str), prefix); } // Overload 3: Does a `string` start with a `char`. -CPP_template(typename CharT, typename Traits, typename Allocator, - typename Other)( - requires ql::concepts::convertible_to< - const Other&, - CharT>) constexpr bool starts_with(const std::basic_string& - str, - const Other& prefix) noexcept { +CPP_template( + typename CharT, typename Traits, typename Allocator, + typename Other) (requires ql::concepts::convertible_to) +constexpr bool starts_with( + const std::basic_string& str, + const Other& prefix) noexcept { return starts_with(std::basic_string_view(str), prefix); } @@ -81,16 +69,12 @@ CPP_template(typename CharT, typename Traits, typename Allocator, // string/string_view as the first parameter. // Overload 1: Does a `string_view` end with a `string_view`. -CPP_template(typename CharT, typename Traits, typename Other)( - requires ql::concepts::convertible_to< - const Other&, - std::basic_string_view< - CharT, Traits>>) constexpr bool ends_with(const std:: - basic_string_view< - CharT, Traits>& - sv, - const Other& - suffixIn) noexcept { +CPP_template( + typename CharT, typename Traits, + typename Other) (requires ql::concepts::convertible_to< + const Other&, std::basic_string_view>) +constexpr bool ends_with(const std::basic_string_view& sv, + const Other& suffixIn) noexcept { std::basic_string_view suffix(suffixIn); return sv.size() >= suffix.size() && Traits::compare(sv.data() + (sv.size() - suffix.size()), suffix.data(), @@ -98,39 +82,31 @@ CPP_template(typename CharT, typename Traits, typename Other)( } // Overload 2: Does a `string_view` end with a `char`. -CPP_template(typename CharT, typename Traits, typename Other)( - requires ql::concepts::convertible_to< - const Other&, - CharT>) constexpr bool ends_with(std::basic_string_view - sv, - const Other& suffixIn) noexcept { +CPP_template( + typename CharT, typename Traits, + typename Other) (requires ql::concepts::convertible_to) +constexpr bool ends_with(std::basic_string_view sv, + const Other& suffixIn) noexcept { CharT suffix(suffixIn); return !sv.empty() && Traits::eq(sv.back(), suffix); } // Overload 3: Does a `string` end with a `string_view`. -CPP_template(typename CharT, typename Traits, typename Allocator, - typename Other)( - requires ql::concepts::convertible_to< - const Other&, - std::basic_string_view< - CharT, - Traits>>) constexpr bool ends_with(const std:: - basic_string& str, - const Other& suffix) noexcept { +CPP_template( + typename CharT, typename Traits, typename Allocator, + typename Other) (requires ql::concepts::convertible_to< + const Other&, std::basic_string_view>) +constexpr bool ends_with(const std::basic_string& str, + const Other& suffix) noexcept { return ends_with(std::basic_string_view(str), suffix); } // Overload 4: Does a `string` end with a `char`. -CPP_template(typename CharT, typename Traits, typename Allocator, - typename Other)( - requires ql::concepts::convertible_to< - const Other&, - CharT>) constexpr bool ends_with(const std::basic_string& - str, - const Other& suffix) noexcept { +CPP_template( + typename CharT, typename Traits, typename Allocator, + typename Other) (requires ql::concepts::convertible_to) +constexpr bool ends_with(const std::basic_string& str, + const Other& suffix) noexcept { return ends_with(std::basic_string_view(str), suffix); } diff --git a/src/backports/iterator.h b/src/backports/iterator.h index 0f1db4097f..247e84563b 100644 --- a/src/backports/iterator.h +++ b/src/backports/iterator.h @@ -34,8 +34,8 @@ inline constexpr default_sentinel_t default_sentinel{}; // A backport of `std::move_sentinel` for C++17. It wraps an iterator or // sentinel type and can be compared with a compatible `ql::move_iterator`. -CPP_template(typename Sent)( - requires ql::concepts::semiregular) class move_sentinel { +CPP_template(typename Sent) (requires ql::concepts::semiregular) +class move_sentinel { public: // Default constructor constexpr move_sentinel() noexcept( @@ -48,20 +48,16 @@ CPP_template(typename Sent)( : sent_(std::move(s)) {} // Converting constructor for convertible underlying types. - CPP_template_2(typename S2)( - requires ql::concepts::convertible_to< - const S2&, - Sent>) constexpr move_sentinel(const move_sentinel& - s) noexcept(std:: - is_nothrow_constructible_v< - Sent, - const S2&>) + CPP_template_2( + typename S2)(requires ql::concepts::convertible_to) + constexpr move_sentinel(const move_sentinel& s) noexcept( + std::is_nothrow_constructible_v) : sent_(s.base()) {} // Converting assignment for convertible underlying types. - CPP_template_2(typename S2)(requires ql::concepts::assignable_from< - Sent&, const S2&>) constexpr move_sentinel& - operator=(const move_sentinel& s) noexcept( + CPP_template_2( + typename S2)(requires ql::concepts::assignable_from) + constexpr move_sentinel& operator=(const move_sentinel& s) noexcept( std::is_nothrow_assignable_v) { sent_ = s.base(); return *this; @@ -75,30 +71,26 @@ CPP_template(typename Sent)( // Compare with a compatible iterator (typically obtained via // `ql::make_move_iterator`. - CPP_template_2(typename It)( - requires ql::concepts::sentinel_for) friend bool - operator==(const move_iterator it, move_sentinel sent) { + CPP_template_2(typename It)(requires ql::concepts::sentinel_for) + friend bool operator==(const move_iterator it, move_sentinel sent) { return it.base() == sent.base(); } // Operator != (details same as for `operator==` above). - CPP_template_2(typename It)( - requires ql::concepts::sentinel_for) friend bool - operator!=(const move_iterator it, move_sentinel sent) { + CPP_template_2(typename It)(requires ql::concepts::sentinel_for) + friend bool operator!=(const move_iterator it, move_sentinel sent) { return it.base() != sent.base(); } // The same operators as above, but with the argument order switched (sentinel // first). They are required by the C++17 mode of `range-v3`. - CPP_template_2(typename It)( - requires ql::concepts::sentinel_for) friend bool - operator==(move_sentinel sent, const move_iterator it) { + CPP_template_2(typename It)(requires ql::concepts::sentinel_for) + friend bool operator==(move_sentinel sent, const move_iterator it) { return it == sent; } - CPP_template_2(typename It)( - requires ql::concepts::sentinel_for) friend bool - operator!=(move_sentinel sent, const move_iterator it) { + CPP_template_2(typename It)(requires ql::concepts::sentinel_for) + friend bool operator!=(move_sentinel sent, const move_iterator it) { return it != sent; } diff --git a/src/backports/shift.h b/src/backports/shift.h index 91cf1f60ff..30a8fab0cb 100644 --- a/src/backports/shift.h +++ b/src/backports/shift.h @@ -28,10 +28,11 @@ namespace ql { // Otherwise, for every integer i in [0, last - first - n), moves the element // at position first + n + i to position first + i. /// -CPP_template(typename ForwardIt)( - requires ql::concepts::forward_iterator) constexpr ForwardIt - shift_left(ForwardIt first, ForwardIt last, - typename std::iterator_traits::difference_type n) { +CPP_template( + typename ForwardIt) (requires ql::concepts::forward_iterator) +constexpr ForwardIt shift_left( + ForwardIt first, ForwardIt last, + typename std::iterator_traits::difference_type n) { assert(n >= 0); if (n == 0) { return first; @@ -52,10 +53,11 @@ CPP_template(typename ForwardIt)( // Otherwise, for every integer i in [0, last - first - n), moves the element // at position first + i to position first + n + i. /// -CPP_template(typename ForwardIt)( - requires ql::concepts::forward_iterator) constexpr ForwardIt - shift_right(ForwardIt first, ForwardIt last, - typename std::iterator_traits::difference_type n) { +CPP_template( + typename ForwardIt) (requires ql::concepts::forward_iterator) +constexpr ForwardIt shift_right( + ForwardIt first, ForwardIt last, + typename std::iterator_traits::difference_type n) { assert(n >= 0); if (n == 0 || n >= std::distance(first, last)) { return last; diff --git a/src/engine/AddCombinedRowToTable.h b/src/engine/AddCombinedRowToTable.h index e7a4fc2e4f..5dfe738db1 100644 --- a/src/engine/AddCombinedRowToTable.h +++ b/src/engine/AddCombinedRowToTable.h @@ -155,10 +155,9 @@ class AddCombinedRowToIdTable { // Same as calling `addRow` for each element in the Cartesian product of // `rowIndicesA` and `rowIndicesB` with an optimization for the special case // that the `resultTable` has zero columns. - CPP_template(typename R1, typename R2)( - requires sizedRangeOfUnsigned CPP_and - sizedRangeOfUnsigned) void addRows(const R1& rowIndicesA, - const R2& rowIndicesB) { + CPP_template(typename R1, typename R2) ( + requires sizedRangeOfUnsigned CPP_and sizedRangeOfUnsigned) + void addRows(const R1& rowIndicesA, const R2& rowIndicesB) { size_t total = ql::ranges::size(rowIndicesA) * ql::ranges::size(rowIndicesB); if (resultTable_.numColumns() == 0) { diff --git a/src/engine/CallFixedSize.h b/src/engine/CallFixedSize.h index 28e662f8be..bc767fdb5b 100644 --- a/src/engine/CallFixedSize.h +++ b/src/engine/CallFixedSize.h @@ -56,10 +56,10 @@ namespace detail { // Call the `lambda` when the correct compile-time `Int`s are given as a // `std::integer_sequence`. -CPP_variadic_template(typename Int, Int... Is, typename F, typename... Args)( - requires ql::concepts::integral< - Int>) auto applyOnIntegerSequence(ad_utility::ValueSequence, - F&& lambda, Args&&... args) { +CPP_variadic_template(typename Int, Int... Is, typename F, + typename... Args)(requires ql::concepts::integral) +auto applyOnIntegerSequence(ad_utility::ValueSequence, F&& lambda, + Args&&... args) { return lambda.template operator()(AD_FWD(args)...); }; @@ -72,10 +72,9 @@ static constexpr std::array DummyArray{}; // J,...)(args)` where `I, J, ...` are the elements in the `array`. Requires // that each element in the `array` is `<= maxValue`. CPP_variadic_template(int maxValue, size_t NumValues, typename Int, typename F, - typename... Args)( - requires(ql::concepts::integral< - Int>)) auto callLambdaForIntArray(std::array array, - F&& lambda, Args&&... args) { + typename... Args)(requires(ql::concepts::integral)) +auto callLambdaForIntArray(std::array array, F&& lambda, + Args&&... args) { AD_CONTRACT_CHECK( ql::ranges::all_of(array, [](auto el) { return el <= maxValue; })); auto apply = [&](auto integerSequence) { @@ -130,9 +129,8 @@ CPP_variadic_template(int maxValue, size_t NumValues, typename Int, typename F, // Overload for a single int. CPP_variadic_template(int maxValue, typename Int, typename F, - typename... Args)(requires( - ql::concepts::integral)) auto callLambdaForIntArray(Int i, F&& lambda, - Args&&... args) { + typename... Args)(requires(ql::concepts::integral)) +auto callLambdaForIntArray(Int i, F&& lambda, Args&&... args) { return callLambdaForIntArray(std::array{i}, AD_FWD(lambda), AD_FWD(args)...); } @@ -149,10 +147,9 @@ constexpr int mapToZeroIfTooLarge(int x, int maxValue) { // `mapToZeroIfTooLarge`. CPP_variadic_template(int MaxValue = DEFAULT_MAX_NUM_COLUMNS_STATIC_ID_TABLE, size_t NumIntegers, typename Int, typename F, - typename... Args)( - requires std::is_integral_v) decltype(auto) - callFixedSize(std::array ints, F&& functor, - Args&&... args) { + typename... Args)(requires std::is_integral_v) +decltype(auto) callFixedSize(std::array ints, F&& functor, + Args&&... args) { static_assert(NumIntegers > 0); // TODO Use `std::bind_back` auto p = [](int i) { return detail::mapToZeroIfTooLarge(i, MaxValue); }; @@ -168,9 +165,9 @@ CPP_variadic_template(int MaxValue = DEFAULT_MAX_NUM_COLUMNS_STATIC_ID_TABLE, // Overload for a single integer. CPP_variadic_template(int MaxValue = DEFAULT_MAX_NUM_COLUMNS_STATIC_ID_TABLE, - typename Int, typename F, typename... Args)( - requires std::is_integral_v) decltype(auto) - callFixedSize(Int i, F&& functor, Args&&... args) { + typename Int, typename F, + typename... Args)(requires std::is_integral_v) +decltype(auto) callFixedSize(Int i, F&& functor, Args&&... args) { return callFixedSize(std::array{i}, AD_FWD(functor), AD_FWD(args)...); } @@ -180,19 +177,18 @@ CPP_variadic_template(int MaxValue = DEFAULT_MAX_NUM_COLUMNS_STATIC_ID_TABLE, // as ValueIdentity objects to the functor rather than as template parameters. CPP_variadic_template(int MaxValue = DEFAULT_MAX_NUM_COLUMNS_STATIC_ID_TABLE, size_t NumIntegers, typename Int, typename F, - typename... Args)( - requires std::is_integral_v) decltype(auto) - callFixedSizeVi(std::array ints, F&& functor, - Args&&... args) { + typename... Args)(requires std::is_integral_v) +decltype(auto) callFixedSizeVi(std::array ints, F&& functor, + Args&&... args) { return callFixedSize(ints, ApplyAsValueIdentity{AD_FWD(functor)}, AD_FWD(args)...); } // Overload for a single integer. CPP_variadic_template(int MaxValue = DEFAULT_MAX_NUM_COLUMNS_STATIC_ID_TABLE, - typename Int, typename F, typename... Args)( - requires std::is_integral_v) decltype(auto) - callFixedSizeVi(Int i, F&& functor, Args&&... args) { + typename Int, typename F, + typename... Args)(requires std::is_integral_v) +decltype(auto) callFixedSizeVi(Int i, F&& functor, Args&&... args) { return callFixedSizeVi(std::array{i}, AD_FWD(functor), AD_FWD(args)...); } diff --git a/src/engine/CartesianProductJoin.cpp b/src/engine/CartesianProductJoin.cpp index d705f51331..71f15a20b7 100644 --- a/src/engine/CartesianProductJoin.cpp +++ b/src/engine/CartesianProductJoin.cpp @@ -195,8 +195,9 @@ VariableToColumnMap CartesianProductJoin::computeVariableToColumnMap() const { // _____________________________________________________________________________ CPP_template_def(typename R)(requires ql::ranges::random_access_range) - IdTable CartesianProductJoin::writeAllColumns( - R idTables, size_t offset, size_t limit, size_t lastTableOffset) const { +IdTable CartesianProductJoin::writeAllColumns(R idTables, size_t offset, + size_t limit, + size_t lastTableOffset) const { AD_CORRECTNESS_CHECK(offset >= lastTableOffset); IdTable result{getResultWidth(), getExecutionContext()->getAllocator()}; // TODO Find a solution to cheaply handle the case, that only a @@ -317,11 +318,10 @@ CartesianProductJoin::calculateSubResults(bool requestLaziness) { } // _____________________________________________________________________________ -CPP_template_def(typename R)(requires ql::ranges::range) Result::LazyResult - CartesianProductJoin::produceTablesLazily(LocalVocab mergedVocab, - R idTables, size_t offset, - size_t limit, - size_t lastTableOffset) const { +CPP_template_def(typename R)(requires ql::ranges::range) +Result::LazyResult CartesianProductJoin::produceTablesLazily( + LocalVocab mergedVocab, R idTables, size_t offset, size_t limit, + size_t lastTableOffset) const { using Lc = Result::IdTableLoopControl; auto get = [self = this, mergedVocab = std::move(mergedVocab), idTables = std::move(idTables), offset, limit, diff --git a/src/engine/CartesianProductJoin.h b/src/engine/CartesianProductJoin.h index 07e9c09ba3..4058d22f3e 100644 --- a/src/engine/CartesianProductJoin.h +++ b/src/engine/CartesianProductJoin.h @@ -105,9 +105,9 @@ class CartesianProductJoin : public Operation { // rows to write at most. `lastTableOffset` is the offset of the last table, // to account for cases where the last table does not cover the whole result // and so index 0 of a table does not correspond to row 0 of the result. - CPP_template(typename R)(requires ql::ranges::random_access_range) IdTable - writeAllColumns(R idTables, size_t offset, size_t limit, - size_t lastTableOffset = 0) const; + CPP_template(typename R) (requires ql::ranges::random_access_range) + IdTable writeAllColumns(R idTables, size_t offset, size_t limit, + size_t lastTableOffset = 0) const; // Calculate the subresults of the children and store them into a vector. If // the rightmost child can produce a lazy result, it will be stored outside of @@ -125,9 +125,10 @@ class CartesianProductJoin : public Operation { // `lastTableOffset` is the offset of the last table in the range. This is // used to handle `IdTable`s yielded by generators where the range of indices // they represent do not cover the whole result. - CPP_template(typename R)(requires ql::ranges::range) Result::LazyResult - produceTablesLazily(LocalVocab mergedVocab, R idTables, size_t offset, - size_t limit, size_t lastTableOffset = 0) const; + CPP_template(typename R) (requires ql::ranges::range) + Result::LazyResult produceTablesLazily(LocalVocab mergedVocab, R idTables, + size_t offset, size_t limit, + size_t lastTableOffset = 0) const; // Similar to `produceTablesLazily` but can handle a single lazy result. Result::LazyResult createLazyConsumer( diff --git a/src/engine/ExportQueryExecutionTrees.cpp b/src/engine/ExportQueryExecutionTrees.cpp index fd457e0f15..8e7823db36 100644 --- a/src/engine/ExportQueryExecutionTrees.cpp +++ b/src/engine/ExportQueryExecutionTrees.cpp @@ -926,9 +926,9 @@ STREAMABLE_GENERATOR_TYPE ExportQueryExecutionTrees::selectQueryResultToStream( const auto& val = selectedColumnIndices[j].value(); Id id = pair.idTable()(i, val.columnIndex_); auto optionalStringAndType = - idToStringAndType( - qet.getQec()->getIndex(), id, pair.localVocab(), - escapeFunction); + idToStringAndType < format == + MediaType::csv > (qet.getQec()->getIndex(), id, pair.localVocab(), + escapeFunction); if (optionalStringAndType.has_value()) [[likely]] { STREAMABLE_YIELD(optionalStringAndType.value().first); } diff --git a/src/engine/Filter.cpp b/src/engine/Filter.cpp index 531a6d72db..cf726e4483 100644 --- a/src/engine/Filter.cpp +++ b/src/engine/Filter.cpp @@ -114,8 +114,8 @@ Result Filter::computeResult(bool requestLaziness) { // _____________________________________________________________________________ CPP_template_def(typename Table)(requires ad_utility::SimilarTo) - IdTable Filter::filterIdTable(std::vector sortedBy, - Table&& idTable) const { +IdTable Filter::filterIdTable(std::vector sortedBy, + Table&& idTable) const { size_t width = idTable.numColumns(); IdTable result{width, getExecutionContext()->getAllocator()}; @@ -128,10 +128,10 @@ CPP_template_def(typename Table)(requires ad_utility::SimilarTo) } // _____________________________________________________________________________ -CPP_template_def(int WIDTH, typename Table)( - requires ad_utility::SimilarTo) void Filter:: - computeFilterImpl(IdTable& dynamicResultTable, Table&& inputTable, - std::vector sortedBy) const { +CPP_template_def(int WIDTH, + typename Table)(requires ad_utility::SimilarTo) +void Filter::computeFilterImpl(IdTable& dynamicResultTable, Table&& inputTable, + std::vector sortedBy) const { LocalVocab dummyLocalVocab{}; AD_CONTRACT_CHECK(inputTable.numColumns() == WIDTH || WIDTH == 0); IdTableStatic resultTable = diff --git a/src/engine/Filter.h b/src/engine/Filter.h index b628632793..3649056dd9 100644 --- a/src/engine/Filter.h +++ b/src/engine/Filter.h @@ -73,17 +73,15 @@ class Filter : public Operation { Result computeResult(bool requestLaziness) override; // Perform the actual filter operation of the data provided. - CPP_template(int WIDTH, typename Table)( - requires ad_utility::SimilarTo< - Table, IdTable>) void computeFilterImpl(IdTable& dynamicResultTable, - Table&& input, - std::vector - sortedBy) const; + CPP_template(int WIDTH, + typename Table) (requires ad_utility::SimilarTo) + void computeFilterImpl(IdTable& dynamicResultTable, Table&& input, + std::vector sortedBy) const; // Run `computeFilterImpl` on the provided IdTable - CPP_template(typename Table)( - requires ad_utility::SimilarTo) IdTable - filterIdTable(std::vector sortedBy, Table&& idTable) const; + CPP_template(typename Table) (requires ad_utility::SimilarTo) + IdTable filterIdTable(std::vector sortedBy, + Table&& idTable) const; }; #endif // QLEVER_SRC_ENGINE_FILTER_H diff --git a/src/engine/GraphStoreProtocol.h b/src/engine/GraphStoreProtocol.h index d082dd4cef..a8e89d8cf0 100644 --- a/src/engine/GraphStoreProtocol.h +++ b/src/engine/GraphStoreProtocol.h @@ -21,9 +21,9 @@ class GraphStoreProtocol { private: // Extract the mediatype from a request. - CPP_template_2(typename RequestT)(requires ad_utility::httpUtils::HttpRequest< - RequestT>) static ad_utility::MediaType - extractMediatype(const RequestT& rawRequest) { + CPP_template_2( + typename RequestT)(requires ad_utility::httpUtils::HttpRequest) + static ad_utility::MediaType extractMediatype(const RequestT& rawRequest) { using namespace boost::beast::http; std::string_view contentTypeString; @@ -97,10 +97,11 @@ class GraphStoreProtocol { // Transform a SPARQL Graph Store Protocol POST to an equivalent ParsedQuery // which is an SPARQL Update. - CPP_template_2(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) static ParsedQuery - transformPost(const RequestT& rawRequest, const GraphOrDefault& graph, - const Index& index) { + CPP_template_2( + typename RequestT)(requires ad_utility::httpUtils::HttpRequest) + static ParsedQuery transformPost(const RequestT& rawRequest, + const GraphOrDefault& graph, + const Index& index) { throwIfRequestBodyEmpty(rawRequest); auto triples = parseTriples(rawRequest.body(), extractMediatype(rawRequest)); @@ -119,10 +120,11 @@ class GraphStoreProtocol { // `TSOP` (`POST` backwards) does a `DELETE DATA` of the payload. It is an // extension to the Graph Store Protocol. - CPP_template_2(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) static ParsedQuery - transformTsop(const RequestT& rawRequest, const GraphOrDefault& graph, - const Index& index) { + CPP_template_2( + typename RequestT)(requires ad_utility::httpUtils::HttpRequest) + static ParsedQuery transformTsop(const RequestT& rawRequest, + const GraphOrDefault& graph, + const Index& index) { throwIfRequestBodyEmpty(rawRequest); auto triples = parseTriples(rawRequest.body(), extractMediatype(rawRequest)); @@ -143,11 +145,11 @@ class GraphStoreProtocol { // Transform a SPARQL Graph Store Protocol PUT to equivalent ParsedQueries // which are SPARQL Updates. - CPP_template_2(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) static std:: - vector transformPut(const RequestT& rawRequest, - const GraphOrDefault& graph, - const Index& index) { + CPP_template_2( + typename RequestT)(requires ad_utility::httpUtils::HttpRequest) + static std::vector transformPut(const RequestT& rawRequest, + const GraphOrDefault& graph, + const Index& index) { // TODO: The response codes are not conform to the specs. "If new RDF graph // content is created", then the status must be `201 Created`. "If // existing graph content is modified", then the status must be `200 OK` @@ -194,12 +196,11 @@ class GraphStoreProtocol { // Every Graph Store Protocol request has equivalent SPARQL Query or Update. // Transform the Graph Store Protocol request into it's equivalent Query or // Update. - CPP_template_2(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) static std:: - vector transformGraphStoreProtocol( - ad_utility::url_parser::sparqlOperation::GraphStoreOperation - operation, - const RequestT& rawRequest, const Index& index) { + CPP_template_2( + typename RequestT)(requires ad_utility::httpUtils::HttpRequest) + static std::vector transformGraphStoreProtocol( + ad_utility::url_parser::sparqlOperation::GraphStoreOperation operation, + const RequestT& rawRequest, const Index& index) { ad_utility::url_parser::ParsedUrl parsedUrl = ad_utility::url_parser::parseRequestTarget(rawRequest.target()); using enum boost::beast::http::verb; diff --git a/src/engine/GroupByHashMapOptimization.h b/src/engine/GroupByHashMapOptimization.h index 9dc534b5fc..d9f0697267 100644 --- a/src/engine/GroupByHashMapOptimization.h +++ b/src/engine/GroupByHashMapOptimization.h @@ -18,10 +18,8 @@ // set error flag. static constexpr auto valueAdder = []() { auto numericValueAdder = [](auto value, double& sum, - [[maybe_unused]] const bool& error) - -> CPP_ret(void)(requires std::is_arithmetic_v) { - sum += static_cast(value); - }; + [[maybe_unused]] const bool& error) -> CPP_ret(void)(requires std::is_arithmetic_v) + { sum += static_cast(value); }; auto nonNumericValueAdder = [](sparqlExpression::detail::NotNumeric, [[maybe_unused]] const double& sum, bool& error) { error = true; }; diff --git a/src/engine/Join.cpp b/src/engine/Join.cpp index a6698508f0..a0275732ba 100644 --- a/src/engine/Join.cpp +++ b/src/engine/Join.cpp @@ -387,13 +387,13 @@ void Join::join(const IdTable& a, const IdTable& b, IdTable* result) const { } // _____________________________________________________________________________ -CPP_template_def(typename ActionT)( - requires ad_utility::InvocableWithExactReturnType< - ActionT, Result::IdTableVocabPair, - std::function>) - Result Join::createResult( - bool requestedLaziness, ActionT action, - std::optional> permutation) const { +CPP_template_def( + typename ActionT)(requires ad_utility::InvocableWithExactReturnType< + ActionT, Result::IdTableVocabPair, + std::function>) +Result Join::createResult( + bool requestedLaziness, ActionT action, + std::optional> permutation) const { if (requestedLaziness) { return {runLazyJoinAndConvertToGenerator(std::move(action), std::move(permutation)), diff --git a/src/engine/Join.h b/src/engine/Join.h index 743611f98e..8300361cb1 100644 --- a/src/engine/Join.h +++ b/src/engine/Join.h @@ -104,12 +104,12 @@ class Join : public Operation { // `action` is a lambda that can be used to send partial chunks to a consumer // in addition to returning the remaining result. If laziness is not required // it is a no-op. - CPP_template(typename ActionT)( - requires ad_utility::InvocableWithExactReturnType< - ActionT, Result::IdTableVocabPair, - std::function>) Result - createResult(bool requestedLaziness, ActionT action, - OptionalPermutation permutation = {}) const; + CPP_template( + typename ActionT) (requires ad_utility::InvocableWithExactReturnType< + ActionT, Result::IdTableVocabPair, + std::function>) + Result createResult(bool requestedLaziness, ActionT action, + OptionalPermutation permutation = {}) const; // Fallback implementation of a join that is used when at least one of the two // inputs is not fully materialized. This represents the general case where we diff --git a/src/engine/JoinHelpers.h b/src/engine/JoinHelpers.h index 7387b6f4dd..c972a963d3 100644 --- a/src/engine/JoinHelpers.h +++ b/src/engine/JoinHelpers.h @@ -44,10 +44,10 @@ using LazyInputView = InputRangeTypeErased>; // Convert a `generator` to a `generator` for // more efficient access in the join columns below and apply the given // permutation to each table. -CPP_template(typename Input)( - requires SameAsAny) - LazyInputView - convertGenerator(Input gen, OptionalPermutation permutation = {}) { +CPP_template( + typename Input) (requires SameAsAny) +LazyInputView convertGenerator(Input gen, + OptionalPermutation permutation = {}) { auto transformer = [permutation = std::move(permutation)](auto& element) { auto& [table, localVocab] = element; applyPermutation(table, permutation); @@ -90,12 +90,12 @@ inline std::variant resultToView( // being passed to the `AddCombinedRowToIdTable` so that the partial results // can be yielded during execution. This is achieved by spawning a separate // thread. -CPP_template_2(typename ActionT)( - requires ad_utility::InvocableWithExactReturnType< - ActionT, Result::IdTableVocabPair, - std::function>) Result::LazyResult - runLazyJoinAndConvertToGenerator(ActionT runLazyJoin, - OptionalPermutation permutation) { +CPP_template_2( + typename ActionT)(requires ad_utility::InvocableWithExactReturnType< + ActionT, Result::IdTableVocabPair, + std::function>) +Result::LazyResult runLazyJoinAndConvertToGenerator( + ActionT runLazyJoin, OptionalPermutation permutation) { return generatorFromActionWithCallback( [runLazyJoin = std::move(runLazyJoin), permutation = std::move(permutation)]( diff --git a/src/engine/LocalVocab.h b/src/engine/LocalVocab.h index 2a5895aa60..cbf0f16ec5 100644 --- a/src/engine/LocalVocab.h +++ b/src/engine/LocalVocab.h @@ -117,8 +117,8 @@ class LocalVocab { // to this local vocab. The purpose is to keep all the contained // `LocalVocabEntry`s alive as long as this `LocalVocab` is alive. The // primary set of this `LocalVocab` remains unchanged. - CPP_template(typename R)(requires ql::ranges::range) void mergeWith( - const R& vocabs) { + CPP_template(typename R) (requires ql::ranges::range) + void mergeWith(const R& vocabs) { using ql::views::filter; auto addWordSet = [this](const std::shared_ptr& set) { if (set == primaryWordSet_) { diff --git a/src/engine/QueryPlanner.cpp b/src/engine/QueryPlanner.cpp index b336bfacfb..519b51d034 100644 --- a/src/engine/QueryPlanner.cpp +++ b/src/engine/QueryPlanner.cpp @@ -612,9 +612,9 @@ constexpr auto rewriteSingle = CPP_template_lambda()(typename T)( constexpr auto handleRepeatedVariablesImpl = [](const auto& triple, auto& addIndexScan, const auto& generateUniqueVarName, const auto& addFilter, - ql::span permutations, auto... rewritePositions) - -> CPP_ret(void)( - requires(TriplePosition&&...)) { + ql::span permutations, + auto... rewritePositions) -> CPP_ret(void)(requires(TriplePosition&&...)) +{ auto scanTriple = triple; (..., rewriteSingle(rewritePositions, scanTriple, addFilter, generateUniqueVarName)); @@ -656,9 +656,8 @@ void QueryPlanner::indexScanTwoVarsCase( auto handleRepeatedVariables = [&triple, &addIndexScan, &addFilter, &generate]( ql::span permutations, - auto... rewritePositions) - -> CPP_ret(void)( - requires(TriplePosition&&...)) { + auto... rewritePositions) -> CPP_ret(void)(requires(TriplePosition&&...)) + { return handleRepeatedVariablesImpl(triple, addIndexScan, generate, addFilter, permutations, rewritePositions...); @@ -711,9 +710,8 @@ void QueryPlanner::indexScanThreeVarsCase( auto handleRepeatedVariables = [&triple, &addIndexScan, &addFilter, &generate]( ql::span permutations, - auto... rewritePositions) - -> CPP_ret(void)( - requires(TriplePosition&&...)) { + auto... rewritePositions) -> CPP_ret(void)(requires(TriplePosition&&...)) + { return handleRepeatedVariablesImpl(triple, addIndexScan, generate, addFilter, permutations, rewritePositions...); diff --git a/src/engine/Result.h b/src/engine/Result.h index 87a2b85e78..e38141e4c5 100644 --- a/src/engine/Result.h +++ b/src/engine/Result.h @@ -64,9 +64,9 @@ class Result { std::make_unique(false); explicit GenContainer(LazyResult generator) : generator_{std::move(generator)} {} - CPP_template(typename Range)( - requires std::is_constructible_v< - LazyResult, Range>) explicit GenContainer(Range range) + CPP_template( + typename Range) (requires std::is_constructible_v) + explicit GenContainer(Range range) : generator_{LazyResult{std::move(range)}} {} }; @@ -231,11 +231,11 @@ class Result { const Result& result2); // Overload for more than two `Results` - CPP_template(typename R)( - requires ql::ranges::forward_range CPP_and ql::concepts:: - convertible_to, - const Result&>) static SharedLocalVocabWrapper - getMergedLocalVocab(R&& subResults) { + CPP_template( + typename R) (requires ql::ranges::forward_range CPP_and + ql::concepts::convertible_to, + const Result&>) + static SharedLocalVocabWrapper getMergedLocalVocab(R&& subResults) { std::vector vocabs; for (const Result& table : subResults) { vocabs.push_back(&table.localVocab()); diff --git a/src/engine/Server.cpp b/src/engine/Server.cpp index 9f0d99e0b6..834e1e4428 100644 --- a/src/engine/Server.cpp +++ b/src/engine/Server.cpp @@ -197,12 +197,13 @@ void Server::run(const std::string& indexBaseName, bool useText, } // _____________________________________________________________________________ -CPP_template_def(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - net::awaitable> Server:: - verifyUserSubmittedQueryTimeout( - std::optional userTimeout, bool accessTokenOk, - const RequestT& request, ResponseT& send) const { +CPP_template_def( + typename RequestT, + typename ResponseT)(requires ad_utility::httpUtils::HttpRequest) +net::awaitable> +Server::verifyUserSubmittedQueryTimeout( + std::optional userTimeout, bool accessTokenOk, + const RequestT& request, ResponseT& send) const { auto defaultTimeout = getRuntimeParameter<&RuntimeParameters::defaultQueryTimeout_>(); // TODO Use the monadic operations for std::optional @@ -336,9 +337,10 @@ void Server::configurePinnedResultWithName( } // _____________________________________________________________________________ -CPP_template_def(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable Server::process(RequestT& request, ResponseT&& send) { +CPP_template_def( + typename RequestT, + typename ResponseT)(requires ad_utility::httpUtils::HttpRequest) +Awaitable Server::process(RequestT& request, ResponseT&& send) { using namespace ad_utility::httpUtils; // Log some basic information about the request. Start with an empty line so @@ -391,8 +393,8 @@ CPP_template_def(typename RequestT, typename ResponseT)( // Execute commands (URL parameter with key "cmd"). auto logCommand = [](const std::optional& cmd, std::string_view actionMsg) { - AD_LOG_INFO << "Processing command \"" << cmd.value() << "\"" - << ": " << actionMsg << std::endl; + AD_LOG_INFO << "Processing command \"" << cmd.value() << "\"" << ": " + << actionMsg << std::endl; }; if (auto cmd = checkParameter("cmd", "stats")) { logCommand(cmd, "get index statistics"); @@ -731,10 +733,10 @@ nlohmann::json Server::composeCacheStatsJson() const { } // _____________________________________________ -CPP_template_def(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) - ad_utility::websocket::OwningQueryId Server::getQueryId( - const RequestT& request, std::string_view query) { +CPP_template_def( + typename RequestT)(requires ad_utility::httpUtils::HttpRequest) +ad_utility::websocket::OwningQueryId Server::getQueryId( + const RequestT& request, std::string_view query) { using ad_utility::websocket::OwningQueryId; std::string_view queryIdHeader = request.base()["Query-Id"]; if (queryIdHeader.empty()) { @@ -749,13 +751,14 @@ CPP_template_def(typename RequestT)( } // _____________________________________________________________________________ -CPP_template_def(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable Server::sendStreamableResponse( - const RequestT& request, ResponseT& send, MediaType mediaType, - const PlannedQuery& plannedQuery, const QueryExecutionTree& qet, - const ad_utility::Timer& requestTimer, - SharedCancellationHandle cancellationHandle) const { +CPP_template_def( + typename RequestT, + typename ResponseT)(requires ad_utility::httpUtils::HttpRequest) +Awaitable Server::sendStreamableResponse( + const RequestT& request, ResponseT& send, MediaType mediaType, + const PlannedQuery& plannedQuery, const QueryExecutionTree& qet, + const ad_utility::Timer& requestTimer, + SharedCancellationHandle cancellationHandle) const { auto responseGenerator = ExportQueryExecutionTrees::computeResult( plannedQuery.parsedQuery_, qet, mediaType, requestTimer, std::move(cancellationHandle)); @@ -793,11 +796,11 @@ CPP_template_def(typename RequestT, typename ResponseT)( } // ____________________________________________________________________________ -CPP_template_def(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) - std::vector Server::determineMediaTypes( - const ad_utility::url_parser::ParamValueMap& params, - const RequestT& request) { +CPP_template_def( + typename RequestT)(requires ad_utility::httpUtils::HttpRequest) +std::vector Server::determineMediaTypes( + const ad_utility::url_parser::ParamValueMap& params, + const RequestT& request) { using namespace ad_utility::url_parser; // The following code block determines the media type to be used for the // result. The media type is either determined by the "Accept:" header of @@ -835,11 +838,11 @@ CPP_template_def(typename RequestT)( } // ____________________________________________________________________________ -CPP_template_def(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) - ad_utility::websocket::MessageSender Server::createMessageSender( - const std::weak_ptr& queryHub, - const RequestT& request, std::string_view operation) { +CPP_template_def( + typename RequestT)(requires ad_utility::httpUtils::HttpRequest) +ad_utility::websocket::MessageSender Server::createMessageSender( + const std::weak_ptr& queryHub, + const RequestT& request, std::string_view operation) { auto queryHubLock = queryHub.lock(); AD_CORRECTNESS_CHECK(queryHubLock); ad_utility::websocket::MessageSender messageSender{ @@ -880,14 +883,15 @@ ad_utility::MediaType Server::chooseBestFittingMediaType( } // ____________________________________________________________________________ -CPP_template_def(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable Server::processQuery( - const ad_utility::url_parser::ParamValueMap& params, - ParsedQuery&& query, const ad_utility::Timer& requestTimer, - ad_utility::SharedCancellationHandle cancellationHandle, - QueryExecutionContext& qec, const RequestT& request, ResponseT&& send, - TimeLimit timeLimit, std::optional& plannedQuery) { +CPP_template_def( + typename RequestT, + typename ResponseT)(requires ad_utility::httpUtils::HttpRequest) +Awaitable Server::processQuery( + const ad_utility::url_parser::ParamValueMap& params, ParsedQuery&& query, + const ad_utility::Timer& requestTimer, + ad_utility::SharedCancellationHandle cancellationHandle, + QueryExecutionContext& qec, const RequestT& request, ResponseT&& send, + TimeLimit timeLimit, std::optional& plannedQuery) { AD_CORRECTNESS_CHECK(!query.hasUpdateClause()); auto mediaTypes = determineMediaTypes(params, request); @@ -1029,14 +1033,15 @@ UpdateMetadata Server::processUpdateImpl( } // ____________________________________________________________________________ -CPP_template_def(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable Server::processUpdate( - std::vector&& updates, - const ad_utility::Timer& requestTimer, SharedTimeTracer tracer, - ad_utility::SharedCancellationHandle cancellationHandle, - QueryExecutionContext& qec, const RequestT& request, ResponseT&& send, - TimeLimit timeLimit, std::optional& plannedUpdate) { +CPP_template_def( + typename RequestT, + typename ResponseT)(requires ad_utility::httpUtils::HttpRequest) +Awaitable Server::processUpdate( + std::vector&& updates, const ad_utility::Timer& requestTimer, + SharedTimeTracer tracer, + ad_utility::SharedCancellationHandle cancellationHandle, + QueryExecutionContext& qec, const RequestT& request, ResponseT&& send, + TimeLimit timeLimit, std::optional& plannedUpdate) { tracer->beginTrace("waitingForUpdateThread"); AD_CORRECTNESS_CHECK(ql::ranges::all_of( updates, [](const ParsedQuery& p) { return p.hasUpdateClause(); })); @@ -1093,9 +1098,8 @@ CPP_template_def(typename RequestT, typename ResponseT)( updateMetadata, *tracer)); tracer->reset(); - AD_LOG_INFO << "Done processing update" - << ", total time was " << requestTimer.msecs().count() - << " ms" << std::endl; + AD_LOG_INFO << "Done processing update" << ", total time was " + << requestTimer.msecs().count() << " ms" << std::endl; AD_LOG_DEBUG << "Runtime Info:\n" << plannedUpdate->queryExecutionTree_.getRootOperation() ->runtimeInfo() @@ -1116,13 +1120,14 @@ CPP_template_def(typename RequestT, typename ResponseT)( } // ____________________________________________________________________________ -CPP_template_def(typename VisitorT, typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable Server::processOperation( - ad_utility::url_parser::sparqlOperation::Operation operation, - VisitorT visitor, const ad_utility::Timer& requestTimer, - const RequestT& request, ResponseT& send, - const std::optional& plannedQuery) { +CPP_template_def( + typename VisitorT, typename RequestT, + typename ResponseT)(requires ad_utility::httpUtils::HttpRequest) +Awaitable Server::processOperation( + ad_utility::url_parser::sparqlOperation::Operation operation, + VisitorT visitor, const ad_utility::Timer& requestTimer, + const RequestT& request, ResponseT& send, + const std::optional& plannedQuery) { // Copy the operation string for the error case before processing the // operation, because processing moves it. const std::string operationString = [&operation] { @@ -1217,9 +1222,9 @@ CPP_template_def(typename VisitorT, typename RequestT, typename ResponseT)( // _____________________________________________________________________________ CPP_template_def(typename Function, typename T)(requires ql::concepts::invocable) - Awaitable Server::computeInNewThread(net::static_thread_pool& threadPool, - Function function, - SharedCancellationHandle handle) { +Awaitable Server::computeInNewThread(net::static_thread_pool& threadPool, + Function function, + SharedCancellationHandle handle) { // `interruptible` will set the shared state of this promise // with a function that can be used to cancel the timer. std::promise> cancelTimerPromise{}; diff --git a/src/engine/Server.h b/src/engine/Server.h index dd77038316..4e6080748d 100644 --- a/src/engine/Server.h +++ b/src/engine/Server.h @@ -111,10 +111,9 @@ class Server { using SharedCancellationHandle = ad_utility::SharedCancellationHandle; using SharedTimeTracer = std::shared_ptr; - CPP_template(typename CancelTimeout)( - requires ad_utility::isInstantiation< - CancelTimeout, - absl::Cleanup>) struct CancellationHandleAndTimeoutTimerCancel { + CPP_template(typename CancelTimeout) ( + requires ad_utility::isInstantiation) + struct CancellationHandleAndTimeoutTimerCancel { SharedCancellationHandle handle_; /// Object of type `absl::Cleanup` that when destroyed cancels the timer /// that would otherwise invoke the cancellation of the `handle_` via the @@ -125,11 +124,11 @@ class Server { // Clang doesn't seem to be able to automatically deduce the type correctly. // and GCC 11 thinks deduction guides are not allowed within classes. #ifdef __clang__ - CPP_template(typename CancelTimeout)( - requires ad_utility::isInstantiation) - CancellationHandleAndTimeoutTimerCancel(SharedCancellationHandle, - CancelTimeout) - -> CancellationHandleAndTimeoutTimerCancel; + CPP_template(typename CancelTimeout) ( + requires ad_utility::isInstantiation) + CancellationHandleAndTimeoutTimerCancel(SharedCancellationHandle, + CancelTimeout) + -> CancellationHandleAndTimeoutTimerCancel; #endif /// Handle a single HTTP request. Check whether a file request or a query was @@ -138,19 +137,21 @@ class Server { /// \param req The HTTP request. /// \param send The action that sends a http:response. (see the /// `HttpServer.h` for documentation). - CPP_template(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable process(RequestT& request, ResponseT&& send); + CPP_template( + typename RequestT, + typename ResponseT) (requires ad_utility::httpUtils::HttpRequest) + Awaitable process(RequestT& request, ResponseT&& send); // Wraps the error handling around the processing of operations. Calls the // visitor on the given operation. - CPP_template(typename VisitorT, typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable processOperation( - ad_utility::url_parser::sparqlOperation::Operation operation, - VisitorT visitor, const ad_utility::Timer& requestTimer, - const RequestT& request, ResponseT& send, - const std::optional& plannedQuery); + CPP_template( + typename VisitorT, typename RequestT, + typename ResponseT) (requires ad_utility::httpUtils::HttpRequest) + Awaitable processOperation( + ad_utility::url_parser::sparqlOperation::Operation operation, + VisitorT visitor, const ad_utility::Timer& requestTimer, + const RequestT& request, ResponseT& send, + const std::optional& plannedQuery); // Out of a list of allowed media types, choose the one that best fits the // given query type. Currently it just chooses the first from the list. If the @@ -161,14 +162,15 @@ class Server { FRIEND_TEST(ServerTest, chooseBestFittingMediaType); // Do the actual execution of a query. - CPP_template(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable processQuery( - const ad_utility::url_parser::ParamValueMap& params, - ParsedQuery&& query, const ad_utility::Timer& requestTimer, - ad_utility::SharedCancellationHandle cancellationHandle, - QueryExecutionContext& qec, const RequestT& request, ResponseT&& send, - TimeLimit timeLimit, std::optional& plannedQuery); + CPP_template( + typename RequestT, + typename ResponseT) (requires ad_utility::httpUtils::HttpRequest) + Awaitable processQuery( + const ad_utility::url_parser::ParamValueMap& params, ParsedQuery&& query, + const ad_utility::Timer& requestTimer, + ad_utility::SharedCancellationHandle cancellationHandle, + QueryExecutionContext& qec, const RequestT& request, ResponseT&& send, + TimeLimit timeLimit, std::optional& plannedQuery); // For an executed update create a json with some stats on the update (timing, // number of changed triples, etc.). static nlohmann::ordered_json createResponseMetadataForUpdate( @@ -178,24 +180,25 @@ class Server { const ad_utility::timer::TimeTracer& tracer); FRIEND_TEST(ServerTest, createResponseMetadata); // Do the actual execution of an update. - CPP_template(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable processUpdate( - std::vector&& updates, - const ad_utility::Timer& requestTimer, SharedTimeTracer tracer, - ad_utility::SharedCancellationHandle cancellationHandle, - QueryExecutionContext& qec, const RequestT& request, ResponseT&& send, - TimeLimit timeLimit, std::optional& plannedUpdate); + CPP_template( + typename RequestT, + typename ResponseT) (requires ad_utility::httpUtils::HttpRequest) + Awaitable processUpdate( + std::vector&& updates, const ad_utility::Timer& requestTimer, + SharedTimeTracer tracer, + ad_utility::SharedCancellationHandle cancellationHandle, + QueryExecutionContext& qec, const RequestT& request, ResponseT&& send, + TimeLimit timeLimit, std::optional& plannedUpdate); // Determine media type candidates to be used for the result. Media types are // determined (in this order) by the current action (e.g., // "action=csv_export") and by the "Accept" header of the request. The latter // option can produce multiple candidates. - CPP_template(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) static std:: - vector determineMediaTypes( - const ad_utility::url_parser::ParamValueMap& params, - const RequestT& request); + CPP_template( + typename RequestT) (requires ad_utility::httpUtils::HttpRequest) + static std::vector determineMediaTypes( + const ad_utility::url_parser::ParamValueMap& params, + const RequestT& request); FRIEND_TEST(ServerTest, determineMediaType); // Determine whether the subtrees and the result should be pinned. static std::pair determineResultPinning( @@ -229,11 +232,11 @@ class Server { TimeLimit timeLimit, QueryExecutionContext& qec, SharedCancellationHandle handle) const; // Creates a `MessageSender` for the given operation. - CPP_template(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) - ad_utility::websocket::MessageSender createMessageSender( - const std::weak_ptr& queryHub, - const RequestT& request, std::string_view operation); + CPP_template( + typename RequestT) (requires ad_utility::httpUtils::HttpRequest) + ad_utility::websocket::MessageSender createMessageSender( + const std::weak_ptr& queryHub, + const RequestT& request, std::string_view operation); // Execute an update operation. The function must have exclusive access to the // DeltaTriples object. UpdateMetadata processUpdateImpl( @@ -250,11 +253,12 @@ class Server { /// Invoke `function` on `threadPool_`, and return an awaitable to wait for /// its completion, wrapping the result. - CPP_template(typename Function, typename T = std::invoke_result_t)( - requires ql::concepts::invocable) - Awaitable computeInNewThread( - boost::asio::static_thread_pool& threadPool, Function function, - SharedCancellationHandle handle); + CPP_template(typename Function, + typename T = std::invoke_result_t< + Function>) (requires ql::concepts::invocable) + Awaitable computeInNewThread(boost::asio::static_thread_pool& threadPool, + Function function, + SharedCancellationHandle handle); /// This method extracts a client-defined query id from the passed HTTP /// request if it is present. If it is not present or empty, a new @@ -269,10 +273,10 @@ class Server { /// /// \return An OwningQueryId object. It removes itself from the registry /// on destruction. - CPP_template(typename RequestT)( - requires ad_utility::httpUtils::HttpRequest) - ad_utility::websocket::OwningQueryId - getQueryId(const RequestT& request, std::string_view query); + CPP_template( + typename RequestT) (requires ad_utility::httpUtils::HttpRequest) + ad_utility::websocket::OwningQueryId getQueryId(const RequestT& request, + std::string_view query); /// Schedule a task to trigger the timeout after the `timeLimit`. /// The returned callback can be used to prevent this task from executing @@ -307,21 +311,24 @@ class Server { /// lower than the server default. Return an empty optional and send a 403 /// Forbidden HTTP response if the change is not allowed. Return the new /// timeout otherwise. - CPP_template(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) boost::asio:: - awaitable> verifyUserSubmittedQueryTimeout( - std::optional userTimeout, bool accessTokenOk, - const RequestT& request, ResponseT& send) const; + CPP_template( + typename RequestT, + typename ResponseT) (requires ad_utility::httpUtils::HttpRequest) + boost::asio::awaitable> + verifyUserSubmittedQueryTimeout(std::optional userTimeout, + bool accessTokenOk, const RequestT& request, + ResponseT& send) const; /// Send response for the streamable media types (tsv, csv, octet-stream, /// turtle, sparqlJson, qleverJson). - CPP_template(typename RequestT, typename ResponseT)( - requires ad_utility::httpUtils::HttpRequest) - Awaitable sendStreamableResponse( - const RequestT& request, ResponseT& send, - ad_utility::MediaType mediaType, const PlannedQuery& plannedQuery, - const QueryExecutionTree& qet, const ad_utility::Timer& requestTimer, - SharedCancellationHandle cancellationHandle) const; + CPP_template( + typename RequestT, + typename ResponseT) (requires ad_utility::httpUtils::HttpRequest) + Awaitable sendStreamableResponse( + const RequestT& request, ResponseT& send, ad_utility::MediaType mediaType, + const PlannedQuery& plannedQuery, const QueryExecutionTree& qet, + const ad_utility::Timer& requestTimer, + SharedCancellationHandle cancellationHandle) const; }; #endif // QLEVER_SRC_ENGINE_SERVER_H diff --git a/src/engine/Service.cpp b/src/engine/Service.cpp index 23d82b9213..7bed9399e0 100644 --- a/src/engine/Service.cpp +++ b/src/engine/Service.cpp @@ -258,9 +258,8 @@ namespace { // `CachingTransformInputRange` with a trivial transformation. This enables the // usage of the `Range` with the additional interface and caching properties of // the `CachingInputRange`. -CPP_template(typename Range)( - requires ad_utility::Rvalue< - Range&&>) auto moveToCachingInputRange(Range&& range) { +CPP_template(typename Range) (requires ad_utility::Rvalue) +auto moveToCachingInputRange(Range&& range) { return ad_utility::CachingTransformInputRange( AD_FWD(range), [](auto& input) { return std::move(input); }); } diff --git a/src/engine/TextIndexScanForEntity.cpp b/src/engine/TextIndexScanForEntity.cpp index 1d0cee2ce8..8ccb48d24c 100644 --- a/src/engine/TextIndexScanForEntity.cpp +++ b/src/engine/TextIndexScanForEntity.cpp @@ -136,8 +136,8 @@ std::string TextIndexScanForEntity::getDescriptor() const { // _____________________________________________________________________________ std::string TextIndexScanForEntity::getCacheKeyImpl() const { std::ostringstream os; - os << "ENTITY INDEX SCAN FOR WORD: " - << " with word: \"" << config_.word_ << "\" and fixed-entity: \"" + os << "ENTITY INDEX SCAN FOR WORD: " << " with word: \"" << config_.word_ + << "\" and fixed-entity: \"" << (hasFixedEntity() ? fixedEntity() : "no fixed-entity") << "\", has variable: " << config_.scoreVar_.has_value(); return std::move(os).str(); diff --git a/src/engine/TextIndexScanForWord.cpp b/src/engine/TextIndexScanForWord.cpp index 7e61fde69a..72cd4c8ed2 100644 --- a/src/engine/TextIndexScanForWord.cpp +++ b/src/engine/TextIndexScanForWord.cpp @@ -115,8 +115,7 @@ std::string TextIndexScanForWord::getDescriptor() const { // _____________________________________________________________________________ std::string TextIndexScanForWord::getCacheKeyImpl() const { std::ostringstream os; - os << "WORD INDEX SCAN: " - << " with word: \"" << config_.word_ + os << "WORD INDEX SCAN: " << " with word: \"" << config_.word_ << "\", has variable: " << config_.scoreVar_.has_value(); return std::move(os).str(); } diff --git a/src/engine/TextLimit.cpp b/src/engine/TextLimit.cpp index 056564fca9..b109dd37c2 100644 --- a/src/engine/TextLimit.cpp +++ b/src/engine/TextLimit.cpp @@ -178,8 +178,8 @@ std::string TextLimit::getDescriptor() const { // _____________________________________________________________________________ std::string TextLimit::getCacheKeyImpl() const { std::ostringstream os; - os << "TEXT LIMIT: " - << " with n: " << limit_ << ", with child: " << child_->getCacheKey() + os << "TEXT LIMIT: " << " with n: " << limit_ + << ", with child: " << child_->getCacheKey() << " and ColumnIndices: " << textRecordColumn_ << ", {"; for (const auto& column : entityColumns_) { os << column << ", "; diff --git a/src/engine/TransitivePathBinSearch.cpp b/src/engine/TransitivePathBinSearch.cpp index 2d68adf3f1..9caadab3fd 100644 --- a/src/engine/TransitivePathBinSearch.cpp +++ b/src/engine/TransitivePathBinSearch.cpp @@ -90,9 +90,8 @@ IdWithGraphs BinSearchMap::getEquivalentIdAndMatchingGraphs(Id node) const { // of all distinct Ids in the current graph. auto transformedRange = ql::ranges::subrange{startIdsLower, startIdsUpper} | - ql::views::transform([graphId](Id id) { - return std::pair{id, graphId}; - }); + ql::views::transform( + [graphId](Id id) { return std::pair{id, graphId}; }); ql::ranges::unique_copy(transformedRange, std::back_inserter(result), {}, ad_utility::first); } else { diff --git a/src/engine/TransitivePathImpl.h b/src/engine/TransitivePathImpl.h index 97c4545414..2da5ca3569 100644 --- a/src/engine/TransitivePathImpl.h +++ b/src/engine/TransitivePathImpl.h @@ -257,10 +257,10 @@ class TransitivePathImpl : public TransitivePathBase { * LocalVocab is a no-op). * @return Map Maps each Id to its connected Ids in the transitive hull */ - CPP_template(typename Node)(requires ql::ranges::range) NodeGenerator - transitiveHull(T edges, LocalVocab edgesVocab, Node startNodes, - TripleComponent start, TripleComponent target, - bool yieldOnce) const { + CPP_template(typename Node) (requires ql::ranges::range) + NodeGenerator transitiveHull(T edges, LocalVocab edgesVocab, Node startNodes, + TripleComponent start, TripleComponent target, + bool yieldOnce) const { ad_utility::Timer timer{ad_utility::Timer::Stopped}; // `targetId` is only ever used for comparisons, and never stored in the // result, so we use a separate local vocabulary. diff --git a/src/engine/idTable/CompressedExternalIdTable.h b/src/engine/idTable/CompressedExternalIdTable.h index 327eb4f77d..3534d5da0c 100644 --- a/src/engine/idTable/CompressedExternalIdTable.h +++ b/src/engine/idTable/CompressedExternalIdTable.h @@ -349,9 +349,10 @@ CPP_class_template(size_t NumStaticCols, } // Add a single row to the input. The type of `row` needs to be something that // can be `push_back`ed to a `IdTable`. - CPP_template(typename R)( - requires compressedExternalIdTable::detail::HasPushBack< - decltype(currentBlock_), R>) void push(const R& row) { + CPP_template( + typename R) (requires compressedExternalIdTable::detail::HasPushBack< + decltype(currentBlock_), R>) + void push(const R& row) { ++numElementsPushed_; currentBlock_.push_back(row); if (currentBlock_.size() >= blocksize_) { @@ -640,9 +641,10 @@ class CompressedExternalIdTableSorter // Similar to `sortedView` (see above), but the elements are yielded in // blocks. The size of the blocks is `blocksize` if specified, otherwise it // will be automatically determined from the given memory limit. - CPP_template(size_t N = NumStaticCols)(requires(N == NumStaticCols || N == 0)) - ad_utility::InputRangeTypeErased> getSortedBlocks( - std::optional blocksize = std::nullopt) { + CPP_template(size_t N = + NumStaticCols) (requires(N == NumStaticCols || N == 0)) + ad_utility::InputRangeTypeErased> getSortedBlocks( + std::optional blocksize = std::nullopt) { // If we move the result out, there must only be a single merge phase. AD_CONTRACT_CHECK(this->isFirstIteration_ || !this->moveResultOnMerge_); AD_CONTRACT_CHECK(!mergeIsActive_.load()); @@ -755,9 +757,10 @@ class CompressedExternalIdTableSorter // Transition from the input phase, where `push()` may be called, to the // output phase and return an input range that yields the sorted elements. // This function may be called exactly once. - CPP_template(size_t N = NumStaticCols)(requires(N == NumStaticCols || N == 0)) - ad_utility::InputRangeTypeErased> sortedBlocks( - std::optional blocksize = std::nullopt) { + CPP_template(size_t N = + NumStaticCols) (requires(N == NumStaticCols || N == 0)) + ad_utility::InputRangeTypeErased> sortedBlocks( + std::optional blocksize = std::nullopt) { if (!this->transformAndPushLastBlock()) { // There was only one block, return it. If a blocksize was explicitly // requested for the output, and the single block is larger than this diff --git a/src/engine/idTable/IdTable.h b/src/engine/idTable/IdTable.h index f7ce706904..5b0e78d593 100644 --- a/src/engine/idTable/IdTable.h +++ b/src/engine/idTable/IdTable.h @@ -183,14 +183,12 @@ class IdTable { // Then the argument `numColumns` and `NumColumns` (the static and the // dynamic number of columns) must be equal, else a runtime check fails. // Note: this also allows to create an empty view. - CPP_template(typename = void)( - requires columnsAreAllocatable CPP_and std::is_default_constructible_v< - Allocator>) explicit IdTable(size_t numColumns) - : IdTable(numColumns, Allocator{}) {} - - CPP_template(typename = void)( - requires(columnsAreAllocatable)) explicit IdTable(size_t numColumns, - Allocator allocator) + CPP_template(typename = void) (requires columnsAreAllocatable CPP_and + std::is_default_constructible_v) + explicit IdTable(size_t numColumns) : IdTable(numColumns, Allocator{}) {} + + CPP_template(typename = void) (requires(columnsAreAllocatable)) + explicit IdTable(size_t numColumns, Allocator allocator) : numColumns_{numColumns}, allocator_{std::move(allocator)} { if constexpr (!isDynamic) { AD_CONTRACT_CHECK(NumColumns == numColumns); @@ -207,9 +205,9 @@ class IdTable { // fails. Additional columns (if `columns.size() > numColumns`) are deleted. // This behavior is useful for unit tests Where we can just generically pass // in more columns than are needed in any test. - CPP_template(typename ColT)( - requires ql::ranges::forward_range CPP_and CPP_NOT(isView)) - IdTable(size_t numColumns, ColT columns) + CPP_template( + typename ColT) (requires ql::ranges::forward_range CPP_and CPP_NOT(isView)) + IdTable(size_t numColumns, ColT columns) : data_{ql::make_move_iterator(columns.begin()), ql::make_move_iterator(columns.end())}, numColumns_{numColumns} { @@ -228,14 +226,15 @@ class IdTable { // already set up with the correct number of columns and can be used directly. // If `NumColumns == 0` then the number of columns has to be specified via // `setNumColumns()`. - CPP_template(typename = void)( - requires CPP_NOT(isView) CPP_and columnsAreAllocatable CPP_and - std::is_default_constructible_v) IdTable() - : IdTable{NumColumns, Allocator{}} {}; - - CPP_template(typename = void)( - requires CPP_NOT(isView) - CPP_and columnsAreAllocatable) explicit IdTable(Allocator allocator) + CPP_template( + typename = + void) (requires CPP_NOT(isView) CPP_and columnsAreAllocatable CPP_and + std::is_default_constructible_v) + IdTable() : IdTable{NumColumns, Allocator{}} {}; + + CPP_template( + typename = void) (requires CPP_NOT(isView) CPP_and columnsAreAllocatable) + explicit IdTable(Allocator allocator) : IdTable{NumColumns, std::move(allocator)} {}; // `IdTables` are expensive to copy, so we disable accidental copies as they @@ -245,12 +244,20 @@ class IdTable { // TODO implement a facility (probably via inheritance) where we can // also implement the deleted copy operations for C++17 #ifndef QLEVER_CPP_17 - IdTable(const IdTable&) requires(!isView) = delete; - IdTable& operator=(const IdTable&) requires(!isView) = delete; + IdTable(const IdTable&) + requires(!isView) + = delete; + IdTable& operator=(const IdTable&) + requires(!isView) + = delete; // Views are copyable, as they are cheap to copy. - IdTable(const IdTable&) requires isView = default; - IdTable& operator=(const IdTable&) requires isView = default; + IdTable(const IdTable&) + requires isView + = default; + IdTable& operator=(const IdTable&) + requires isView + = default; #else IdTable(const IdTable&) = default; @@ -289,8 +296,8 @@ class IdTable { public: // For an empty and dynamic (`NumColumns == 0`) `IdTable`, specify the // number of columns. - CPP_template(typename = void)( - requires(columnsAreAllocatable)) void setNumColumns(size_t numColumns) { + CPP_template(typename = void) (requires(columnsAreAllocatable)) + void setNumColumns(size_t numColumns) { AD_CONTRACT_CHECK(empty()); AD_CONTRACT_CHECK(isDynamic || numColumns == NumColumns); numColumns_ = numColumns; @@ -298,8 +305,9 @@ class IdTable { } // Add a new empty column to the table. - CPP_template(typename = void)( - requires columnsAreAllocatable CPP_and isDynamic) void addEmptyColumn() { + CPP_template(typename = + void) (requires columnsAreAllocatable CPP_and isDynamic) + void addEmptyColumn() { data().emplace_back(size(), allocator_); ++numColumns_; } @@ -332,8 +340,8 @@ class IdTable { // for performance reason whenever possible. // TODO Use the multidimensional subscript operator. // TODO Use explicit object parameters ("deducing this"). - CPP_template(typename = void)(requires(!isView)) T& operator()( - size_t row, size_t column) { + CPP_template(typename = void) (requires(!isView)) + T& operator()(size_t row, size_t column) { AD_EXPENSIVE_CHECK(column < data().size(), [&]() { return absl::StrCat(row, " , ", column, ", ", data().size(), " ", numColumns(), ", ", numStaticColumns); @@ -348,18 +356,18 @@ class IdTable { // Get safe access to a single element specified by the row and the column. // Throw if the row or the column is out of bounds. See the note for // `operator()` above. - CPP_template(typename = void)(requires(!isView)) T& at(size_t row, - size_t column) { + CPP_template(typename = void) (requires(!isView)) + T& at(size_t row, size_t column) { return data().at(column).at(row); } // TODO Remove overload for `isView` and drop requires clause. - CPP_template(typename = void)(requires(!isView)) const T& at( - size_t row, size_t column) const { + CPP_template(typename = void) (requires(!isView)) + const T& at(size_t row, size_t column) const { return data().at(column).at(row); } // `std::span::at` is a C++26 feature, so we have to implement it ourselves. - CPP_template(typename = void)(requires(isView)) const T& at( - size_t row, size_t column) const { + CPP_template(typename = void) (requires(isView)) + const T& at(size_t row, size_t column) const { const auto& col = data().at(column); AD_CONTRACT_CHECK(row < col.size()); return col[row]; @@ -368,8 +376,8 @@ class IdTable { // Get a reference to the `i`-th row. The returned proxy objects can be // implicitly and trivially converted to `row_reference`. For the design // rationale behind those proxy types see above for their definition. - CPP_template(typename = void)(requires(!isView)) row_reference_restricted - operator[](size_t index) { + CPP_template(typename = void) (requires(!isView)) + row_reference_restricted operator[](size_t index) { return *(begin() + index); } const_row_reference_restricted operator[](size_t index) const { @@ -378,8 +386,8 @@ class IdTable { // Same as operator[], but throw an exception if the `row` is out of bounds. // This is similar to the behavior of `std::vector::at`. - CPP_template(typename = void)(requires(!isView)) row_reference_restricted - at(size_t row) { + CPP_template(typename = void) (requires(!isView)) + row_reference_restricted at(size_t row) { AD_CONTRACT_CHECK(row < numRows()); return operator[](row); } @@ -392,15 +400,15 @@ class IdTable { // `std::vector` and other containers. // TODO Remove the duplicates via explicit object parameters // ("deducing this"). - CPP_template(typename = void)(requires(!isView)) row_reference_restricted - front() { + CPP_template(typename = void) (requires(!isView)) + row_reference_restricted front() { return (*this)[0]; } const_row_reference_restricted front() const { return (*this)[0]; } - CPP_template(typename = void)(requires(!isView)) row_reference_restricted - back() { + CPP_template(typename = void) (requires(!isView)) + row_reference_restricted back() { return (*this)[numRows() - 1]; } const_row_reference_restricted back() const { return (*this)[numRows() - 1]; } @@ -413,7 +421,8 @@ class IdTable { // // Note: The semantics of this function is similar to `std::vector::resize`. // To set the capacity, use the `reserve` function. - CPP_template(typename = void)(requires(!isView)) void resize(size_t numRows) { + CPP_template(typename = void) (requires(!isView)) + void resize(size_t numRows) { ql::ranges::for_each(data(), [numRows](auto& column) { column.resize(numRows); }); numRows_ = numRows; @@ -425,8 +434,8 @@ class IdTable { // iterators are invalidated, but you obtain the guarantee, that the insertion // of the next `numRows - size()` elements (via `insert` or `push_back`) can // be done in O(1) time without dynamic allocations. - CPP_template(typename = void)(requires(!isView)) void reserve( - size_t numRows) { + CPP_template(typename = void) (requires(!isView)) + void reserve(size_t numRows) { ql::ranges::for_each(data(), [numRows](auto& column) { column.reserve(numRows); }); } @@ -434,7 +443,8 @@ class IdTable { // Delete all the elements, but keep the allocated memory (`capacityRows_` // stays the same). Runs in O(1) time. To also free the allocated memory, call // `shrinkToFit()` after calling `clear()` . - CPP_template(typename = void)(requires(!isView)) void clear() { + CPP_template(typename = void) (requires(!isView)) + void clear() { numRows_ = 0; ql::ranges::for_each(data(), [](auto& column) { column.clear(); }); } @@ -442,7 +452,8 @@ class IdTable { // Adjust the capacity to exactly match the size. This optimizes the memory // consumption of this table. This operation runs in O(size()), allocates // memory, and invalidates all iterators. - CPP_template(typename = void)(requires(!isView)) void shrinkToFit() { + CPP_template(typename = void) (requires(!isView)) + void shrinkToFit() { ql::ranges::for_each(data(), [](auto& column) { column.shrink_to_fit(); }); } @@ -453,7 +464,8 @@ class IdTable { // `O(n)`. The underlying data model is a dynamic array like `std::vector`. // Insert a new uninitialized row at the end. - CPP_template(typename = void)(requires(!isView)) void emplace_back() { + CPP_template(typename = void) (requires(!isView)) + void emplace_back() { ql::ranges::for_each(data(), [](auto& column) { column.emplace_back(); }); ++numRows_; } @@ -462,11 +474,12 @@ class IdTable { // otherwise the behavior is undefined (in Release mode) or an assertion will // fail (in Debug mode). The `newRow` can be any random access range that // stores the right type and has the right size. - CPP_template(typename RowLike)( - requires CPP_NOT(isView) CPP_and ql::ranges::random_access_range - CPP_and - ql::concepts::same_as, - T>) void push_back(const RowLike& newRow) { + CPP_template( + typename RowLike) (requires CPP_NOT(isView) + CPP_and ql::ranges::random_access_range + CPP_and ql::concepts::same_as< + ql::ranges::range_value_t, T>) + void push_back(const RowLike& newRow) { AD_EXPENSIVE_CHECK(newRow.size() == numColumns()); ++numRows_; ql::ranges::for_each(ad_utility::integerRange(numColumns()), @@ -475,8 +488,8 @@ class IdTable { }); } - CPP_template(typename = void)(requires(!isView)) void push_back( - const std::initializer_list& newRow) { + CPP_template(typename = void) (requires(!isView)) + void push_back(const std::initializer_list& newRow) { push_back(ql::ranges::ref_view{newRow}); } @@ -491,8 +504,8 @@ class IdTable { // `true`), then the copy constructor will also create a (const and // non-owning) view, but `clone` will create a mutable deep copy of the data // that the view points to - CPP_template(typename = void)(requires(isCloneable)) - IdTable clone() const { + CPP_template(typename = void) (requires(isCloneable)) + IdTable clone() const { Storage storage; for (const auto& column : getColumns()) { storage.emplace_back(column.begin(), column.end(), getAllocator()); @@ -506,8 +519,8 @@ class IdTable { // `auto newTable = AD_FWD(oldTable).moveOrClone()` which is equivalent to the // pattern `auto newX = AD_FWD(oldX)` where the type is copy-constructible // (which `IdTable` is not.). - CPP_member auto moveOrClone() const& -> CPP_ret(IdTable)( - requires isCloneable) { + CPP_member auto moveOrClone() const& -> CPP_ret(IdTable)(requires isCloneable) + { return clone(); } @@ -518,11 +531,10 @@ class IdTable { // Overload of `clone` for `Storage` types that are not copy constructible. // It requires a preconstructed but empty argument of type `Storage` that // is then resized and filled with the appropriate contents. - CPP_template(typename = void)( - requires(!std::is_copy_constructible_v)) - IdTable clone( - std::vector newColumns, - Allocator allocator = {}) const { + CPP_template( + typename = void) (requires(!std::is_copy_constructible_v)) + IdTable clone( + std::vector newColumns, Allocator allocator = {}) const { AD_CONTRACT_CHECK(newColumns.size() >= numColumns()); Data newStorage(ql::make_move_iterator(newColumns.begin()), ql::make_move_iterator(newColumns.begin() + numColumns())); @@ -545,10 +557,10 @@ class IdTable { // in fact moves a dynamic table to a new dynamic table. This makes // generic code that is templated on the number of columns easier to // write. - CPP_template(int NewNumColumns)( - requires(isDynamic || NewNumColumns == NumColumns || NewNumColumns == 0) - CPP_and CPP_NOT( - isView)) IdTable toStatic() && { + CPP_template( + int NewNumColumns) (requires(isDynamic || NewNumColumns == NumColumns || + NewNumColumns == 0) CPP_and CPP_NOT(isView)) + IdTable toStatic() && { AD_CONTRACT_CHECK(numColumns() == NewNumColumns || NewNumColumns == 0); auto result = IdTable{ std::move(data()), numColumns(), std::move(numRows_), @@ -559,8 +571,8 @@ class IdTable { // Move this `IdTable` into a dynamic `IdTable` with `NumColumns == 0`. This // function may only be called on rvalues, because the table will be moved // from. - CPP_template(typename = void)( - requires(!isView)) IdTable toDynamic() && { + CPP_template(typename = void) (requires(!isView)) + IdTable toDynamic() && { auto result = IdTable{std::move(data()), numColumns_, std::move(numRows_), std::move(allocator_)}; @@ -580,9 +592,8 @@ class IdTable { // Note: This function can also be used with `NewNumColumns == 0`. Then it // creates a dynamic view from a dynamic table. This makes generic code // that is templated on the number of columns easier to write. - CPP_template(size_t NewNumColumns)(requires(isDynamic || NewNumColumns == 0)) - IdTable asStaticView() - const { + CPP_template(size_t NewNumColumns) (requires(isDynamic || NewNumColumns == 0)) + IdTable asStaticView() const { AD_CONTRACT_CHECK(numColumns() == NewNumColumns || NewNumColumns == 0); ViewSpans viewSpans(data().begin(), data().end()); @@ -593,9 +604,9 @@ class IdTable { // Obtain a dynamic and const view to this IdTable that contains a subset of // the columns that may be permuted. The subset of the columns is specified by // the argument `columnIndices`. - CPP_template(typename = void)(requires isDynamic) - IdTable asColumnSubsetView( - ql::span columnIndices) const { + CPP_template(typename = void) (requires isDynamic) + IdTable asColumnSubsetView( + ql::span columnIndices) const { AD_CONTRACT_CHECK(ql::ranges::all_of( columnIndices, [this](size_t idx) { return idx < numColumns(); })); ViewSpans viewSpans; @@ -647,8 +658,8 @@ class IdTable { } // Delete the column with the given column index. - CPP_template(typename = void)(requires isDynamic) void deleteColumn( - ColumnIndex colIdx) { + CPP_template(typename = void) (requires isDynamic) + void deleteColumn(ColumnIndex colIdx) { AD_CONTRACT_CHECK(colIdx < numColumns()); data().erase(data().begin() + colIdx); numColumns_--; @@ -691,10 +702,12 @@ class IdTable { // The usual overloads of `begin()` and `end()` for const and mutable // `IdTable`s. - CPP_template(typename = void)(requires(!isView)) iterator begin() { + CPP_template(typename = void) (requires(!isView)) + iterator begin() { return {this, 0}; } - CPP_template(typename = void)(requires(!isView)) iterator end() { + CPP_template(typename = void) (requires(!isView)) + iterator end() { return {this, size()}; } const_iterator begin() const { return {this, 0}; } @@ -710,8 +723,9 @@ class IdTable { // that `begin() <= beginIt <= endIt < end`, else the behavior is undefined. // The order of the elements before and after the erased regions remains the // same. This behavior is similar to `std::vector::erase`. - CPP_member auto erase(const iterator& beginIt, const iterator& endIt) - -> CPP_ret(void)(requires(!isView)) { + CPP_member auto erase(const iterator& beginIt, const iterator& endIt) -> CPP_ret( + void)(requires(!isView)) + { AD_EXPENSIVE_CHECK(begin() <= beginIt && beginIt <= endIt && endIt <= end()); auto startIndex = beginIt - begin(); @@ -726,8 +740,8 @@ class IdTable { // Erase the single row that `it` points to by shifting all the elements // after `it` towards the beginning. Requires that `begin() <= it < end()`, // otherwise the behavior is undefined. - CPP_member auto erase(const iterator& it) - -> CPP_ret(void)(requires(!isView)) { + CPP_member auto erase(const iterator& it) -> CPP_ret(void)(requires(!isView)) + { erase(it, it + 1); } @@ -775,8 +789,8 @@ class IdTable { // Check whether two `IdTables` have the same content. Mostly used for unit // testing. - CPP_template(typename = void)(requires(!isView)) bool operator==( - const IdTable& other) const { + CPP_template(typename = void) (requires(!isView)) + bool operator==(const IdTable& other) const { if (numColumns() != other.numColumns()) { return (empty() && other.empty()); } @@ -799,8 +813,8 @@ class IdTable { } // Get the `i`-th column. It is stored contiguously in memory. - CPP_template(typename = void)(requires(!isView)) ql::span getColumn( - size_t i) { + CPP_template(typename = void) (requires(!isView)) + ql::span getColumn(size_t i) { return {data().at(i)}; } ql::span getColumn(size_t i) const { return {data().at(i)}; } diff --git a/src/engine/idTable/IdTableRow.h b/src/engine/idTable/IdTableRow.h index 669e76fdcc..ca7e22eec7 100644 --- a/src/engine/idTable/IdTableRow.h +++ b/src/engine/idTable/IdTableRow.h @@ -56,19 +56,18 @@ class Row { public: // Construct a row for the dynamic case (then the number of columns has to be // specified). - CPP_template_2(typename = void)(requires(isDynamic())) explicit Row( - size_t numCols) - : data_(numCols) {} + CPP_template_2(typename = void)(requires(isDynamic())) + explicit Row(size_t numCols) : data_(numCols) {} // Construct a row when the number of columns is statically known. Besides the // default constructor, we also keep the constructor that has a `numCols` // argument (which is ignored), in order to facilitate generic code that works // for both cases. - CPP_template_2(typename = void)(requires(!isDynamic())) Row(){}; + CPP_template_2(typename = void)(requires(!isDynamic())) + Row(){}; - CPP_template_2(typename = void)(requires(!isDynamic())) explicit Row( - size_t numCols) - : Row() { + CPP_template_2(typename = void)(requires(!isDynamic())) + explicit Row(size_t numCols) : Row() { (void)numCols; } @@ -96,8 +95,8 @@ class Row { QL_DEFINE_DEFAULTED_EQUALITY_OPERATOR_LOCAL(Row, data_) // Convert from a static `RowReference` to a `std::array` (makes a copy). - CPP_template_2(typename = void)(requires(NumColumns != 0)) explicit - operator std::array() const { + CPP_template_2(typename = void)(requires(NumColumns != 0)) + explicit operator std::array() const { std::array result; ql::ranges::copy(*this, result.begin()); return result; @@ -105,9 +104,8 @@ class Row { // This operator is only for debugging and testing. It returns a // human-readable representation. - CPP_template_2(typename = void)( - requires(std::is_same_v)) friend std::ostream& - operator<<(std::ostream& os, const Row& idTableRow) { + CPP_template_2(typename = void)(requires(std::is_same_v)) + friend std::ostream& operator<<(std::ostream& os, const Row& idTableRow) { os << "("; for (size_t i = 0; i < idTableRow.numColumns(); ++i) { os << idTableRow[i] << (i < idTableRow.numColumns() - 1 ? " " : ")"); @@ -181,11 +179,10 @@ class RowReferenceImpl { protected: // The actual implementation of operator[]. - CPP_template(typename SelfType)( - requires CPP_NOT(std::is_const_v>) - CPP_and CPP_NOT( - isConst)) static T& operatorBracketImpl(SelfType& self, - size_t i) { + CPP_template(typename SelfType) ( + requires CPP_NOT(std::is_const_v>) + CPP_and CPP_NOT(isConst)) + static T& operatorBracketImpl(SelfType& self, size_t i) { return (*self.table_)(self.row_, i); } template @@ -196,8 +193,8 @@ class RowReferenceImpl { public: // Access to the `i`-th columns of this row. Only allowed for const values // and for rvalues. - CPP_template_2(typename = void)(requires(!isConst)) T& operator[]( - size_t i) && { + CPP_template_2(typename = void)(requires(!isConst)) + T& operator[](size_t i) && { return operatorBracketImpl(*this, i); } const T& operator[](size_t i) const& { @@ -246,8 +243,8 @@ class RowReferenceImpl { protected: // The implementation of swapping two `RowReference`s (passed either by // value or by reference). - CPP_template(typename AType, typename BType)( - requires(!isConst)) static void swapImpl(AType&& a, BType&& b) { + CPP_template(typename AType, typename BType) (requires(!isConst)) + static void swapImpl(AType&& a, BType&& b) { for (size_t i = 0; i < a.numColumns(); ++i) { std::swap(operatorBracketImpl(a, i), operatorBracketImpl(b, i)); } @@ -261,8 +258,8 @@ class RowReferenceImpl { public: // Swap two `RowReference`s, but only if they are temporaries (rvalues). // This modifies the underlying table. - CPP_template(typename = void)(requires CPP_NOT(isConst)) friend void swap( - This&& a, This&& b) { + CPP_template(typename = void) (requires CPP_NOT(isConst)) + friend void swap(This&& a, This&& b) { return swapImpl(a, b); } @@ -302,8 +299,8 @@ class RowReferenceImpl { } // Convert from a static `RowReference` to a `std::array` (makes a copy). - CPP_template(typename = void)(requires(numStaticColumns != 0)) explicit - operator std::array() const { + CPP_template(typename = void) (requires(numStaticColumns != 0)) + explicit operator std::array() const { std::array result; ql::ranges::copy(*this, result.begin()); return result; @@ -335,9 +332,9 @@ class RowReferenceImpl { } // Assignment from a `const` RowReference to a `mutable` RowReference - CPP_template_2(typename = void)(requires(!isConst)) This& operator=( - const RowReferenceWithRestrictedAccess< - Table, ad_utility::IsConst::True>& other) && { + CPP_template_2(typename = void)(requires(!isConst)) + This& operator=(const RowReferenceWithRestrictedAccess< + Table, ad_utility::IsConst::True>& other) && { return assignmentImpl(*this, other); } @@ -391,7 +388,8 @@ class RowReference using Base::Base; // Access to the `i`-th column of this row. - CPP_template_2(typename = void)(requires(!isConst)) T& operator[](size_t i) { + CPP_template_2(typename = void)(requires(!isConst)) + T& operator[](size_t i) { return Base::operatorBracketImpl(base(), i); } const T& operator[](size_t i) const { @@ -407,23 +405,21 @@ class RowReference // The `cbegin` and `cend` functions are implicitly inherited from `Base`. // __________________________________________________________________________ - CPP_template_2(typename R)(requires ad_utility::SimilarTo - CPP_and_2(!isConst)) friend void swap(R&& a, - R&& b) { + CPP_template_2(typename R)( + requires ad_utility::SimilarTo CPP_and_2(!isConst)) + friend void swap(R&& a, R&& b) { return Base::swapImpl(AD_FWD(a), AD_FWD(b)); } // Equality comparison. Works between two `RowReference`s, but also between // a `RowReference` and a `Row` if the number of columns match. - CPP_template_2(typename T)(requires(numStaticColumns == - T::numStaticColumns)) bool - operator==(const T& other) const { + CPP_template_2(typename T)(requires(numStaticColumns == T::numStaticColumns)) + bool operator==(const T& other) const { return base() == other; } - CPP_template_2(typename T)(requires(numStaticColumns == - T::numStaticColumns)) bool - operator!=(const T& other) const { + CPP_template_2(typename T)(requires(numStaticColumns == T::numStaticColumns)) + bool operator!=(const T& other) const { return !(base() == other); } @@ -446,7 +442,8 @@ class RowReference } // Assignment from a `const` RowReference to a `mutable` RowReference - CPP_template_2(typename = void)(requires(!isConst)) RowReference& operator=( + CPP_template_2(typename = void)(requires(!isConst)) + RowReference& operator=( const RowReference& other) { this->assignmentImpl(base(), other); return *this; diff --git a/src/engine/sparqlExpressions/AggregateExpression.cpp b/src/engine/sparqlExpressions/AggregateExpression.cpp index a95e9dbdf3..eaec2f51cf 100644 --- a/src/engine/sparqlExpressions/AggregateExpression.cpp +++ b/src/engine/sparqlExpressions/AggregateExpression.cpp @@ -22,7 +22,8 @@ struct EvaluateOnChildOperand { ValueId resultForEmptyGroup, const FinalOperation& finalOperation, EvaluationContext* context, bool distinct, O&& operand) const - -> CPP_ret(ExpressionResult)(requires SingleExpressionResult) { + -> CPP_ret(ExpressionResult)(requires SingleExpressionResult) + { // Perform the more efficient calculation on `SetOfInterval`s if it is // possible. // diff --git a/src/engine/sparqlExpressions/AggregateExpression.h b/src/engine/sparqlExpressions/AggregateExpression.h index 364df8b598..ec6885ca50 100644 --- a/src/engine/sparqlExpressions/AggregateExpression.h +++ b/src/engine/sparqlExpressions/AggregateExpression.h @@ -115,8 +115,9 @@ using AGG_EXP = AggregateExpression< template struct NumericExpressionForAggregate { template - auto operator()(const Args&... args) const -> CPP_ret(NumericValue)( - requires(ad_utility::SimilarTo&&...)) { + auto operator()(const Args&... args) const -> CPP_ret( + NumericValue)(requires(ad_utility::SimilarTo&&...)) + { auto visitor = [](const auto&... t) -> NumericValue { if constexpr ((... || std::is_same_v>)) { @@ -204,7 +205,8 @@ template struct MinMaxLambdaForAllTypes { template auto operator()(const T& a, const T& b, const EvaluationContext* ctx) const - -> CPP_ret(T)(requires SingleExpressionResult) { + -> CPP_ret(T)(requires SingleExpressionResult) + { auto actualImpl = [ctx](const auto& x, const auto& y) { return compareIdsOrStrings(x, y, ctx); }; diff --git a/src/engine/sparqlExpressions/BlankNodeExpression.cpp b/src/engine/sparqlExpressions/BlankNodeExpression.cpp index 10ec6830ec..b33bd9d41f 100644 --- a/src/engine/sparqlExpressions/BlankNodeExpression.cpp +++ b/src/engine/sparqlExpressions/BlankNodeExpression.cpp @@ -85,12 +85,13 @@ class BlankNodeExpression : public SparqlExpression { // Perform the actual evaluation of the expression. This creates a blank node // based on the result of `getNextLabel`. - CPP_template(typename Printable, typename Func)( - requires ad_utility::InvocableWithConvertibleReturnType< - Func, std::optional> - CPP_and std::is_constructible_v) - ExpressionResult - evaluateImpl(EvaluationContext* context, Func getNextLabel) const { + CPP_template( + typename Printable, + typename Func) (requires ad_utility::InvocableWithConvertibleReturnType< + Func, std::optional> + CPP_and std::is_constructible_v) + ExpressionResult evaluateImpl(EvaluationContext* context, + Func getNextLabel) const { std::string_view blankNodePrefix = "un"; VectorWithMemoryLimit result{context->_allocator}; diff --git a/src/engine/sparqlExpressions/ConditionalExpressions.cpp b/src/engine/sparqlExpressions/ConditionalExpressions.cpp index c298a32eeb..846c42fb99 100644 --- a/src/engine/sparqlExpressions/ConditionalExpressions.cpp +++ b/src/engine/sparqlExpressions/ConditionalExpressions.cpp @@ -14,12 +14,13 @@ namespace sparqlExpression { namespace detail::conditional_expressions { using namespace sparqlExpression::detail; struct IfImpl { - CPP_template(typename I, typename E)( - requires SingleExpressionResult&& SingleExpressionResult&& - std::is_rvalue_reference_v&& std::is_rvalue_reference_v) - IdOrLiteralOrIri - operator()(EffectiveBooleanValueGetter::Result condition, I&& i, - E&& e) const { + CPP_template( + typename I, + typename E) (requires SingleExpressionResult && SingleExpressionResult && + std::is_rvalue_reference_v && + std::is_rvalue_reference_v) + IdOrLiteralOrIri operator()(EffectiveBooleanValueGetter::Result condition, + I&& i, E&& e) const { if (condition == EffectiveBooleanValueGetter::Result::True) { return AD_FWD(i); } else if (condition == EffectiveBooleanValueGetter::Result::False) { diff --git a/src/engine/sparqlExpressions/ConvertToDtypeConstructor.cpp b/src/engine/sparqlExpressions/ConvertToDtypeConstructor.cpp index 8d2dace5c4..21e55f04b1 100644 --- a/src/engine/sparqlExpressions/ConvertToDtypeConstructor.cpp +++ b/src/engine/sparqlExpressions/ConvertToDtypeConstructor.cpp @@ -34,9 +34,9 @@ namespace detail::to_numeric { // class that converts an input `int64_t`, `double` or `std::string` // to a numeric value `int64_t` or `double` -CPP_template(typename T, bool AllowExponentialNotation = true)( - requires(concepts::same_as || - concepts::same_as)) class ToNumericImpl { +CPP_template(typename T, bool AllowExponentialNotation = true) ( + requires(concepts::same_as || concepts::same_as)) +class ToNumericImpl { private: ValueId getFromString(const std::string& input) const { auto str = absl::StripAsciiWhitespace(input); @@ -67,9 +67,9 @@ CPP_template(typename T, bool AllowExponentialNotation = true)( // ___________________________________________________________________________ template - auto getFromNumber(N number) const - -> CPP_ret(Id)(requires(concepts::integral || - ql::concepts::floating_point)) { + auto getFromNumber(N number) const -> CPP_ret( + Id)(requires(concepts::integral || ql::concepts::floating_point)) + { auto resNumber = static_cast(number); if constexpr (std::is_same_v) { return Id::makeFromInt(resNumber); diff --git a/src/engine/sparqlExpressions/GroupConcatExpression.cpp b/src/engine/sparqlExpressions/GroupConcatExpression.cpp index 6ef036239f..3239c70a07 100644 --- a/src/engine/sparqlExpressions/GroupConcatExpression.cpp +++ b/src/engine/sparqlExpressions/GroupConcatExpression.cpp @@ -21,9 +21,9 @@ sparqlExpression::GroupConcatExpression::GroupConcatExpression( sparqlExpression::ExpressionResult sparqlExpression::GroupConcatExpression::evaluate( EvaluationContext* context) const { - auto impl = [this, context](auto&& el) - -> CPP_ret(ExpressionResult)( - requires SingleExpressionResult) { + auto impl = [this, context](auto&& el) -> CPP_ret( + ExpressionResult)(requires SingleExpressionResult) + { bool undefined = false; std::string result; std::optional langTag; diff --git a/src/engine/sparqlExpressions/LiteralExpression.h b/src/engine/sparqlExpressions/LiteralExpression.h index 2e419cce01..a2687563d3 100644 --- a/src/engine/sparqlExpressions/LiteralExpression.h +++ b/src/engine/sparqlExpressions/LiteralExpression.h @@ -43,11 +43,11 @@ class LiteralExpression : public SparqlExpression { // Evaluating just returns the constant/literal value. ExpressionResult evaluate(EvaluationContext* context) const override { // Common code for the `Literal` and `Iri` case. - auto getIdOrString = [this, &context](const auto& s) - -> CPP_ret(ExpressionResult)( - requires ad_utility::SameAsAny, - TripleComponent::Literal, - TripleComponent::Iri>) { + auto getIdOrString = [this, &context](const auto& s) -> CPP_ret( + ExpressionResult)(requires ad_utility::SameAsAny, + TripleComponent::Literal, + TripleComponent::Iri>) + { if (auto ptr = cachedResult_.load(std::memory_order_relaxed)) { return *ptr; } diff --git a/src/engine/sparqlExpressions/NaryExpression.h b/src/engine/sparqlExpressions/NaryExpression.h index 409545a01a..a80146bdb2 100644 --- a/src/engine/sparqlExpressions/NaryExpression.h +++ b/src/engine/sparqlExpressions/NaryExpression.h @@ -189,11 +189,12 @@ struct VariadicExpressionFactory { // `make...` functions for n-ary expressions that have a compile-time known // number of children. This makes the testing easier, as we then can use the // same test helpers for all expressions. -CPP_template(auto function)( - requires std::is_invocable_r_v< - SparqlExpression::Ptr, decltype(function), - std::vector< - SparqlExpression::Ptr> >) constexpr auto variadicExpressionFactory = +CPP_template( + auto + function) (requires std::is_invocable_r_v >) +constexpr auto variadicExpressionFactory = detail::VariadicExpressionFactory{}; SparqlExpression::Ptr makeCoalesceExpression( diff --git a/src/engine/sparqlExpressions/NaryExpressionImpl.h b/src/engine/sparqlExpressions/NaryExpressionImpl.h index 2cd433de10..4424d5f53a 100644 --- a/src/engine/sparqlExpressions/NaryExpressionImpl.h +++ b/src/engine/sparqlExpressions/NaryExpressionImpl.h @@ -31,9 +31,10 @@ class NaryExpression : public SparqlExpression { // Construct from `N` child expressions. Each of the children must have a type // `std::unique_ptr`. - CPP_template(typename... C)( - requires(concepts::convertible_to&&...) - CPP_and(sizeof...(C) == N)) explicit NaryExpression(C... children) + CPP_template( + typename... C) (requires(concepts::convertible_to&&...) + CPP_and(sizeof...(C) == N)) + explicit NaryExpression(C... children) : NaryExpression{Children{std::move(children)...}} {} // __________________________________________________________________________ @@ -48,11 +49,11 @@ class NaryExpression : public SparqlExpression { ql::span childrenImpl() override; // Evaluate the `naryOperation` on the `operands` using the `context`. - CPP_template(typename... Operands)( - requires(SingleExpressionResult&&...)) static ExpressionResult - evaluateOnChildrenOperands(NaryOperation naryOperation, - EvaluationContext* context, - Operands&&... operands) { + CPP_template( + typename... Operands) (requires(SingleExpressionResult&&...)) + static ExpressionResult evaluateOnChildrenOperands( + NaryOperation naryOperation, EvaluationContext* context, + Operands&&... operands) { // Perform a more efficient calculation if a specialized function exists // that matches all operands. if (isAnySpecializedFunctionPossible(naryOperation._specializedFunctions, diff --git a/src/engine/sparqlExpressions/NumericBinaryExpressions.cpp b/src/engine/sparqlExpressions/NumericBinaryExpressions.cpp index 0ff110f6fc..77994cddcb 100644 --- a/src/engine/sparqlExpressions/NumericBinaryExpressions.cpp +++ b/src/engine/sparqlExpressions/NumericBinaryExpressions.cpp @@ -329,9 +329,9 @@ constexpr auto getMergeFunction(bool isNegated) { } // namespace //______________________________________________________________________________ -CPP_template(typename BinaryPrefilterExpr, typename NaryOperation)( - requires isOperation) class LogicalBinaryExpressionImpl - : public NaryExpression { +CPP_template(typename BinaryPrefilterExpr, + typename NaryOperation) (requires isOperation) +class LogicalBinaryExpressionImpl : public NaryExpression { public: using NaryExpression::NaryExpression; diff --git a/src/engine/sparqlExpressions/NumericUnaryExpressions.cpp b/src/engine/sparqlExpressions/NumericUnaryExpressions.cpp index 29a541e952..7026204ba5 100644 --- a/src/engine/sparqlExpressions/NumericUnaryExpressions.cpp +++ b/src/engine/sparqlExpressions/NumericUnaryExpressions.cpp @@ -26,9 +26,8 @@ struct UnaryNegate { } }; -CPP_template(typename NaryOperation)( - requires isOperation) class UnaryNegateExpressionImpl - : public NaryExpression { +CPP_template(typename NaryOperation) (requires isOperation) +class UnaryNegateExpressionImpl : public NaryExpression { public: using NaryExpression::NaryExpression; diff --git a/src/engine/sparqlExpressions/PrefilterExpressionIndex.cpp b/src/engine/sparqlExpressions/PrefilterExpressionIndex.cpp index e4f214bf2e..e43568da62 100644 --- a/src/engine/sparqlExpressions/PrefilterExpressionIndex.cpp +++ b/src/engine/sparqlExpressions/PrefilterExpressionIndex.cpp @@ -839,8 +839,8 @@ std::string LogicalExpression::asString(size_t depth) const { std::stringstream stream; stream << "Prefilter LogicalExpression<" << getLogicalOpStr(Operation) << ">\n" - << "child1 {" << child1Info << "}" - << "child2 {" << child2Info << "}" << std::endl; + << "child1 {" << child1Info << "}" << "child2 {" << child2Info << "}" + << std::endl; return stream.str(); } diff --git a/src/engine/sparqlExpressions/RelationalExpressionHelpers.h b/src/engine/sparqlExpressions/RelationalExpressionHelpers.h index 7cab71a2cc..483ef08bc7 100644 --- a/src/engine/sparqlExpressions/RelationalExpressionHelpers.h +++ b/src/engine/sparqlExpressions/RelationalExpressionHelpers.h @@ -143,8 +143,8 @@ CPP_concept StoresStringOrId = // `getRangeFromVocab` above for details). This function also takes `ValueId`s // and `pair` which are simply returned unchanged. This makes // the usage of this function easier. -CPP_template(typename S)(requires StoresStringOrId) auto makeValueId( - const S& value, const EvaluationContext* context) { +CPP_template(typename S) (requires StoresStringOrId) +auto makeValueId(const S& value, const EvaluationContext* context) { if constexpr (ad_utility::SimilarToAny>) { return value; } else if constexpr (ad_utility::isSimilar) { @@ -168,10 +168,11 @@ template inline const auto compareIdsOrStrings = - [](const auto& a, const auto& b, const EvaluationContext* ctx) - -> CPP_ret(valueIdComparators::ComparisonResult)( - requires StoresStringOrId>&& - StoresStringOrId>) { + [](const auto& a, const auto& b, + const EvaluationContext* ctx) -> CPP_ret(valueIdComparators:: + ComparisonResult)(requires StoresStringOrId> && + StoresStringOrId>) +{ using T = std::decay_t; using U = std::decay_t; if constexpr (ad_utility::isSimilar && diff --git a/src/engine/sparqlExpressions/RelationalExpressions.cpp b/src/engine/sparqlExpressions/RelationalExpressions.cpp index f8eb889f16..8ea33e89d8 100644 --- a/src/engine/sparqlExpressions/RelationalExpressions.cpp +++ b/src/engine/sparqlExpressions/RelationalExpressions.cpp @@ -32,8 +32,9 @@ using valueIdComparators::Comparison; // case where `S` is `string` or `vector`. In this case the generator // yields `pair` (see `makeValueId` and `getRangeFromVocab` // above for details). -CPP_template(typename S)(requires SingleExpressionResult) auto idGenerator( - S&& input, size_t targetSize, const EvaluationContext* context) { +CPP_template(typename S) (requires SingleExpressionResult) +auto idGenerator(S&& input, size_t targetSize, + const EvaluationContext* context) { [[maybe_unused]] auto makeId = [context](const auto& el) { return makeValueId(el, context); }; @@ -57,10 +58,10 @@ CPP_template(typename S)(requires SingleExpressionResult) auto idGenerator( // `ValueId, vector, Variable`), then `idGenerator`s are returned for // both inputs. Else the "plain" generators from `sparqlExpression::detail` are // returned. These simply yield the values unchanged. -CPP_template(typename S1, typename S2)( - requires SingleExpressionResult CPP_and SingleExpressionResult< - S2>) auto getGenerators(S1&& value1, S2&& value2, size_t targetSize, - const EvaluationContext* context) { +CPP_template(typename S1, typename S2) ( + requires SingleExpressionResult CPP_and SingleExpressionResult) +auto getGenerators(S1&& value1, S2&& value2, size_t targetSize, + const EvaluationContext* context) { if constexpr (StoresValueId || StoresValueId) { return std::pair{idGenerator(AD_FWD(value1), targetSize, context), idGenerator(AD_FWD(value2), targetSize, context)}; @@ -122,11 +123,11 @@ ad_utility::SetOfIntervals evaluateWithBinarySearch( // The actual comparison function for the `SingleExpressionResult`'s which are // `AreComparable` (see above), which means that the comparison between them is // supported and not always false. -CPP_template(Comparison Comp, typename S1, typename S2)( - requires SingleExpressionResult CPP_and SingleExpressionResult - CPP_and AreComparable) ExpressionResult - evaluateRelationalExpression(S1&& value1, S2&& value2, - const EvaluationContext* context) { +CPP_template(Comparison Comp, typename S1, typename S2) ( + requires SingleExpressionResult CPP_and SingleExpressionResult + CPP_and AreComparable) +ExpressionResult evaluateRelationalExpression( + S1&& value1, S2&& value2, const EvaluationContext* context) { auto resultSize = sparqlExpression::detail::getResultSize(*context, value1, value2); constexpr static bool resultIsConstant = @@ -203,16 +204,16 @@ CPP_template(Comparison Comp, typename S1, typename S2)( // The relational comparisons like `less than` are not useful for booleans and // thus currently throw an exception. CPP_template(Comparison, typename A, - typename B)(requires(StoresBoolean || StoresBoolean)) Id - evaluateRelationalExpression(const A&, const B&, const EvaluationContext*) { + typename B) (requires(StoresBoolean || StoresBoolean)) +Id evaluateRelationalExpression(const A&, const B&, const EvaluationContext*) { throw std::runtime_error( "Relational expressions like <, >, == are currently not supported for " "boolean arguments"); } CPP_template(Comparison Comp, typename A, - typename B)(requires AreIncomparable) Id - evaluateRelationalExpression(const A&, const B&, const EvaluationContext*) { + typename B) (requires AreIncomparable) +Id evaluateRelationalExpression(const A&, const B&, const EvaluationContext*) { // TODO We should probably return `undefined` here. if constexpr (Comp == Comparison::NE) { return Id::makeFromBool(true); @@ -223,12 +224,13 @@ CPP_template(Comparison Comp, typename A, // For comparisons where exactly one of the operands is a variable, the variable // must come first. -CPP_template(Comparison Comp, typename A, typename B)( - requires SingleExpressionResult CPP_and SingleExpressionResult CPP_and - CPP_NOT(AreComparable) - CPP_and AreComparable) ExpressionResult - evaluateRelationalExpression(A&& a, B&& b, - const EvaluationContext* context) { +CPP_template( + Comparison Comp, typename A, + typename B) (requires SingleExpressionResult CPP_and SingleExpressionResult + CPP_and CPP_NOT(AreComparable) + CPP_and AreComparable) +ExpressionResult evaluateRelationalExpression( + A&& a, B&& b, const EvaluationContext* context) { return evaluateRelationalExpression( AD_FWD(b), AD_FWD(a), context); } diff --git a/src/engine/sparqlExpressions/SparqlExpressionGenerators.h b/src/engine/sparqlExpressions/SparqlExpressionGenerators.h index 27d9d47053..afa5bc33f3 100644 --- a/src/engine/sparqlExpressions/SparqlExpressionGenerators.h +++ b/src/engine/sparqlExpressions/SparqlExpressionGenerators.h @@ -63,24 +63,23 @@ inline ql::span getIdsFromVariable( /// `SparqlExpressionValueGetters` with an already bound `EvaluationContext`. #ifdef QLEVER_EXPRESSION_GENERATOR_BACKPORTS_FOR_CPP17 // Use range-based implementation for C++17 compatibility. -CPP_template(typename T, typename Transformation = ql::identity)( - requires SingleExpressionResult CPP_and isConstantResult CPP_and - ranges::invocable< - Transformation, - T>) auto resultGeneratorImpl(T constant, size_t numItems, - Transformation transformation = {}) { +CPP_template(typename T, typename Transformation = ql::identity) (requires SingleExpressionResult CPP_and isConstantResult + CPP_and ranges::invocable) +auto resultGeneratorImpl(T constant, size_t numItems, + Transformation transformation = {}) { // We have to use `range-v3` as `views::repeat` is a C++23 feature. return ::ranges::repeat_n_view(transformation(constant), numItems); } #else // Use faster coroutine-based implementation. -CPP_template(typename T, typename Transformation = ql::identity)( - requires SingleExpressionResult CPP_and isConstantResult CPP_and - ranges::invocable) - cppcoro::generator>> resultGeneratorImpl(T constant, size_t numItems, - Transformation transformation = - {}) { +CPP_template( + typename T, + typename Transformation = ql:: + identity) (requires SingleExpressionResult CPP_and isConstantResult + CPP_and ranges::invocable) +cppcoro::generator>> +resultGeneratorImpl(T constant, size_t numItems, + Transformation transformation = {}) { auto transformed = transformation(constant); for (size_t i = 0; i < numItems; ++i) { co_yield transformed; @@ -88,10 +87,10 @@ CPP_template(typename T, typename Transformation = ql::identity)( } #endif -CPP_template(typename T, typename Transformation = ql::identity)( - requires ql::ranges::input_range< - T>) auto resultGeneratorImpl(T&& vector, size_t numItems, - Transformation transformation = {}) { +CPP_template(typename T, typename Transformation = + ql::identity) (requires ql::ranges::input_range) +auto resultGeneratorImpl(T&& vector, size_t numItems, + Transformation transformation = {}) { AD_CONTRACT_CHECK(numItems == vector.size()); return ad_utility::allView(AD_FWD(vector)) | ql::views::transform(std::move(transformation)); @@ -187,11 +186,12 @@ inline auto resultGenerator(S&& input, size_t targetSize, } /// Return a generator that yields `numItems` many items for the various /// `SingleExpressionResult` -CPP_template(typename Input, typename Transformation = ql::identity)( - requires SingleExpressionResult< - Input>) auto makeGenerator(Input&& input, size_t numItems, - const EvaluationContext* context, - Transformation transformation = {}) { +CPP_template(typename Input, + typename Transformation = + ql::identity) (requires SingleExpressionResult) +auto makeGenerator(Input&& input, size_t numItems, + const EvaluationContext* context, + Transformation transformation = {}) { if constexpr (ad_utility::isSimilar<::Variable, Input>) { return resultGenerator(getIdsFromVariable(AD_FWD(input), context), numItems, transformation); @@ -266,11 +266,11 @@ inline auto applyFunction = [](auto function, size_t numItems, /// Return a generator that returns the `numElements` many results of the /// `Operation` applied to the `operands` -CPP_template(typename Operation, typename... Operands)(requires( - SingleExpressionResult< - Operands>&&...)) auto applyOperation(size_t numElements, Operation&&, - EvaluationContext* context, - Operands&&... operands) { +CPP_template( + typename Operation, + typename... Operands) (requires(SingleExpressionResult&&...)) +auto applyOperation(size_t numElements, Operation&&, EvaluationContext* context, + Operands&&... operands) { using ValueGetters = typename std::decay_t::ValueGetters; using Function = typename std::decay_t::Function; static_assert(std::tuple_size_v == sizeof...(Operands)); diff --git a/src/engine/sparqlExpressions/SparqlExpressionTypes.h b/src/engine/sparqlExpressions/SparqlExpressionTypes.h index 16746f3d16..3e60a0f472 100644 --- a/src/engine/sparqlExpressions/SparqlExpressionTypes.h +++ b/src/engine/sparqlExpressions/SparqlExpressionTypes.h @@ -51,14 +51,13 @@ class VectorWithMemoryLimit // * the last argument must be `AllocatorWithMemoryLimit` (all constructors to // `vector` take the allocator as a last parameter) // * there must be a constructor of `Base` for the given arguments. - CPP_template(typename... Args)( - requires(sizeof...(Args) > 0) CPP_and CPP_NOT( - concepts::derived_from>, - Base>) - CPP_and concepts::convertible_to, Allocator> - CPP_and concepts::constructible_from) - QL_EXPLICIT(sizeof...(Args) == 1) VectorWithMemoryLimit(Args&&... args) - : Base{AD_FWD(args)...} {} + CPP_template(typename... Args) (requires(sizeof...(Args) > 0) CPP_and CPP_NOT( + concepts::derived_from>, + Base>) CPP_and + concepts::convertible_to, Allocator> + CPP_and concepts::constructible_from) + QL_EXPLICIT(sizeof...(Args) == 1) + VectorWithMemoryLimit(Args&&... args) : Base{AD_FWD(args)...} {} // We have to explicitly forward the `initializer_list` constructor because it // for some reason is not covered by the above generic mechanism. @@ -129,12 +128,12 @@ CPP_concept SingleExpressionResult = ad_utility::SimilarToAnyTypeIn; // Copy an expression result. -CPP_template(typename ResultT)( - requires ad_utility::SimilarTo) ExpressionResult - copyExpressionResult(ResultT&& result) { - auto copyIfCopyable = [](const auto& x) - -> CPP_ret(ExpressionResult)( - requires SingleExpressionResult>) { +CPP_template( + typename ResultT) (requires ad_utility::SimilarTo) +ExpressionResult copyExpressionResult(ResultT&& result) { + auto copyIfCopyable = [](const auto& x) -> CPP_ret( + ExpressionResult)(requires SingleExpressionResult>) + { using R = std::decay_t; if constexpr (ql::concepts::copyable) { return x; @@ -238,10 +237,11 @@ struct EvaluationContext { namespace detail { /// Get Id of constant result of type T. -CPP_template(typename T, typename LocalVocabT)( - requires SingleExpressionResult CPP_and isConstantResult CPP_and - std::is_rvalue_reference_v) Id - constantExpressionResultToId(T&& result, LocalVocabT& localVocab) { +CPP_template( + typename T, + typename LocalVocabT) (requires SingleExpressionResult CPP_and isConstantResult + CPP_and std::is_rvalue_reference_v) +Id constantExpressionResultToId(T&& result, LocalVocabT& localVocab) { if constexpr (ad_utility::isSimilar) { return result; } else if constexpr (ad_utility::isSimilar) { @@ -384,8 +384,8 @@ constexpr bool isOperation> = true; // Return the common logical size of the `SingleExpressionResults`. // This is either 1 (in case all the `inputs` are constants) or the // size of the `context`. -CPP_template(typename... Inputs)(requires(SingleExpressionResult&&...)) - size_t getResultSize(const EvaluationContext& context, const Inputs&...) { +CPP_template(typename... Inputs) (requires(SingleExpressionResult&&...)) +size_t getResultSize(const EvaluationContext& context, const Inputs&...) { return (... && isConstantResult) ? 1ul : context.size(); } diff --git a/src/engine/sparqlExpressions/SparqlExpressionValueGetters.cpp b/src/engine/sparqlExpressions/SparqlExpressionValueGetters.cpp index 404f38777b..2ec1156429 100644 --- a/src/engine/sparqlExpressions/SparqlExpressionValueGetters.cpp +++ b/src/engine/sparqlExpressions/SparqlExpressionValueGetters.cpp @@ -436,11 +436,11 @@ std::optional GeoPointOrWktValueGetter::operator()( }; //______________________________________________________________________________ -CPP_template(typename T, typename ValueGetter)( - requires(concepts::same_as || - concepts::same_as, T>)) T - getValue(ValueId id, const sparqlExpression::EvaluationContext* context, - ValueGetter& valueGetter) { +CPP_template(typename T, + typename ValueGetter) (requires(concepts::same_as || + concepts::same_as, T>)) +T getValue(ValueId id, const sparqlExpression::EvaluationContext* context, + ValueGetter& valueGetter) { using enum Datatype; switch (id.getDatatype()) { case LocalVocabIndex: @@ -530,7 +530,7 @@ CPP_template_out_def(typename RequestedInfo)( requires ad_utility::RequestedInfoT) std::optional GeometryInfoValueGetter::operator()(ValueId id, - const EvaluationContext* context) const { + const EvaluationContext * context) const { using enum Datatype; switch (id.getDatatype()) { case EncodedVal: @@ -567,8 +567,8 @@ CPP_template_out_def(typename RequestedInfo)( CPP_template_out_def(typename RequestedInfo)( requires ad_utility::RequestedInfoT) std::optional GeometryInfoValueGetter::operator()(const LiteralOrIri& litOrIri, - [[maybe_unused]] const EvaluationContext* + RequestedInfo)>::operator()(const LiteralOrIri & litOrIri, + [[maybe_unused]] const EvaluationContext * context) const { // If we receive only a literal, we have no choice but to parse it and compute // the geometry info ad hoc. diff --git a/src/engine/sparqlExpressions/SparqlExpressionValueGetters.h b/src/engine/sparqlExpressions/SparqlExpressionValueGetters.h index d7c748cdf7..3cde3d85c4 100644 --- a/src/engine/sparqlExpressions/SparqlExpressionValueGetters.h +++ b/src/engine/sparqlExpressions/SparqlExpressionValueGetters.h @@ -59,7 +59,8 @@ CPP_concept ValueAsNumericId = // from above) into an `ID`. When `NanOrInfToUndef` is `true` then floating // point `NaN` or `+-infinity` values will become `Id::makeUndefined()`. CPP_template(bool NanOrInfToUndef = false, - typename T)(requires ValueAsNumericId) Id makeNumericId(T t) { + typename T) (requires ValueAsNumericId) +Id makeNumericId(T t) { if constexpr (concepts::integral) { return Id::makeFromInt(t); } else if constexpr (ql::concepts::floating_point && NanOrInfToUndef) { @@ -309,8 +310,9 @@ struct RegexValueGetter { template auto operator()(S&& input, const EvaluationContext* context) const -> CPP_ret(std::shared_ptr)( - requires SingleExpressionResult&& ranges::invocable< - LiteralFromIdGetter, S&&, const EvaluationContext*>) { + requires SingleExpressionResult && + ranges::invocable) + { auto str = LiteralFromIdGetter{}(AD_FWD(input), context); if (!str.has_value()) { return nullptr; @@ -423,10 +425,10 @@ struct IriOrUriValueGetter : Mixin { // `RequestedInfo` is computed ad hoc (for example the bounding box is not // calculated, when requesting the centroid). -CPP_template(typename RequestedInfo = ad_utility::GeometryInfo)( - requires ad_utility::RequestedInfoT< - RequestedInfo>) struct GeometryInfoValueGetter - : Mixin> { +CPP_template( + typename RequestedInfo = ad_utility:: + GeometryInfo) (requires ad_utility::RequestedInfoT) +struct GeometryInfoValueGetter : Mixin> { using Mixin>::operator(); std::optional operator()( ValueId id, const EvaluationContext* context) const; diff --git a/src/engine/sparqlExpressions/StdevExpression.cpp b/src/engine/sparqlExpressions/StdevExpression.cpp index 6ca1e2b2f7..d4212a4a4c 100644 --- a/src/engine/sparqlExpressions/StdevExpression.cpp +++ b/src/engine/sparqlExpressions/StdevExpression.cpp @@ -59,9 +59,9 @@ ExpressionResult DeviationExpression::evaluate( }; // Visitor for child expression result - auto impl = [context, devImpl](auto&& el) - -> CPP_ret(ExpressionResult)( - requires SingleExpressionResult) { + auto impl = [context, devImpl](auto&& el) -> CPP_ret( + ExpressionResult)(requires SingleExpressionResult) + { // Prepare space for result VectorWithMemoryLimit exprResult{context->_allocator}; exprResult.resize(context->size()); diff --git a/src/engine/sparqlExpressions/StringExpressions.cpp b/src/engine/sparqlExpressions/StringExpressions.cpp index bcb5822c39..a5dbec7c75 100644 --- a/src/engine/sparqlExpressions/StringExpressions.cpp +++ b/src/engine/sparqlExpressions/StringExpressions.cpp @@ -75,9 +75,9 @@ class StrExpression : public StrExpressionImpl { // strings. template struct LiftStringFunction { - CPP_template(typename... Arguments)(requires( - concepts::same_as>&&...)) auto - operator()(Arguments... arguments) const { + CPP_template(typename... Arguments) ( + requires(concepts::same_as>&&...)) + auto operator()(Arguments... arguments) const { using ResultOfFunction = decltype(std::invoke(Function{}, std::move(arguments.value())...)); static_assert(concepts::same_as || @@ -231,9 +231,8 @@ struct StrStartsImpl { namespace { -CPP_template(typename NaryOperation)( - requires isOperation) class StrStartsExpressionImpl - : public NaryExpression { +CPP_template(typename NaryOperation) (requires isOperation) +class StrStartsExpressionImpl : public NaryExpression { public: using NaryExpression::NaryExpression; std::vector getPrefilterExpressionForMetadata( @@ -611,8 +610,8 @@ using std::move; using Expr = SparqlExpression::Ptr; CPP_template(typename T, - typename... C)(requires(concepts::same_as&&...)) Expr - make(C&... children) { + typename... C) (requires(concepts::same_as&&...)) +Expr make(C&... children) { return std::make_unique(std::move(children)...); } Expr makeStrExpression(Expr child) { return make(child); } diff --git a/src/engine/sparqlExpressions/StringExpressionsHelper.h b/src/engine/sparqlExpressions/StringExpressionsHelper.h index f5fe57d387..6206862f31 100644 --- a/src/engine/sparqlExpressions/StringExpressionsHelper.h +++ b/src/engine/sparqlExpressions/StringExpressionsHelper.h @@ -27,11 +27,10 @@ class StringExpressionImplImpl : public SparqlExpression { Ptr impl_; public: - CPP_template(typename... C)( - requires(concepts::same_as&&...) - CPP_and(sizeof...(C) + 1 == - N)) explicit StringExpressionImplImpl(Ptr child, - C... children) { + CPP_template( + typename... C) (requires(concepts::same_as&&...) + CPP_and(sizeof...(C) + 1 == N)) + explicit StringExpressionImplImpl(Ptr child, C... children) { AD_CORRECTNESS_CHECK(child != nullptr); if (child->isStrExpression()) { auto childrenOfStr = std::move(*child).moveChildrenOut(); diff --git a/src/global/IdTriple.h b/src/global/IdTriple.h index 556dd5128f..b71fa5a06b 100644 --- a/src/global/IdTriple.h +++ b/src/global/IdTriple.h @@ -40,9 +40,8 @@ struct IdTriple { const auto& payload() const { return std::get<1>(data_); } auto& payload() { return std::get<1>(data_); } - CPP_template_2(typename = void)(requires(N == 0)) explicit IdTriple( - const std::array& idsIn) - : data_{idsIn, {}} {}; + CPP_template_2(typename = void)(requires(N == 0)) + explicit IdTriple(const std::array& idsIn) : data_{idsIn, {}} {}; explicit IdTriple(const std::array& idsIn, const Payload& payload) @@ -86,7 +85,7 @@ struct IdTriple { } CPP_template_2(typename = void)(requires(N == 0)) - CompressedBlockMetadata::PermutedTriple toPermutedTriple() const { + CompressedBlockMetadata::PermutedTriple toPermutedTriple() const { static_assert(NumCols == 4); return {ids()[0], ids()[1], ids()[2], ids()[3]}; } diff --git a/src/index/CompressedRelation.cpp b/src/index/CompressedRelation.cpp index a4d2744ce3..e3615fe18c 100644 --- a/src/index/CompressedRelation.cpp +++ b/src/index/CompressedRelation.cpp @@ -960,14 +960,14 @@ size_t CompressedRelationReader::getResultSizeOfScan( } // ____________________________________________________________________________ -CPP_template_def(typename IdGetter)( - requires ad_utility::InvocableWithConvertibleReturnType< - IdGetter, Id, const CompressedBlockMetadata::PermutedTriple&>) IdTable - CompressedRelationReader::getDistinctColIdsAndCountsImpl( - IdGetter idGetter, const ScanSpecAndBlocks& scanSpecAndBlocks, - const CancellationHandle& cancellationHandle, - const LocatedTriplesPerBlock& locatedTriplesPerBlock, - const LimitOffsetClause& limitOffset) const { +CPP_template_def( + typename IdGetter)(requires ad_utility::InvocableWithConvertibleReturnType< + IdGetter, Id, const CompressedBlockMetadata::PermutedTriple&>) +IdTable CompressedRelationReader::getDistinctColIdsAndCountsImpl( + IdGetter idGetter, const ScanSpecAndBlocks& scanSpecAndBlocks, + const CancellationHandle& cancellationHandle, + const LocatedTriplesPerBlock& locatedTriplesPerBlock, + const LimitOffsetClause& limitOffset) const { // The result has two columns: one for the distinct `Id`s and one for their // counts. IdTableStatic<2> table(allocator_); @@ -1548,9 +1548,10 @@ namespace { // Collect elements of type `T` in batches of size 100'000 and apply the // `Function` to each batch. For the last batch (which might be smaller) the // function is applied in the destructor. -CPP_template(typename T, typename Function)( - requires ad_utility::InvocableWithExactReturnType< - Function, void, std::vector&&>) struct Batcher { +CPP_template(typename T, typename Function) ( + requires ad_utility::InvocableWithExactReturnType &&>) +struct Batcher { Function function_; size_t blocksize_; std::vector vec_; @@ -2020,20 +2021,17 @@ auto createErrorMessage = [](const auto& b1, const auto& b2, // _____________________________________________________________________________ // Check if the provided `Range` holds less than two `CompressedBlockMetadata` // values. -CPP_template(typename Range)( - requires ql::ranges::input_range< - Range>) static bool checkBlockRangeSizeLessThanTwo(const Range& - blockMetadataRange) { +CPP_template(typename Range) (requires ql::ranges::input_range) +static bool checkBlockRangeSizeLessThanTwo(const Range& blockMetadataRange) { auto begin = ql::ranges::begin(blockMetadataRange); auto end = ql::ranges::end(blockMetadataRange); return begin == end || ql::ranges::next(begin) == end; }; // _____________________________________________________________________________ -CPP_template(typename Range)( - requires ql::ranges::input_range< - Range>) static void checkBlockMetadataInvariantOrderAndUniquenessImpl(const Range& - blockMetadataRange) { +CPP_template(typename Range) (requires ql::ranges::input_range) +static void checkBlockMetadataInvariantOrderAndUniquenessImpl( + const Range& blockMetadataRange) { if (checkBlockRangeSizeLessThanTwo(blockMetadataRange)) { return; } @@ -2059,7 +2057,8 @@ CPP_template(typename Range)( } // ____________________________________________________________________________ -CPP_template(typename Range)(requires ql::ranges::input_range) static void checkBlockMetadataInvariantBlockConsistencyImpl( +CPP_template(typename Range) (requires ql::ranges::input_range) +static void checkBlockMetadataInvariantBlockConsistencyImpl( const Range& blockMetadataRange, size_t firstFreeColIndex) { if (checkBlockRangeSizeLessThanTwo(blockMetadataRange)) { return; diff --git a/src/index/CompressedRelation.h b/src/index/CompressedRelation.h index 5d1022ee5e..ceeab88990 100644 --- a/src/index/CompressedRelation.h +++ b/src/index/CompressedRelation.h @@ -873,14 +873,14 @@ class CompressedRelationReader { // The common implementation for `getDistinctCol0IdsAndCounts` and // `getCol1IdsAndCounts`. - CPP_template(typename IdGetter)( - requires ad_utility::InvocableWithConvertibleReturnType< - IdGetter, Id, const CompressedBlockMetadata::PermutedTriple&>) IdTable - getDistinctColIdsAndCountsImpl( - IdGetter idGetter, const ScanSpecAndBlocks& scanSpecAndBlocks, - const CancellationHandle& cancellationHandle, - const LocatedTriplesPerBlock& locatedTriplesPerBlock, - const LimitOffsetClause& limitOffset) const; + CPP_template( + typename IdGetter) (requires ad_utility::InvocableWithConvertibleReturnType< + IdGetter, Id, const CompressedBlockMetadata::PermutedTriple&>) + IdTable getDistinctColIdsAndCountsImpl( + IdGetter idGetter, const ScanSpecAndBlocks& scanSpecAndBlocks, + const CancellationHandle& cancellationHandle, + const LocatedTriplesPerBlock& locatedTriplesPerBlock, + const LimitOffsetClause& limitOffset) const; }; // TODO diff --git a/src/index/DeltaTriples.cpp b/src/index/DeltaTriples.cpp index d85c1ba0b4..74945bff8d 100644 --- a/src/index/DeltaTriples.cpp +++ b/src/index/DeltaTriples.cpp @@ -90,8 +90,7 @@ DeltaTriplesCount DeltaTriples::getCounts() const { void DeltaTriples::insertTriples(CancellationHandle cancellationHandle, Triples triples, ad_utility::timer::TimeTracer& tracer) { - AD_LOG_DEBUG << "Inserting" - << " " << triples.size() + AD_LOG_DEBUG << "Inserting" << " " << triples.size() << " triples (including idempotent triples)." << std::endl; modifyTriplesImpl(std::move(cancellationHandle), std::move(triples), true, triplesInserted_, triplesDeleted_, tracer); @@ -101,8 +100,7 @@ void DeltaTriples::insertTriples(CancellationHandle cancellationHandle, void DeltaTriples::deleteTriples(CancellationHandle cancellationHandle, Triples triples, ad_utility::timer::TimeTracer& tracer) { - AD_LOG_DEBUG << "Deleting" - << " " << triples.size() + AD_LOG_DEBUG << "Deleting" << " " << triples.size() << " triples (including idempotent triples)." << std::endl; modifyTriplesImpl(std::move(cancellationHandle), std::move(triples), false, triplesDeleted_, triplesInserted_, tracer); diff --git a/src/index/GraphFilter.h b/src/index/GraphFilter.h index 534ac440ef..9d8c8847e0 100644 --- a/src/index/GraphFilter.h +++ b/src/index/GraphFilter.h @@ -57,9 +57,8 @@ class GraphFilter { // Transforms this `GraphFilter` into another one with a different template // argument, by using `func` to transform the underlying values from `T` to a // new type. - CPP_template(typename Func)(requires ql::concepts::invocable) - GraphFilter> transform( - const Func& func) const { + CPP_template(typename Func) (requires ql::concepts::invocable) + GraphFilter> transform(const Func& func) const { using TransformedT = std::invoke_result_t; using ResultT = GraphFilter; return std::visit(ad_utility::OverloadCallOperator{ diff --git a/src/index/IndexImpl.cpp b/src/index/IndexImpl.cpp index 5a14880804..4bda74e5b7 100644 --- a/src/index/IndexImpl.cpp +++ b/src/index/IndexImpl.cpp @@ -1329,9 +1329,8 @@ void IndexImpl::readIndexBuilderSettingsFromFile() { << std::endl; } AD_LOG_INFO << "You specified \"locale = " << lang << "_" << country - << "\" " - << "and \"ignore-punctuation = " << ignorePunctuation << "\"" - << std::endl; + << "\" " << "and \"ignore-punctuation = " << ignorePunctuation + << "\"" << std::endl; if (lang != LOCALE_DEFAULT_LANG || country != LOCALE_DEFAULT_COUNTRY) { AD_LOG_WARN @@ -1724,12 +1723,11 @@ constexpr auto makeNumDistinctIdsCounter = [](size_t& numDistinctIds) { } // namespace // _____________________________________________________________________________ -CPP_template_def(typename... NextSorter)(requires( - sizeof...(NextSorter) <= - 1)) void IndexImpl::createPSOAndPOSImpl(size_t numColumns, - BlocksOfTriples sortedTriples, - bool doWriteConfiguration, - NextSorter&&... nextSorter) +CPP_template_def(typename... NextSorter)(requires(sizeof...(NextSorter) <= 1)) +void IndexImpl::createPSOAndPOSImpl(size_t numColumns, + BlocksOfTriples sortedTriples, + bool doWriteConfiguration, + NextSorter&&... nextSorter) { size_t numTriplesNormal = 0; @@ -1756,20 +1754,19 @@ CPP_template_def(typename... NextSorter)(requires( }; // _____________________________________________________________________________ -CPP_template_def(typename... NextSorter)( - requires(sizeof...(NextSorter) <= - 1)) void IndexImpl::createPSOAndPOS(size_t numColumns, - BlocksOfTriples sortedTriples, - NextSorter&&... nextSorter) { +CPP_template_def(typename... NextSorter)(requires(sizeof...(NextSorter) <= 1)) +void IndexImpl::createPSOAndPOS(size_t numColumns, + BlocksOfTriples sortedTriples, + NextSorter&&... nextSorter) { createPSOAndPOSImpl(numColumns, std::move(sortedTriples), true, AD_FWD(nextSorter)...); } // _____________________________________________________________________________ CPP_template_def(typename... NextSorter)(requires(sizeof...(NextSorter) <= 1)) - std::optional IndexImpl::createSPOAndSOP( - size_t numColumns, BlocksOfTriples sortedTriples, - NextSorter&&... nextSorter) { +std::optional IndexImpl::createSPOAndSOP( + size_t numColumns, BlocksOfTriples sortedTriples, + NextSorter&&... nextSorter) { size_t numSubjectsNormal = 0; size_t numSubjectsTotal = 0; auto numSubjectCounter = makeNumDistinctIdsCounter<0>(numSubjectsNormal); @@ -1817,11 +1814,10 @@ CPP_template_def(typename... NextSorter)(requires(sizeof...(NextSorter) <= 1)) }; // _____________________________________________________________________________ -CPP_template_def(typename... NextSorter)( - requires(sizeof...(NextSorter) <= - 1)) void IndexImpl::createOSPAndOPS(size_t numColumns, - BlocksOfTriples sortedTriples, - NextSorter&&... nextSorter) { +CPP_template_def(typename... NextSorter)(requires(sizeof...(NextSorter) <= 1)) +void IndexImpl::createOSPAndOPS(size_t numColumns, + BlocksOfTriples sortedTriples, + NextSorter&&... nextSorter) { // For the last pair of permutations we don't need a next sorter, so we // have no fourth argument. size_t numObjectsNormal = 0; diff --git a/src/index/IndexImpl.h b/src/index/IndexImpl.h index 9294975026..88f4bc5c3d 100644 --- a/src/index/IndexImpl.h +++ b/src/index/IndexImpl.h @@ -705,34 +705,30 @@ class IndexImpl { // Create the SPO and SOP permutations. Additionally, count the number of // distinct actual (not internal) subjects in the input and write it to the // metadata. Also builds the patterns if specified. - CPP_template(typename... NextSorter)(requires(sizeof...(NextSorter) <= 1)) - std::optional createSPOAndSOP( - size_t numColumns, BlocksOfTriples sortedTriples, - NextSorter&&... nextSorter); + CPP_template(typename... NextSorter) (requires(sizeof...(NextSorter) <= 1)) + std::optional createSPOAndSOP( + size_t numColumns, BlocksOfTriples sortedTriples, + NextSorter&&... nextSorter); // Create the OSP and OPS permutations. Additionally, count the number of // distinct objects and write it to the metadata. - CPP_template(typename... NextSorter)(requires( - sizeof...(NextSorter) <= - 1)) void createOSPAndOPS(size_t numColumns, BlocksOfTriples sortedTriples, - NextSorter&&... nextSorter); + CPP_template(typename... NextSorter) (requires(sizeof...(NextSorter) <= 1)) + void createOSPAndOPS(size_t numColumns, BlocksOfTriples sortedTriples, + NextSorter&&... nextSorter); // Create the PSO and POS permutations. Additionally, count the number of // distinct predicates and the number of actual triples and write them to the // metadata. The meta-data JSON file for the index statistics will only be // written iff `doWriteConfiguration` is true. That parameter is set to // `false` when building the additional permutations for the internal triples. - CPP_template(typename... NextSorter)( - requires(sizeof...(NextSorter) <= - 1)) void createPSOAndPOSImpl(size_t numColumns, - BlocksOfTriples sortedTriples, - bool doWriteConfiguration, - NextSorter&&... nextSorter); + CPP_template(typename... NextSorter) (requires(sizeof...(NextSorter) <= 1)) + void createPSOAndPOSImpl(size_t numColumns, BlocksOfTriples sortedTriples, + bool doWriteConfiguration, + NextSorter&&... nextSorter); // Call `createPSOAndPOSImpl` with the given arguments and with // `doWriteConfiguration` set to `true` (see above). - CPP_template(typename... NextSorter)(requires( - sizeof...(NextSorter) <= - 1)) void createPSOAndPOS(size_t numColumns, BlocksOfTriples sortedTriples, - NextSorter&&... nextSorter); + CPP_template(typename... NextSorter) (requires(sizeof...(NextSorter) <= 1)) + void createPSOAndPOS(size_t numColumns, BlocksOfTriples sortedTriples, + NextSorter&&... nextSorter); // Create the internal PSO and POS permutations from the sorted internal // triples. Return `(numInternalTriples, numInternalPredicates)`. diff --git a/src/index/KeyOrder.h b/src/index/KeyOrder.h index 911dd9d37b..796f1617e0 100644 --- a/src/index/KeyOrder.h +++ b/src/index/KeyOrder.h @@ -66,10 +66,10 @@ class KeyOrder { } // The internal implementation of `permute` above. - CPP_variadic_template(typename T, size_t N, size_t... Indexes)(requires( - sizeof...(Indexes) == - N)) auto permuteImpl(const std::array& input, - std::integer_sequence) const + CPP_variadic_template(typename T, size_t N, + size_t... Indexes)(requires(sizeof...(Indexes) == N)) + auto permuteImpl(const std::array& input, + std::integer_sequence) const -> std::array { return {input[std::get(keys_)]...}; } diff --git a/src/index/LocalVocabEntry.h b/src/index/LocalVocabEntry.h index b86d708d77..ad12d4cbe6 100644 --- a/src/index/LocalVocabEntry.h +++ b/src/index/LocalVocabEntry.h @@ -80,8 +80,9 @@ class alignas(16) LocalVocabEntry // It suffices to hash the base class `LiteralOrIri` as the position in the // vocab is redundant for those purposes. template - friend auto AbslHashValue(H h, const V& entry) - -> CPP_ret(H)(requires ranges::same_as) { + friend auto AbslHashValue(H h, const V& entry) -> CPP_ret( + H)(requires ranges::same_as) + { return H::combine(std::move(h), static_cast(entry)); } diff --git a/src/index/LocatedTriples.cpp b/src/index/LocatedTriples.cpp index 51638175de..8e5f9bca50 100644 --- a/src/index/LocatedTriples.cpp +++ b/src/index/LocatedTriples.cpp @@ -82,10 +82,10 @@ auto tieHelper(Row& row, Tp) { // `numIndexColumns` and `includeGraphColumn`. For example, if `numIndexColumns` // is `2` and `includeGraphColumn` is `true`, the function returns // `std::tie(row[0], row[1], row[2])`. -CPP_template(size_t numIndexColumns, bool includeGraphColumn, - typename T)(requires(numIndexColumns >= 1 && - numIndexColumns <= - 3)) auto tieIdTableRow(T& row) { +CPP_template( + size_t numIndexColumns, bool includeGraphColumn, + typename T) (requires(numIndexColumns >= 1 && numIndexColumns <= 3)) +auto tieIdTableRow(T& row) { return tieHelper( row, std::make_index_sequence(includeGraphColumn)>{}); @@ -105,10 +105,10 @@ static constexpr auto tieLocatedTriplesIndices = []() { } return a; }(); -CPP_template(size_t numIndexColumns, bool includeGraphColumn, - typename T)(requires(numIndexColumns >= 1 && - numIndexColumns <= - 3)) auto tieLocatedTriple(T& lt) { +CPP_template( + size_t numIndexColumns, bool includeGraphColumn, + typename T) (requires(numIndexColumns >= 1 && numIndexColumns <= 3)) +auto tieLocatedTriple(T& lt) { auto& ids = lt->triple_.ids(); return tieHelper( ids, diff --git a/src/index/StringSortComparator.h b/src/index/StringSortComparator.h index d176541bd4..4f727d2fc5 100644 --- a/src/index/StringSortComparator.h +++ b/src/index/StringSortComparator.h @@ -56,8 +56,9 @@ class LocaleManager { using U8String = std::basic_string; using U8StringView = std::basic_string_view; - CPP_template(typename T)(requires ad_utility::SimilarToAny< - T, U8String, U8StringView>) class SortKeyImpl { + CPP_template( + typename T) (requires ad_utility::SimilarToAny) + class SortKeyImpl { public: SortKeyImpl() = default; explicit SortKeyImpl(U8StringView sortKey) : sortKey_(sortKey) {} @@ -185,9 +186,9 @@ class LocaleManager { // clang-format off CPP_template(typename F)( requires ranges::invocable) - // clang-format on - void getSortKey(std::string_view s, const Level level, - F resultFunction) const { + // clang-format on + void getSortKey(std::string_view s, const Level level, + F resultFunction) const { // TODO This function is one of the bottlenecks of the first pass // of the IndexBuilder One possible improvement is to reuse the memory // allocations for the `sortKeyBuffer`. diff --git a/src/index/TextIndexReadWrite.h b/src/index/TextIndexReadWrite.h index 04fcd2c739..cc54abc7c2 100644 --- a/src/index/TextIndexReadWrite.h +++ b/src/index/TextIndexReadWrite.h @@ -342,10 +342,9 @@ class FrequencyEncode { // .cpp file when using this specific requires clause. To circumvent this the // requires clause is kept only in the .h file and the constructor calls the // initialize function which has no direct requires clause. - CPP_template(typename View)(requires( - !ranges::same_as< - FrequencyEncode, - ql::remove_cvref_t>)) explicit FrequencyEncode(View&& view) { + CPP_template(typename View) ( + requires(!ranges::same_as>)) + explicit FrequencyEncode(View&& view) { initialize(std::forward(view)); }; @@ -396,9 +395,9 @@ class GapEncode { // .cpp file when using this specific requires clause. To circumvent this the // requires clause is kept only in the .h file and the constructor calls the // initialize function which has no direct requires clause. - CPP_template(typename View)(requires( - !ranges::same_as>)) explicit GapEncode(View&& view) { + CPP_template( + typename View) (requires(!ranges::same_as>)) + explicit GapEncode(View&& view) { initialize(std::forward(view)); }; diff --git a/src/index/VocabularyMerger.h b/src/index/VocabularyMerger.h index 90bdb04977..ec4f690170 100644 --- a/src/index/VocabularyMerger.h +++ b/src/index/VocabularyMerger.h @@ -178,8 +178,8 @@ struct VocabularyMetaData { template auto mergeVocabulary(const std::string& basename, size_t numFiles, W comparator, C& wordCallback, ad_utility::MemorySize memoryToUse) - -> CPP_ret(VocabularyMetaData)( - requires WordComparator&& WordCallback); + -> CPP_ret( + VocabularyMetaData)(requires WordComparator && WordCallback); // A helper class that implements the `mergeVocabulary` function (see // above). Everything in this class is private and only the @@ -201,8 +201,8 @@ class VocabularyMerger { friend auto mergeVocabulary(const std::string& basename, size_t numFiles, W comparator, C& wordCallback, ad_utility::MemorySize memoryToUse) - -> CPP_ret(VocabularyMetaData)( - requires WordComparator&& WordCallback); + -> CPP_ret( + VocabularyMetaData)(requires WordComparator && WordCallback); VocabularyMerger() = default; // _______________________________________________________________ @@ -211,9 +211,7 @@ class VocabularyMerger { template auto mergeVocabulary(const std::string& basename, size_t numFiles, W comparator, C& wordCallback, - ad_utility::MemorySize memoryToUse) - -> CPP_ret(VocabularyMetaData)( - requires WordComparator&& WordCallback); + ad_utility::MemorySize memoryToUse) -> CPP_ret(VocabularyMetaData)(requires WordComparator && WordCallback); // Helper `struct` for a word from a partial vocabulary. struct QueueWord { @@ -249,10 +247,10 @@ class VocabularyMerger { CPP_template(typename C, typename L)( requires WordCallback CPP_and ranges::predicate< L, TripleComponentWithIndex, TripleComponentWithIndex>) - // clang-format on - void writeQueueWordsToIdMap(const std::vector& buffer, - C& wordCallback, const L& lessThan, - ad_utility::ProgressBar& progressBar); + // clang-format on + void writeQueueWordsToIdMap(const std::vector& buffer, + C& wordCallback, const L& lessThan, + ad_utility::ProgressBar& progressBar); // Close all associated files and file-based vectors and reset all internal // variables. diff --git a/src/index/VocabularyMergerImpl.h b/src/index/VocabularyMergerImpl.h index 0587b91e30..c665d7f3ca 100644 --- a/src/index/VocabularyMergerImpl.h +++ b/src/index/VocabularyMergerImpl.h @@ -38,9 +38,8 @@ namespace ad_utility::vocabulary_merger { template auto mergeVocabulary(const std::string& basename, size_t numFiles, W comparator, C& internalWordCallback, - ad_utility::MemorySize memoryToUse) - -> CPP_ret(VocabularyMetaData)( - requires WordComparator&& WordCallback) { + ad_utility::MemorySize memoryToUse) -> CPP_ret(VocabularyMetaData)(requires WordComparator && WordCallback) +{ VocabularyMerger merger; return merger.mergeVocabulary(basename, numFiles, std::move(comparator), internalWordCallback, memoryToUse); @@ -52,8 +51,9 @@ auto VocabularyMerger::mergeVocabulary(const std::string& basename, size_t numFiles, W comparator, C& wordCallback, ad_utility::MemorySize memoryToUse) - -> CPP_ret(VocabularyMetaData)( - requires WordComparator&& WordCallback) { + -> CPP_ret( + VocabularyMetaData)(requires WordComparator && WordCallback) +{ // Return true iff p1 >= p2 according to the lexicographic order of the IRI // or literal. auto lessThan = [&comparator](const TripleComponentWithIndex& t1, @@ -149,13 +149,13 @@ auto VocabularyMerger::mergeVocabulary(const std::string& basename, } // ________________________________________________________________________________ -CPP_template_def(typename C, typename L)( - requires WordCallback CPP_and_def - ranges::predicate) void VocabularyMerger:: - writeQueueWordsToIdMap(const std::vector& buffer, - C& wordCallback, const L& lessThan, - ad_utility::ProgressBar& progressBar) { +CPP_template_def( + typename C, + typename L)(requires WordCallback CPP_and_def ranges::predicate< + L, TripleComponentWithIndex, TripleComponentWithIndex>) +void VocabularyMerger::writeQueueWordsToIdMap( + const std::vector& buffer, C& wordCallback, const L& lessThan, + ad_utility::ProgressBar& progressBar) { AD_LOG_TIMING << "Start writing a batch of merged words\n"; // Smaller grained buffer for the actual inner write. @@ -332,10 +332,9 @@ inline ItemVec vocabMapsToVector(ItemMapArray& map) { futures.push_back( std::async(std::launch::async, [&singleMap, &els, &offsets, i] { using T = ItemVec::value_type; - ql::ranges::transform(singleMap.map_, els.begin() + offsets[i], - [](auto& el) -> T { - return {el.first, std::move(el.second)}; - }); + ql::ranges::transform( + singleMap.map_, els.begin() + offsets[i], + [](auto& el) -> T { return {el.first, std::move(el.second)}; }); })); ++i; } diff --git a/src/index/vocabulary/CompressedVocabulary.h b/src/index/vocabulary/CompressedVocabulary.h index d3cd4e8640..6ecb0b1cc0 100644 --- a/src/index/vocabulary/CompressedVocabulary.h +++ b/src/index/vocabulary/CompressedVocabulary.h @@ -36,9 +36,9 @@ CPP_concept IterableVocabulary = CPP_template(typename UnderlyingVocabulary, typename CompressionWrapper = ad_utility::vocabulary::FsstSquaredCompressionWrapper, - size_t NumWordsPerBlock = 1UL << 20)( - requires ad_utility::vocabulary::CompressionWrapper< - CompressionWrapper>) class CompressedVocabulary { + size_t NumWordsPerBlock = 1UL << 20) ( + requires ad_utility::vocabulary::CompressionWrapper) +class CompressedVocabulary { private: UnderlyingVocabulary underlyingVocabulary_; CompressionWrapper compressionWrapper_; diff --git a/src/libqlever/LibQLeverExample.cpp b/src/libqlever/LibQLeverExample.cpp index d66ce851dc..534c94e2e8 100644 --- a/src/libqlever/LibQLeverExample.cpp +++ b/src/libqlever/LibQLeverExample.cpp @@ -49,8 +49,7 @@ int main(int argc, char** argv) { std::cout << std::endl; // Execute query. - std::cout << "\x1b[1mExecuting test query" - << "\x1b[0m" << std::endl; + std::cout << "\x1b[1mExecuting test query" << "\x1b[0m" << std::endl; std::string queryResult; ad_utility::Timer timer{ad_utility::Timer::Started}; try { diff --git a/src/parser/LiteralOrIri.h b/src/parser/LiteralOrIri.h index f7d6d993bb..20a96c953a 100644 --- a/src/parser/LiteralOrIri.h +++ b/src/parser/LiteralOrIri.h @@ -62,9 +62,9 @@ class alignas(16) LiteralOrIri { return LiteralOrIri{Iri::fromStringRepresentation(std::move(internal))}; } } - CPP_template(typename H, typename L)( - requires ql::concepts::same_as) friend H - AbslHashValue(H h, const L& literalOrIri) { + CPP_template(typename H, + typename L) (requires ql::concepts::same_as) + friend H AbslHashValue(H h, const L& literalOrIri) { return H::combine(std::move(h), literalOrIri.data_); } diff --git a/src/parser/ParallelParseBuffer.h b/src/parser/ParallelParseBuffer.h index 5ab5b49bf1..57bb3433eb 100644 --- a/src/parser/ParallelParseBuffer.h +++ b/src/parser/ParallelParseBuffer.h @@ -65,9 +65,10 @@ class ParserBatcher { } } - CPP_member auto getBatch() - -> CPP_ret(std::optional>)( - requires ad_utility::detail::ParserGetBatch) { + CPP_member auto getBatch() -> CPP_ret( + std::optional>)(requires ad_utility::detail::ParserGetBatch) + { if (m_numTriplesAlreadyParsed >= m_maxNumTriples) { return std::nullopt; } diff --git a/src/parser/PropertyPath.h b/src/parser/PropertyPath.h index 08fa199863..7534068980 100644 --- a/src/parser/PropertyPath.h +++ b/src/parser/PropertyPath.h @@ -142,16 +142,15 @@ class PropertyPath { // Process the path with the given functions. The functions are called // depending on which internal representation this instance has. CPP_template(typename T, typename IriFunc, typename ModifiedPathFunc, - typename MinMaxPathFunc)( - requires ad_utility::InvocableWithConvertibleReturnType< - IriFunc, T, const ad_utility::triple_component::Iri&> - CPP_and ad_utility::InvocableWithConvertibleReturnType< - ModifiedPathFunc, T, const std::vector&, Modifier> - CPP_and ad_utility::InvocableWithConvertibleReturnType< - MinMaxPathFunc, T, const PropertyPath&, size_t, size_t>) T - handlePath(const IriFunc& iriFunc, - const ModifiedPathFunc& modifiedPathFunc, - const MinMaxPathFunc& minMaxPathFunc) const { + typename MinMaxPathFunc) ( + requires ad_utility::InvocableWithConvertibleReturnType< + IriFunc, T, const ad_utility::triple_component::Iri&> + CPP_and ad_utility::InvocableWithConvertibleReturnType< + ModifiedPathFunc, T, const std::vector&, Modifier> + CPP_and ad_utility::InvocableWithConvertibleReturnType< + MinMaxPathFunc, T, const PropertyPath&, size_t, size_t>) + T handlePath(const IriFunc& iriFunc, const ModifiedPathFunc& modifiedPathFunc, + const MinMaxPathFunc& minMaxPathFunc) const { return std::visit( ad_utility::OverloadCallOperator{ iriFunc, diff --git a/src/parser/RdfParser.h b/src/parser/RdfParser.h index e6415d4084..fd3184ce40 100644 --- a/src/parser/RdfParser.h +++ b/src/parser/RdfParser.h @@ -410,9 +410,9 @@ class NQuadParser : public TurtleParser { * Parses turtle from std::string. Used to perform unit tests for * the different parser rules */ -CPP_template(typename Parser)(requires ql::concepts::derived_from< - Parser, RdfParserBase>) class RdfStringParser - : public Parser { +CPP_template( + typename Parser) (requires ql::concepts::derived_from) +class RdfStringParser : public Parser { public: using Parser::getLine; using Parser::prefixMap_; diff --git a/src/parser/TripleComponent.h b/src/parser/TripleComponent.h index 05f572dc3a..797a50f9b9 100644 --- a/src/parser/TripleComponent.h +++ b/src/parser/TripleComponent.h @@ -70,11 +70,11 @@ class TripleComponent { TripleComponent() = default; /// Construct from anything that is able to construct the underlying /// `Variant`. - CPP_template(typename FirstArg, typename... Args)( - requires CPP_NOT(ql::concepts::same_as, - TripleComponent>) && - std::is_constructible_v) - TripleComponent(FirstArg&& firstArg, Args&&... args) + CPP_template(typename FirstArg, typename... Args) ( + requires CPP_NOT(ql::concepts::same_as, + TripleComponent>) && + std::is_constructible_v) + TripleComponent(FirstArg&& firstArg, Args&&... args) : _variant(AD_FWD(firstArg), AD_FWD(args)...) { if (isString()) { // Storing variables and literals as strings is deprecated. The following @@ -98,9 +98,8 @@ class TripleComponent { /// Assignment for types that can be directly assigned to the underlying /// variant. - CPP_template(typename T)(requires std::is_assignable_v) - TripleComponent& - operator=(T&& value) { + CPP_template(typename T) (requires std::is_assignable_v) + TripleComponent& operator=(T&& value) { _variant = AD_FWD(value); checkThatStringIsValid(); return *this; @@ -118,9 +117,8 @@ class TripleComponent { TripleComponent& operator=(TripleComponent&&) = default; /// Make a `TripleComponent` directly comparable to the underlying types. - CPP_template(typename T)( - requires ad_utility::SameAsAnyTypeIn) bool - operator==(const T& other) const { + CPP_template(typename T) (requires ad_utility::SameAsAnyTypeIn) + bool operator==(const T& other) const { auto ptr = std::get_if(&_variant); return ptr && *ptr == other; } @@ -133,9 +131,10 @@ class TripleComponent { /// this overload would also be eligible for the contained types that are /// implicitly convertible to `TripleComponent` which would lead to strange /// bugs. - CPP_template(typename H, typename TC)( - requires ql::concepts::same_as) friend H - AbslHashValue(H h, const TC& tc) { + CPP_template( + typename H, + typename TC) (requires ql::concepts::same_as) + friend H AbslHashValue(H h, const TC& tc) { return H::combine(std::move(h), tc._variant); } diff --git a/src/parser/data/Literal.h b/src/parser/data/Literal.h index 28255f9175..44bfc808ee 100644 --- a/src/parser/data/Literal.h +++ b/src/parser/data/Literal.h @@ -17,9 +17,8 @@ class Literal { std::string _stringRepresentation; - CPP_template_2(typename T)( - requires ad_utility::Streamable) static std::string - toString(const T& t) { + CPP_template_2(typename T)(requires ad_utility::Streamable) + static std::string toString(const T& t) { std::ostringstream stream; stream << t; return std::move(stream).str(); @@ -31,8 +30,9 @@ class Literal { public: CPP_template_2(typename T)( - requires CPP_NOT(ql::concepts::same_as, Literal>) - CPP_and_2 ad_utility::Streamable) explicit Literal(T&& t) + requires CPP_NOT(ql::concepts::same_as, Literal>) + CPP_and_2 ad_utility::Streamable) + explicit Literal(T&& t) : _stringRepresentation(toString(std::forward(t))) {} explicit Literal(std::variant t) { diff --git a/src/parser/sparqlParser/SparqlQleverVisitor.cpp b/src/parser/sparqlParser/SparqlQleverVisitor.cpp index 620aa66d8d..1b5b6c015f 100644 --- a/src/parser/sparqlParser/SparqlQleverVisitor.cpp +++ b/src/parser/sparqlParser/SparqlQleverVisitor.cpp @@ -3046,20 +3046,18 @@ GraphTerm Visitor::visit(Parser::BlankNodeContext* ctx) { } // ____________________________________________________________________________________ -CPP_template_def(typename Ctx)( - requires Visitor::voidWhenVisited) void Visitor:: - visitVector(const std::vector& childContexts) { +CPP_template_def(typename Ctx)(requires Visitor::voidWhenVisited) +void Visitor::visitVector(const std::vector& childContexts) { for (const auto& child : childContexts) { visit(child); } } // ____________________________________________________________________________________ -CPP_template_def(typename Ctx)( - requires CPP_NOT(Visitor::voidWhenVisited)) - [[nodiscard]] auto Visitor::visitVector( - const std::vector& childContexts) - -> std::vector { +CPP_template_def( + typename Ctx)(requires CPP_NOT(Visitor::voidWhenVisited)) +[[nodiscard]] auto Visitor::visitVector(const std::vector& childContexts) + -> std::vector { std::vector children; for (const auto& child : childContexts) { children.emplace_back(visit(child)); @@ -3102,8 +3100,8 @@ void Visitor::visitIf(Target* target, Ctx* ctx) { } // _____________________________________________________________________________ -CPP_template_def(typename Ctx)(requires Visitor::voidWhenVisited< - Visitor, Ctx>) void Visitor::visitIf(Ctx* ctx) { +CPP_template_def(typename Ctx)(requires Visitor::voidWhenVisited) +void Visitor::visitIf(Ctx* ctx) { if (ctx) { visit(ctx); } diff --git a/src/parser/sparqlParser/SparqlQleverVisitor.h b/src/parser/sparqlParser/SparqlQleverVisitor.h index 631526abd7..5bea128286 100644 --- a/src/parser/sparqlParser/SparqlQleverVisitor.h +++ b/src/parser/sparqlParser/SparqlQleverVisitor.h @@ -625,17 +625,15 @@ class SparqlQleverVisitor { std::array{std::move(children)...}); } - CPP_template(typename Ctx)( - requires SparqlQleverVisitor::voidWhenVisited< - SparqlQleverVisitor, Ctx>) void visitVector(const std::vector& - childContexts); + CPP_template(typename Ctx) ( + requires SparqlQleverVisitor::voidWhenVisited) + void visitVector(const std::vector& childContexts); // Call `visit` for each of the `childContexts` and return the results of // those calls as a `vector`. - CPP_template(typename Ctx)(requires CPP_NOT( - SparqlQleverVisitor::voidWhenVisited< - SparqlQleverVisitor, Ctx>)) auto visitVector(const std::vector& - childContexts) + CPP_template(typename Ctx) (requires CPP_NOT( + SparqlQleverVisitor::voidWhenVisited)) + auto visitVector(const std::vector& childContexts) -> std::vector; // Check that exactly one of the `ctxs` is not `null`, visit that context, @@ -659,8 +657,9 @@ class SparqlQleverVisitor { template void visitIf(Target* target, Ctx* ctx); - CPP_template(typename Ctx)(requires SparqlQleverVisitor::voidWhenVisited< - SparqlQleverVisitor, Ctx>) void visitIf(Ctx* ctx); + CPP_template(typename Ctx) ( + requires SparqlQleverVisitor::voidWhenVisited) + void visitIf(Ctx* ctx); public: [[noreturn]] static void reportError(const antlr4::ParserRuleContext* ctx, diff --git a/src/rdfTypes/GeoPoint.h b/src/rdfTypes/GeoPoint.h index 972ef7dccb..1388ad6d3b 100644 --- a/src/rdfTypes/GeoPoint.h +++ b/src/rdfTypes/GeoPoint.h @@ -43,8 +43,8 @@ class GeoPoint { using T = uint64_t; CPP_template(typename H, - typename G)(requires ql::concepts::same_as) friend H - AbslHashValue(H h, const G& g) { + typename G) (requires ql::concepts::same_as) + friend H AbslHashValue(H h, const G& g) { return H::combine(std::move(h), g.lat_, g.lng_); } diff --git a/src/rdfTypes/GeometryInfo.cpp b/src/rdfTypes/GeometryInfo.cpp index 3ada0767ec..d5681f94d4 100644 --- a/src/rdfTypes/GeometryInfo.cpp +++ b/src/rdfTypes/GeometryInfo.cpp @@ -247,7 +247,7 @@ std::optional GeometryInfo::getNumGeometries( // ____________________________________________________________________________ CPP_template_def(typename RequestedInfo)(requires RequestedInfoT) - RequestedInfo GeometryInfo::getRequestedInfo() const { +RequestedInfo GeometryInfo::getRequestedInfo() const { if constexpr (std::is_same_v) { return *this; } else if constexpr (std::is_same_v) { @@ -278,8 +278,8 @@ template MetricArea GeometryInfo::getRequestedInfo() const; // ____________________________________________________________________________ CPP_template_def(typename RequestedInfo)(requires RequestedInfoT) - std::optional GeometryInfo::getRequestedInfo( - std::string_view wkt) { +std::optional GeometryInfo::getRequestedInfo( + std::string_view wkt) { if constexpr (std::is_same_v) { return GeometryInfo::fromWktLiteral(wkt); } else if constexpr (std::is_same_v) { diff --git a/src/rdfTypes/GeometryInfo.h b/src/rdfTypes/GeometryInfo.h index 6e3d5454cd..19c68ad253 100644 --- a/src/rdfTypes/GeometryInfo.h +++ b/src/rdfTypes/GeometryInfo.h @@ -243,14 +243,14 @@ class GeometryInfo { const std::string_view& wkt); // Extract the requested information from this object. - CPP_template(typename RequestedInfo = GeometryInfo)( - requires RequestedInfoT) RequestedInfo - getRequestedInfo() const; + CPP_template(typename RequestedInfo = + GeometryInfo) (requires RequestedInfoT) + RequestedInfo getRequestedInfo() const; // Parse the given WKT literal and compute only the requested information. - CPP_template(typename RequestedInfo = GeometryInfo)( - requires RequestedInfoT) static std:: - optional getRequestedInfo(std::string_view wkt); + CPP_template(typename RequestedInfo = + GeometryInfo) (requires RequestedInfoT) + static std::optional getRequestedInfo(std::string_view wkt); }; // For the disk serialization we require that a `GeometryInfo` is trivially diff --git a/src/rdfTypes/GeometryInfoHelpersImpl.h b/src/rdfTypes/GeometryInfoHelpersImpl.h index 9d96638dc0..7eab100745 100644 --- a/src/rdfTypes/GeometryInfoHelpersImpl.h +++ b/src/rdfTypes/GeometryInfoHelpersImpl.h @@ -299,10 +299,10 @@ struct MetricLengthVisitor { // Compute the length of a multi-geometry by adding up the lengths of its // members. - CPP_template(typename T)(requires ad_utility::SimilarToAny< - T, MultiLine, MultiPolygon, - MultiPoint, Collection>) double - operator()(const T& multiGeom) const { + CPP_template(typename T) (requires ad_utility::SimilarToAny< + T, MultiLine, MultiPolygon, + MultiPoint, Collection>) + double operator()(const T& multiGeom) const { // This overload only handles the geometry types implemented by vectors. static_assert(ad_utility::similarToInstantiation); @@ -312,9 +312,9 @@ struct MetricLengthVisitor { // Compute the length for the custom container type `AnyGeometry` from // `pb_util`. It can dynamically hold any geometry type. - CPP_template(typename T)( - requires ad_utility::SimilarTo>) double - operator()(const T& geom) const { + CPP_template( + typename T) (requires ad_utility::SimilarTo>) + double operator()(const T& geom) const { using enum AnyGeometryMember; // `AnyGeometry` is a class from `pb_util`. It does not operate on an enum, // this is why we use our own enum here. The correct matching of the integer @@ -413,10 +413,10 @@ struct MetricAreaVisitor { } // The remaining geometry types always return the area zero - CPP_template(typename T)( - requires SameAsAny, MultiPoint, - Line, MultiLine>) double - operator()(const T&) const { + CPP_template( + typename T) (requires SameAsAny, MultiPoint, + Line, MultiLine>) + double operator()(const T&) const { return 0.0; } diff --git a/src/rdfTypes/Iri.h b/src/rdfTypes/Iri.h index 2d46533879..bada7aced7 100644 --- a/src/rdfTypes/Iri.h +++ b/src/rdfTypes/Iri.h @@ -33,9 +33,8 @@ class Iri { public: // A default constructed IRI is empty. Iri() = default; - CPP_template(typename H, - typename I)(requires ql::concepts::same_as) friend H - AbslHashValue(H h, const I& iri) { + CPP_template(typename H, typename I) (requires ql::concepts::same_as) + friend H AbslHashValue(H h, const I& iri) { return H::combine(std::move(h), iri.iri_); } diff --git a/src/rdfTypes/Literal.h b/src/rdfTypes/Literal.h index 61608d31dd..2ab2a71221 100644 --- a/src/rdfTypes/Literal.h +++ b/src/rdfTypes/Literal.h @@ -45,8 +45,8 @@ class Literal { public: CPP_template(typename H, - typename L)(requires ql::concepts::same_as) friend H - AbslHashValue(H h, const L& literal) { + typename L) (requires ql::concepts::same_as) + friend H AbslHashValue(H h, const L& literal) { return H::combine(std::move(h), literal.content_); } QL_DEFINE_DEFAULTED_EQUALITY_OPERATOR_LOCAL(Literal, content_, beginOfSuffix_) diff --git a/src/rdfTypes/Variable.cpp b/src/rdfTypes/Variable.cpp index e77e113a93..33c8222d08 100644 --- a/src/rdfTypes/Variable.cpp +++ b/src/rdfTypes/Variable.cpp @@ -113,8 +113,8 @@ namespace { struct IsVariableVisitor { using VarContext = SparqlAutomaticParser::VarContext*; bool visit(VarContext) { return true; } - CPP_template(typename T)( - requires(!ad_utility::SimilarTo)) bool visit(T) { + CPP_template(typename T) (requires(!ad_utility::SimilarTo)) + bool visit(T) { return false; } }; diff --git a/src/util/Algorithm.h b/src/util/Algorithm.h index 024c8f42b8..0fbe6fbfe2 100644 --- a/src/util/Algorithm.h +++ b/src/util/Algorithm.h @@ -80,10 +80,9 @@ bool contains_if(const Container& container, const Predicate& predicate) { * @param destination Vector& to which to append * @param source Vector&& to append */ -CPP_template(typename T, typename U)( - requires ad_utility::SimilarTo< - std::vector, U>) void appendVector(std::vector& destination, - U&& source) { +CPP_template(typename T, + typename U) (requires ad_utility::SimilarTo, U>) +void appendVector(std::vector& destination, U&& source) { destination.insert(destination.end(), ad_utility::makeForwardingIterator(source.begin()), ad_utility::makeForwardingIterator(source.end())); @@ -153,10 +152,9 @@ std::vector flatten(std::vector>&& input) { // used to keep track of which values we have already seen. One of these // copies could be avoided, but our current uses of this function are // currently not at all performance-critical (small `input` and small `T`). -CPP_template(typename Range)(requires ql::ranges::forward_range< - Range>) auto removeDuplicates(const Range& input) - -> std::vector>::value_type> { +CPP_template(typename Range) (requires ql::ranges::forward_range) +auto removeDuplicates(const Range& input) -> std::vector< + typename std::iterator_traits>::value_type> { using T = typename std::iterator_traits>::value_type; std::vector result; @@ -172,13 +170,11 @@ CPP_template(typename Range)(requires ql::ranges::forward_range< // Return a new `std::input` that is obtained by applying the `function` to each // of the elements of the `input`. -CPP_template(typename Array, typename Function)( - requires ad_utility::isArray> CPP_and - ql::concepts::invocable< - Function, - typename Array::value_type>) auto transformArray(Array&& input, - Function - function) { +CPP_template( + typename Array, + typename Function) (requires ad_utility::isArray> CPP_and + ql::concepts::invocable) +auto transformArray(Array&& input, Function function) { return std::apply( [&function](auto&&... vals) { return std::array{std::invoke(function, AD_FWD(vals))...}; @@ -190,11 +186,12 @@ CPP_template(typename Array, typename Function)( // but an iterator (first argument) and a value (second argument). The // implementation is copied from libstdc++ which has this function as an // internal detail, but doesn't expose it to the outside. -CPP_template(typename ForwardIterator, typename Tp, - typename Compare)(requires ql::concepts::forward_iterator< - ForwardIterator>) constexpr ForwardIterator - lower_bound_iterator(ForwardIterator first, ForwardIterator last, - const Tp& val, Compare comp) { +CPP_template( + typename ForwardIterator, typename Tp, + typename Compare) (requires ql::concepts::forward_iterator) +constexpr ForwardIterator lower_bound_iterator(ForwardIterator first, + ForwardIterator last, + const Tp& val, Compare comp) { using DistanceType = typename std::iterator_traits::difference_type; @@ -218,11 +215,12 @@ CPP_template(typename ForwardIterator, typename Tp, // but a value (first argument) and an iterator (second argument). The // implementation is copied from libstdc++ which has this function as an // internal detail, but doesn't expose it to the outside. -CPP_template(typename ForwardIterator, typename Tp, - typename Compare)(requires ql::concepts::forward_iterator< - ForwardIterator>) constexpr ForwardIterator - upper_bound_iterator(ForwardIterator first, ForwardIterator last, - const Tp& val, Compare comp) { +CPP_template( + typename ForwardIterator, typename Tp, + typename Compare) (requires ql::concepts::forward_iterator) +constexpr ForwardIterator upper_bound_iterator(ForwardIterator first, + ForwardIterator last, + const Tp& val, Compare comp) { using DistanceType = typename std::iterator_traits::difference_type; diff --git a/src/util/AllocatorWithLimit.h b/src/util/AllocatorWithLimit.h index c0e79227d4..06dc58c9a7 100644 --- a/src/util/AllocatorWithLimit.h +++ b/src/util/AllocatorWithLimit.h @@ -173,8 +173,8 @@ class AllocatorWithLimit { } AllocatorWithLimit() = delete; - CPP_template(typename U)(requires(!ql::concepts::same_as)) - AllocatorWithLimit(const AllocatorWithLimit& other) + CPP_template(typename U) (requires(!ql::concepts::same_as)) + AllocatorWithLimit(const AllocatorWithLimit& other) : memoryLeft_{other.getMemoryLeft()}, clearOnAllocation_(other.clearOnAllocation()) {} diff --git a/src/util/AsioHelpers.h b/src/util/AsioHelpers.h index 8d30dad878..30206c52c8 100644 --- a/src/util/AsioHelpers.h +++ b/src/util/AsioHelpers.h @@ -28,8 +28,8 @@ namespace detail { // the associated executor of the `handler`, or to the `executor` if no such // associated executor exists. CPP_template(typename Executor, typename Function, - typename Handler)(requires ql::concepts::invocable< - Function>) struct CallFunctionAndPassToHandler { + typename Handler) (requires ql::concepts::invocable) +struct CallFunctionAndPassToHandler { Executor executor_; Function function_; Handler handler_; @@ -73,12 +73,12 @@ CPP_template(typename Executor, typename Function, }; // Explicit deduction guides, we need objects and not references as the template // parameters. -CPP_template(typename Executor, typename Function, typename Handler)( - requires ql::concepts::invocable>) - CallFunctionAndPassToHandler(Executor&&, Function&&, Handler&&) - -> CallFunctionAndPassToHandler, - std::decay_t, - std::decay_t>; +CPP_template( + typename Executor, typename Function, + typename Handler) (requires ql::concepts::invocable>) +CallFunctionAndPassToHandler(Executor&&, Function&&, Handler&&) + -> CallFunctionAndPassToHandler< + std::decay_t, std::decay_t, std::decay_t>; } // namespace detail // Run the `function` on the `executor` (e.g. a strand for synchronization or @@ -88,14 +88,13 @@ CPP_template(typename Executor, typename Function, typename Handler)( // Note: If no executor is associated with the `completionToken`, then the // handler will also be run on the `executor` that is passed to this function as // there is no other way of running it. -CPP_template(typename Executor, typename CompletionToken, typename Function)( - requires ql::concepts::invocable CPP_and( - std::is_default_constructible_v> || - std::is_void_v>)) auto runFunctionOnExecutor(Executor executor, - Function function, - CompletionToken& - completionToken) { +CPP_template( + typename Executor, typename CompletionToken, + typename Function) (requires ql::concepts::invocable CPP_and( + std::is_default_constructible_v> || + std::is_void_v>)) +auto runFunctionOnExecutor(Executor executor, Function function, + CompletionToken& completionToken) { using Value = std::invoke_result_t; static constexpr bool isVoid = std::is_void_v; diff --git a/src/util/BlankNodeManager.h b/src/util/BlankNodeManager.h index b780de256e..36439ceb27 100644 --- a/src/util/BlankNodeManager.h +++ b/src/util/BlankNodeManager.h @@ -91,8 +91,8 @@ class BlankNodeManager { // Merge passed `LocalBlankNodeManager`s to keep alive their reserved // BlankNodeIndex blocks. - CPP_template(typename R)(requires ql::ranges::range) void mergeWith( - const R& localBlankNodeManagers) { + CPP_template(typename R) (requires ql::ranges::range) + void mergeWith(const R& localBlankNodeManagers) { auto inserter = std::back_inserter(otherBlocks_); for (const auto& l : localBlankNodeManagers) { if (l == nullptr) { diff --git a/src/util/Cache.h b/src/util/Cache.h index 38a12cfbd3..f709fed8fd 100644 --- a/src/util/Cache.h +++ b/src/util/Cache.h @@ -442,8 +442,10 @@ struct timeUpdater { } // namespace detail /// A LRU cache using the HeapBasedCache -CPP_template(typename Key, typename Value, typename ValueSizeGetterT)( - requires ValueSizeGetter) class HeapBasedLRUCache +CPP_template( + typename Key, typename Value, + typename ValueSizeGetterT) (requires ValueSizeGetter) +class HeapBasedLRUCache : public HeapBasedCache, detail::timeUpdater, detail::timeAsScore, ValueSizeGetterT> { @@ -461,8 +463,10 @@ CPP_template(typename Key, typename Value, typename ValueSizeGetterT)( }; /// A LRU cache using the TreeBasedCache -CPP_template(typename Key, typename Value, typename ValueSizeGetterT)( - requires ValueSizeGetter) class TreeBasedLRUCache +CPP_template( + typename Key, typename Value, + typename ValueSizeGetterT) (requires ValueSizeGetter) +class TreeBasedLRUCache : public ad_utility::TreeBasedCache, detail::timeUpdater, detail::timeAsScore, ValueSizeGetterT> { @@ -480,13 +484,13 @@ CPP_template(typename Key, typename Value, typename ValueSizeGetterT)( /// typedef for the simple name LRUCache that is fixed to one of the possible /// implementations at compile time #ifdef _QLEVER_USE_TREE_BASED_CACHE -CPP_template(typename Key, typename Value, typename ValueSizeGetterT)( - requires ValueSizeGetter) using LRUCache = - TreeBasedLRUCache; +CPP_template(typename Key, typename Value, typename ValueSizeGetterT) (requires ValueSizeGetter) +using LRUCache = TreeBasedLRUCache; #else -CPP_template(typename Key, typename Value, typename ValueSizeGetterT)( - requires ValueSizeGetter) using LRUCache = - HeapBasedLRUCache; +CPP_template( + typename Key, typename Value, + typename ValueSizeGetterT) (requires ValueSizeGetter) +using LRUCache = HeapBasedLRUCache; #endif } // namespace ad_utility diff --git a/src/util/CancellationHandle.cpp b/src/util/CancellationHandle.cpp index 8b8f05b559..9895147eb9 100644 --- a/src/util/CancellationHandle.cpp +++ b/src/util/CancellationHandle.cpp @@ -21,8 +21,9 @@ void CancellationHandle::cancel( // _____________________________________________________________________________ template -CPP_member_def auto CancellationHandle::startWatchDogInternal() - -> CPP_ret(void)(requires WatchDogEnabled) { +CPP_member_def auto CancellationHandle::startWatchDogInternal() -> CPP_ret( + void)(requires WatchDogEnabled) +{ using enum CancellationState; std::unique_lock lock{watchDogState_.mutex_}; // This function is only supposed to be run once. @@ -65,7 +66,8 @@ void CancellationHandle::startWatchDog() { // _____________________________________________________________________________ template CPP_member_def auto CancellationHandle::setStatePreservingCancel( - CancellationState newState) -> CPP_ret(void)(requires CancellationEnabled) { + CancellationState newState) -> CPP_ret(void)(requires CancellationEnabled) +{ CancellationState state = cancellationState_.load(std::memory_order_relaxed); while (!detail::isCancelled(state)) { if (cancellationState_.compare_exchange_weak(state, newState, diff --git a/src/util/CancellationHandle.h b/src/util/CancellationHandle.h index dadba891dc..db21ddd9fa 100644 --- a/src/util/CancellationHandle.h +++ b/src/util/CancellationHandle.h @@ -156,15 +156,13 @@ class CancellationHandle { /// in the console that would otherwise be triggered by the watchdog. /// NOTE: The parameter state is expected to be one of `CHECK_WINDOW_MISSED` /// or `WAITING_FOR_CHECK`, otherwise it will violate the correctness check. - CPP_template(typename StateFunc)( - requires WatchDogEnabled CPP_and - ad_utility::InvocableWithConvertibleReturnType< - StateFunc, - std::string_view>) void pleaseWatchDog(CancellationState state, - ad_utility::source_location - location, - const StateFunc& - stageInvocable) { + CPP_template( + typename StateFunc) (requires WatchDogEnabled CPP_and + ad_utility::InvocableWithConvertibleReturnType< + StateFunc, std::string_view>) + void pleaseWatchDog(CancellationState state, + ad_utility::source_location location, + const StateFunc& stageInvocable) { using DurationType = std::remove_const_t; AD_CORRECTNESS_CHECK(!detail::isCancelled(state) && @@ -203,14 +201,13 @@ class CancellationHandle { /// Internal function that starts the watch dog. It will set this /// `CancellationHandle` instance into a state that will log a warning in the /// console if `throwIfCancelled` is not called frequently enough. - CPP_member auto startWatchDogInternal() - -> CPP_ret(void)(requires WatchDogEnabled); + CPP_member auto startWatchDogInternal() -> CPP_ret( + void)(requires WatchDogEnabled); /// Helper function that sets the internal state atomically given that it has /// not been cancelled yet. Otherwise no-op. /// CPP_member auto - CPP_member auto setStatePreservingCancel(CancellationState newState) - -> CPP_ret(void)(requires CancellationEnabled); + CPP_member auto setStatePreservingCancel(CancellationState newState) -> CPP_ret(void)(requires CancellationEnabled); public: /// Sets the cancellation flag so the next call to throwIfCancelled will @@ -221,12 +218,14 @@ class CancellationHandle { /// nothing otherwise. If `WatchDogEnabled` is true, this will log a warning /// if this check is not called frequently enough. It will contain the /// filename and line of the caller of this method. - CPP_template(typename Func = decltype(detail::printNothing))( - requires ad_utility::InvocableWithConvertibleReturnType< - Func, std::string_view>) AD_ALWAYS_INLINE - void throwIfCancelled([[maybe_unused]] ad_utility::source_location - location = AD_CURRENT_SOURCE_LOC(), - const Func& stageInvocable = detail::printNothing) { + CPP_template( + typename Func = + decltype(detail::printNothing)) (requires ad_utility::InvocableWithConvertibleReturnType< + Func, std::string_view>) + AD_ALWAYS_INLINE void throwIfCancelled( + [[maybe_unused]] ad_utility::source_location location = + AD_CURRENT_SOURCE_LOC(), + const Func& stageInvocable = detail::printNothing) { if constexpr (CancellationEnabled) { auto state = cancellationState_.load(std::memory_order_relaxed); if (state == CancellationState::NOT_CANCELLED) [[likely]] { diff --git a/src/util/ChunkedForLoop.h b/src/util/ChunkedForLoop.h index 5904f1facc..2df2a7da48 100644 --- a/src/util/ChunkedForLoop.h +++ b/src/util/ChunkedForLoop.h @@ -45,12 +45,12 @@ CPP_concept IteratorAction = /// the next iteration, similar to the break keyword. `chunkOperation` is called /// every `CHUNK_SIZE` iteration steps, and at least a single time at the end if /// the range is not empty. -CPP_template(std::size_t CHUNK_SIZE, typename Action, typename ChunkOpT)( - requires detail::IteratorAction CPP_and ql::concepts::invocable< - ChunkOpT>) inline void chunkedForLoop(std::size_t start, - std::size_t end, - const Action& action, - const ChunkOpT& chunkOperation) { +CPP_template(std::size_t CHUNK_SIZE, typename Action, + typename ChunkOpT) (requires detail::IteratorAction CPP_and + ql::concepts::invocable) +inline void chunkedForLoop(std::size_t start, std::size_t end, + const Action& action, + const ChunkOpT& chunkOperation) { static_assert(CHUNK_SIZE != 0, "Chunk size must be non-zero"); using std::size_t; while (start < end) { @@ -75,16 +75,14 @@ CPP_concept SizedInputRange = // Similar to `ql::ranges::copy`, but invokes `chunkOperation` every // `chunkSize` elements. (Round up to the next chunk size if the range size is // not a multiple of `chunkSize`.) -CPP_template(typename R, typename O, typename ChunkOperationFunc)( - requires SizedInputRange CPP_and ql::concepts::weakly_incrementable - CPP_and ql::concepts::invocable - CPP_and ql::concepts::indirectly_copyable< - ql::ranges::iterator_t, - O>) inline void chunkedCopy(R&& inputRange, O result, - ql::ranges::range_difference_t - chunkSize, - const ChunkOperationFunc& - chunkOperation) { +CPP_template(typename R, typename O, typename ChunkOperationFunc) ( + requires SizedInputRange CPP_and ql::concepts::weakly_incrementable + CPP_and ql::concepts::invocable + CPP_and ql::concepts::indirectly_copyable< + ql::ranges::iterator_t, O>) +inline void chunkedCopy(R&& inputRange, O result, + ql::ranges::range_difference_t chunkSize, + const ChunkOperationFunc& chunkOperation) { auto begin = ql::ranges::begin(inputRange); auto end = ql::ranges::end(inputRange); auto target = result; @@ -106,15 +104,13 @@ CPP_concept SizedOutputRange = // Similar to `ql::ranges::fill`, but invokes `chunkOperation` every // `chunkSize` elements. (Round up to the next chunk size if the range size is // not a multiple of `chunkSize`.) -CPP_template(typename T, typename R, typename ChunkOperationFunc)( - requires SizedOutputRange CPP_and ql::concepts::invocable< - ChunkOperationFunc>) inline void chunkedFill(R&& outputRange, - const T& value, - ql::ranges:: - range_difference_t - chunkSize, - const ChunkOperationFunc& - chunkOperation) { +CPP_template( + typename T, typename R, + typename ChunkOperationFunc) (requires SizedOutputRange CPP_and + ql::concepts::invocable) +inline void chunkedFill(R&& outputRange, const T& value, + ql::ranges::range_difference_t chunkSize, + const ChunkOperationFunc& chunkOperation) { auto begin = ql::ranges::begin(outputRange); auto end = ql::ranges::end(outputRange); while (ql::ranges::distance(begin, end) >= chunkSize) { diff --git a/src/util/ComparisonWithNan.h b/src/util/ComparisonWithNan.h index 87346af06f..d7bb5a84de 100644 --- a/src/util/ComparisonWithNan.h +++ b/src/util/ComparisonWithNan.h @@ -28,11 +28,11 @@ namespace ad_utility { // see the corresponding tests which contain all relevant corner cases. template inline auto makeComparatorForNans(Comparator comparator) { - return [comparator](const auto& a, const auto& b) - -> CPP_ret(bool)( - requires std::is_invocable_r_v, - std::decay_t>) { + return [comparator](const auto& a, const auto& b) -> CPP_ret( + bool)(requires std::is_invocable_r_v, + std::decay_t>) + { auto isNan = [](const auto& t) { using T = std::decay_t; if constexpr (std::is_floating_point_v) { diff --git a/src/util/CompressionUsingZstd/ZstdWrapper.h b/src/util/CompressionUsingZstd/ZstdWrapper.h index ed9ae410ed..1081caeca6 100644 --- a/src/util/CompressionUsingZstd/ZstdWrapper.h +++ b/src/util/CompressionUsingZstd/ZstdWrapper.h @@ -25,10 +25,9 @@ class ZstdWrapper { // Decompress the given byte array, assuming that the size of the decompressed // data is known. - CPP_template(typename T)( - requires(std::is_trivially_copyable_v< - T>)) static std::vector decompress(void* src, size_t numBytes, - size_t knownOriginalSize) { + CPP_template(typename T) (requires(std::is_trivially_copyable_v)) + static std::vector decompress(void* src, size_t numBytes, + size_t knownOriginalSize) { knownOriginalSize *= sizeof(T); std::vector result(knownOriginalSize / sizeof(T)); auto compressedSize = @@ -39,10 +38,9 @@ class ZstdWrapper { // Decompress the given byte array to the given buffer of the given size, // returning the number of bytes of the decompressed data. - CPP_template(typename T)( - requires(std::is_trivially_copyable_v)) static size_t - decompressToBuffer(const char* src, size_t numBytes, T* buffer, - size_t bufferCapacity) { + CPP_template(typename T) (requires(std::is_trivially_copyable_v)) + static size_t decompressToBuffer(const char* src, size_t numBytes, T* buffer, + size_t bufferCapacity) { auto decompressedSize = ZSTD_decompress(buffer, bufferCapacity, src, numBytes); if (ZSTD_isError(decompressedSize)) { diff --git a/src/util/ConcurrentCache.h b/src/util/ConcurrentCache.h index fc0d8b9d51..e6ebf2829d 100644 --- a/src/util/ConcurrentCache.h +++ b/src/util/ConcurrentCache.h @@ -158,9 +158,9 @@ class ConcurrentCache { ConcurrentCache() = default; /// Constructor: all arguments are forwarded to the underlying cache type. - CPP_template(typename CacheArg, typename... CacheArgs)(requires( - !ql::concepts::same_as>)) - ConcurrentCache(CacheArg&& cacheArg, CacheArgs&&... cacheArgs) + CPP_template(typename CacheArg, typename... CacheArgs) (requires( + !ql::concepts::same_as>)) + ConcurrentCache(CacheArg&& cacheArg, CacheArgs&&... cacheArgs) : _cacheAndInProgressMap{AD_FWD(cacheArg), AD_FWD(cacheArgs)...} {} struct ResultAndCacheStatus { @@ -185,26 +185,29 @@ class ConcurrentCache { * @return A `ResultAndCacheStatus` shared_ptr to the computation result. * */ - CPP_template_2(typename ComputeFuncT, typename SuitabilityFuncT)( - requires InvocableWithConvertibleReturnType CPP_and_2 - InvocableWithConvertibleReturnType) ResultAndCacheStatus - computeOnce(const Key& key, const ComputeFuncT& computeFunction, - bool onlyReadFromCache, - const SuitabilityFuncT& suitableForCache) { + CPP_template_2( + typename ComputeFuncT, + typename SuitabilityFuncT)(requires InvocableWithConvertibleReturnType + CPP_and_2 InvocableWithConvertibleReturnType< + SuitabilityFuncT, bool, const Value&>) + ResultAndCacheStatus computeOnce(const Key& key, + const ComputeFuncT& computeFunction, + bool onlyReadFromCache, + const SuitabilityFuncT& suitableForCache) { return computeOnceImpl(false, key, computeFunction, onlyReadFromCache, suitableForCache); } /// Similar to computeOnce, with the following addition: After the call /// completes, the result will be pinned in the underlying cache. - CPP_template_2(typename ComputeFuncT, typename SuitabilityFuncT)( - requires InvocableWithConvertibleReturnType CPP_and_2 - InvocableWithConvertibleReturnType) ResultAndCacheStatus - computeOncePinned(const Key& key, const ComputeFuncT& computeFunction, - bool onlyReadFromCache, - const SuitabilityFuncT& suitedForCache) { + CPP_template_2( + typename ComputeFuncT, + typename SuitabilityFuncT)(requires InvocableWithConvertibleReturnType + CPP_and_2 InvocableWithConvertibleReturnType< + SuitabilityFuncT, bool, const Value&>) + ResultAndCacheStatus computeOncePinned( + const Key& key, const ComputeFuncT& computeFunction, + bool onlyReadFromCache, const SuitabilityFuncT& suitedForCache) { return computeOnceImpl(true, key, computeFunction, onlyReadFromCache, suitedForCache); } @@ -212,14 +215,15 @@ class ConcurrentCache { // If the result is contained in the cache, read and return it. Otherwise, // compute it, but do not store it in the cache. The interface is the same as // for the above two functions, therefore some of the arguments are unused. - CPP_template_2(typename ComputeFuncT, typename SuitabilityFuncT)( - requires InvocableWithConvertibleReturnType CPP_and_2 - InvocableWithConvertibleReturnType) ResultAndCacheStatus - computeButDontStore( - const Key& key, const ComputeFuncT& computeFunction, - bool onlyReadFromCache, - [[maybe_unused]] const SuitabilityFuncT& suitedForCache) { + CPP_template_2( + typename ComputeFuncT, + typename SuitabilityFuncT)(requires InvocableWithConvertibleReturnType + CPP_and_2 InvocableWithConvertibleReturnType< + SuitabilityFuncT, bool, const Value&>) + ResultAndCacheStatus computeButDontStore( + const Key& key, const ComputeFuncT& computeFunction, + bool onlyReadFromCache, + [[maybe_unused]] const SuitabilityFuncT& suitedForCache) { { auto resultPtr = _cacheAndInProgressMap.wlock()->_cache[key]; if (resultPtr != nullptr) { @@ -337,10 +341,12 @@ class ConcurrentCache { _inProgress; CacheAndInProgressMap() = default; - CPP_template_2(typename Arg, typename... Args)(requires( - !ql::concepts::same_as, CacheAndInProgressMap>)) - QL_EXPLICIT(sizeof...(Args) > 0) - CacheAndInProgressMap(Arg&& arg, Args&&... args) + CPP_template_2( + typename Arg, + typename... Args)(requires(!ql::concepts::same_as, + CacheAndInProgressMap>)) + QL_EXPLICIT(sizeof...(Args) > 0) + CacheAndInProgressMap(Arg&& arg, Args&&... args) : _cache{AD_FWD(arg), AD_FWD(args)...} {} }; @@ -367,14 +373,14 @@ class ConcurrentCache { private: // implementation for computeOnce (pinned and normal variant). - CPP_template_2(typename ComputeFuncT, typename SuitabilityFuncT)( - requires InvocableWithConvertibleReturnType CPP_and_2 - InvocableWithConvertibleReturnType) ResultAndCacheStatus - computeOnceImpl(bool pinned, const Key& key, - const ComputeFuncT& computeFunction, - bool onlyReadFromCache, - const SuitabilityFuncT& suitableForCache) { + CPP_template_2( + typename ComputeFuncT, + typename SuitabilityFuncT)(requires InvocableWithConvertibleReturnType + CPP_and_2 InvocableWithConvertibleReturnType< + SuitabilityFuncT, bool, const Value&>) + ResultAndCacheStatus computeOnceImpl( + bool pinned, const Key& key, const ComputeFuncT& computeFunction, + bool onlyReadFromCache, const SuitabilityFuncT& suitableForCache) { using std::make_shared; using std::shared_ptr; bool mustCompute; diff --git a/src/util/ConfigManager/ConfigManager.cpp b/src/util/ConfigManager/ConfigManager.cpp index 1995ed2a5f..d8f232e34b 100644 --- a/src/util/ConfigManager/ConfigManager.cpp +++ b/src/util/ConfigManager/ConfigManager.cpp @@ -48,10 +48,9 @@ ConfigManager::HashMapEntry::HashMapEntry(Data&& data) : data_{std::make_unique(std::move(data))} {} // ____________________________________________________________________________ -CPP_template_def(typename T)( - requires SameAsAnyTypeIn< - T, ConfigManager::HashMapEntry::Data>) bool ConfigManager:: - HashMapEntry::implHolds() const { +CPP_template_def( + typename T)(requires SameAsAnyTypeIn) +bool ConfigManager::HashMapEntry::implHolds() const { // Make sure, that it is not a null pointer. AD_CORRECTNESS_CHECK(data_); @@ -70,12 +69,13 @@ bool ConfigManager::HashMapEntry::holdsSubManager() const { // ____________________________________________________________________________ CPP_template_def(typename ReturnType, typename InstanceType)( - requires SimilarToAnyTypeIn - CPP_and_def std::is_object_v - CPP_and_def ad_utility::SimilarTo) - std::optional ConfigManager::HashMapEntry:: - getConfigOptionOrSubManager(InstanceType& instance) { + requires SimilarToAnyTypeIn + CPP_and_def std::is_object_v + CPP_and_def ad_utility::SimilarTo) +std::optional +ConfigManager::HashMapEntry::getConfigOptionOrSubManager( + InstanceType& instance) { using DecayReturnType = std::decay_t; /* We cheat a bit, by using `implHolds`, because so we can reduce the amount @@ -112,31 +112,32 @@ std::optional ConfigManager::HashMapEntry::getSubManager() } // ____________________________________________________________________________ -CPP_template_def(typename Visitor)( - requires ql::concepts::invocable CPP_and_def - ql::concepts::invocable) decltype(auto) - ConfigManager::HashMapEntry::visit(Visitor&& vis) { +CPP_template_def( + typename Visitor)(requires ql::concepts::invocable CPP_and_def + ql::concepts::invocable) +decltype(auto) ConfigManager::HashMapEntry::visit(Visitor&& vis) { return visitImpl(AD_FWD(vis), data_); } -CPP_template_def(typename Visitor)( - requires ql::concepts::invocable CPP_and_def - ql::concepts::invocable) decltype(auto) - ConfigManager::HashMapEntry::visit(Visitor&& vis) const { +CPP_template_def( + typename Visitor)(requires ql::concepts::invocable CPP_and_def + ql::concepts::invocable) +decltype(auto) ConfigManager::HashMapEntry::visit(Visitor&& vis) const { return visitImpl(AD_FWD(vis), data_); } // ____________________________________________________________________________ CPP_template_def(typename Visitor, typename PointerType)( - requires ad_utility::SimilarTo< - std::unique_ptr, PointerType> - CPP_and_def ql::concepts::invocable< - Visitor, std::conditional_t, - const ConfigOption&, ConfigOption&>> - CPP_and_def ql::concepts::invocable< - Visitor, std::conditional_t, - const ConfigManager&, - ConfigManager&>>) decltype(auto) - ConfigManager::HashMapEntry::visitImpl(Visitor&& vis, PointerType& data) { + requires ad_utility::SimilarTo< + std::unique_ptr, PointerType> + CPP_and_def ql::concepts::invocable< + Visitor, std::conditional_t, + const ConfigOption&, ConfigOption&>> + CPP_and_def ql::concepts::invocable< + Visitor, + std::conditional_t, + const ConfigManager&, ConfigManager&>>) +decltype(auto) ConfigManager::HashMapEntry::visitImpl(Visitor&& vis, + PointerType& data) { // Make sure, that it is not a null pointer. AD_CORRECTNESS_CHECK(data); @@ -157,14 +158,13 @@ void ConfigManager::verifyHashMapEntry(std::string_view jsonPathToEntry, } // ____________________________________________________________________________ -CPP_template_def(typename Visitor)( - requires ad_utility::InvocableWithExactReturnType< - Visitor, void, std::string_view, ConfigManager&> - CPP_and_def ad_utility::InvocableWithExactReturnType< - Visitor, void, std::string_view, - ConfigOption&>) void ConfigManager:: - visitHashMapEntries(Visitor&& vis, bool sortByCreationOrder, - std::string_view pathPrefix) const { +CPP_template_def( + typename Visitor)(requires ad_utility::InvocableWithExactReturnType< + Visitor, void, std::string_view, ConfigManager&> + CPP_and_def ad_utility::InvocableWithExactReturnType< + Visitor, void, std::string_view, ConfigOption&>) +void ConfigManager::visitHashMapEntries(Visitor&& vis, bool sortByCreationOrder, + std::string_view pathPrefix) const { // For less code duplication. using Pair = decltype(configurationOptions_)::value_type; @@ -196,18 +196,19 @@ CPP_template_def(typename Visitor)( } // ____________________________________________________________________________ -CPP_template_def(typename HashMapType, typename Callable)( - requires SimilarTo< - ad_utility::HashMap, - HashMapType> - CPP_and_def std::is_object_v) auto ConfigManager:: - allHashMapEntries(HashMapType& hashMap, std::string_view pathPrefix, - const Callable& predicate) - -> std::conditional_t< - std::is_const_v, - const std::vector< - std::pair>, - std::vector>> { +CPP_template_def( + typename HashMapType, + typename Callable)(requires SimilarTo< + ad_utility::HashMap, + HashMapType> + CPP_and_def std::is_object_v) +auto ConfigManager::allHashMapEntries(HashMapType& hashMap, + std::string_view pathPrefix, + const Callable& predicate) + -> std::conditional_t< + std::is_const_v, + const std::vector>, + std::vector>> { std::conditional_t< std::is_const_v, std::vector>, @@ -265,12 +266,12 @@ CPP_template_def(typename HashMapType, typename Callable)( // ____________________________________________________________________________ CPP_template_def(typename ConfigOptions, typename ReturnReference)( - requires SameAsAny - CPP_and_def SimilarTo< - ad_utility::HashMap, - ConfigOptions>) - std::vector> ConfigManager:: - configurationOptionsImpl(ConfigOptions& configurationOptions) { + requires SameAsAny + CPP_and_def SimilarTo< + ad_utility::HashMap, + ConfigOptions>) +std::vector> +ConfigManager::configurationOptionsImpl(ConfigOptions& configurationOptions) { return ad_utility::transform( allHashMapEntries( configurationOptions, "", @@ -872,10 +873,9 @@ bool ConfigManager::containsOption(const ConfigOption& opt) const { } // ____________________________________________________________________________ -CPP_template_def(typename T)( - requires ConfigOptionOrManager) void ConfigManager:: - ConfigurationDocValidatorAssignment::addEntryUnderKey( - const T& key, const ConfigOptionValidatorManager& manager) { +CPP_template_def(typename T)(requires ConfigOptionOrManager) +void ConfigManager::ConfigurationDocValidatorAssignment::addEntryUnderKey( + const T& key, const ConfigOptionValidatorManager& manager) { getHashMapBasedOnType()[&key].push_back(&manager); } // Explicit instantiation for `ConfigOption` and `ConfigManager`. @@ -887,10 +887,9 @@ template void ConfigManager::ConfigurationDocValidatorAssignment:: const ConfigOptionValidatorManager&); // ____________________________________________________________________________ -CPP_template_def(typename T)( - requires ConfigOptionOrManager) auto ConfigManager:: - ConfigurationDocValidatorAssignment::getEntriesUnderKey(const T& key) const - -> ValueGetterReturnType { +CPP_template_def(typename T)(requires ConfigOptionOrManager) +auto ConfigManager::ConfigurationDocValidatorAssignment::getEntriesUnderKey( + const T& key) const -> ValueGetterReturnType { // The concerned hash map. const MemoryAdressHashMap& hashMap{getHashMapBasedOnType()}; diff --git a/src/util/ConfigManager/ConfigManager.h b/src/util/ConfigManager/ConfigManager.h index 47b74297bd..5a4172dcb4 100644 --- a/src/util/ConfigManager/ConfigManager.h +++ b/src/util/ConfigManager/ConfigManager.h @@ -91,19 +91,19 @@ class ConfigManager { size_t getInitializationId() const; // Wrapper for calling `std::visit` on the saved `Data`. - CPP_template(typename Visitor)( - requires ql::concepts::invocable CPP_and - ql::concepts::invocable) decltype(auto) - visit(Visitor&& vis); - CPP_template(typename Visitor)( - requires ql::concepts::invocable CPP_and - ql::concepts::invocable) decltype(auto) - visit(Visitor&& vis) const; + CPP_template( + typename Visitor) (requires ql::concepts::invocable CPP_and + ql::concepts::invocable) + decltype(auto) visit(Visitor&& vis); + CPP_template( + typename Visitor) (requires ql::concepts::invocable CPP_and + ql::concepts::invocable) + decltype(auto) visit(Visitor&& vis) const; private: // Implementation for `holdsConfigOption` and `holdsSubManager`. - CPP_template(typename T)( - requires SameAsAnyTypeIn) bool implHolds() const; + CPP_template(typename T) (requires SameAsAnyTypeIn) + bool implHolds() const; /* @brief Implementation for `getConfigOption` and `getSubManager`. You can @@ -115,30 +115,29 @@ class ConfigManager { @SameAsAnym instance The `HashMapEntry` you want this from. */ - CPP_template(typename ReturnType, typename InstanceType)( - requires SimilarToAnyTypeIn CPP_and - std::is_object_v - CPP_and ad_utility::SimilarTo) static std:: - optional getConfigOptionOrSubManager( - InstanceType& instance); + CPP_template(typename ReturnType, typename InstanceType) ( + requires SimilarToAnyTypeIn CPP_and + std::is_object_v + CPP_and ad_utility::SimilarTo) + static std::optional getConfigOptionOrSubManager( + InstanceType& instance); /* @brief The implementation for `visit`. Follows the same signature as `std::variant::visit`: */ - CPP_template(typename Visitor, typename PointerType)( - requires ad_utility::SimilarTo< - std::unique_ptr, PointerType> - CPP_and ql::concepts::invocable< - Visitor, std::conditional_t, - const ConfigOption&, ConfigOption&>> - CPP_and ql::concepts::invocable< - Visitor, - std::conditional_t, - const ConfigManager&, - ConfigManager&>>) static decltype(auto) - visitImpl(Visitor&& vis, PointerType& data); + CPP_template(typename Visitor, typename PointerType) ( + requires ad_utility::SimilarTo< + std::unique_ptr, PointerType> + CPP_and ql::concepts::invocable< + Visitor, + std::conditional_t, + const ConfigOption&, ConfigOption&>> + CPP_and ql::concepts::invocable< + Visitor, + std::conditional_t, + const ConfigManager&, ConfigManager&>>) + static decltype(auto) visitImpl(Visitor&& vis, PointerType& data); }; /* @@ -180,12 +179,12 @@ class ConfigManager { @return A reference to the newly created configuration option. This reference will stay valid, even after adding more options. */ - CPP_template(typename OptionType)( - requires SupportedConfigOptionType) - ConstConfigOptionProxy addOption( - const std::vector& pathToOption, - std::string_view optionDescription, - OptionType* variableToPutValueOfTheOptionIn) { + CPP_template( + typename OptionType) (requires SupportedConfigOptionType) + ConstConfigOptionProxy addOption( + const std::vector& pathToOption, + std::string_view optionDescription, + OptionType* variableToPutValueOfTheOptionIn) { return addOptionImpl(pathToOption, optionDescription, variableToPutValueOfTheOptionIn, std::optional(std::nullopt)); @@ -209,14 +208,16 @@ class ConfigManager { @return A reference to the newly created configuration option. This reference will stay valid, even after adding more options. */ - CPP_template(typename OptionType, typename DefaultValueType = OptionType)( - requires SupportedConfigOptionType CPP_and - ql::concepts::same_as) - ConstConfigOptionProxy addOption( - const std::vector& pathToOption, - std::string_view optionDescription, - OptionType* variableToPutValueOfTheOptionIn, - DefaultValueType defaultValue) { + CPP_template( + typename OptionType, + typename DefaultValueType = + OptionType) (requires SupportedConfigOptionType CPP_and + ql::concepts::same_as) + ConstConfigOptionProxy addOption( + const std::vector& pathToOption, + std::string_view optionDescription, + OptionType* variableToPutValueOfTheOptionIn, + DefaultValueType defaultValue) { return addOptionImpl(pathToOption, optionDescription, variableToPutValueOfTheOptionIn, std::optional(std::move(defaultValue))); @@ -230,11 +231,11 @@ class ConfigManager { @return A reference to the newly created configuration option. This reference will stay valid, even after adding more options. */ - CPP_template(typename OptionType)( - requires SupportedConfigOptionType) - ConstConfigOptionProxy addOption( - std::string optionName, std::string_view optionDescription, - OptionType* variableToPutValueOfTheOptionIn) { + CPP_template( + typename OptionType) (requires SupportedConfigOptionType) + ConstConfigOptionProxy addOption( + std::string optionName, std::string_view optionDescription, + OptionType* variableToPutValueOfTheOptionIn) { return addOption( std::vector{std::move(optionName)}, optionDescription, variableToPutValueOfTheOptionIn); @@ -248,13 +249,15 @@ class ConfigManager { @return A reference to the newly created configuration option. This reference will stay valid, even after adding more options. */ - CPP_template(typename OptionType, typename DefaultValueType = OptionType)( - requires SupportedConfigOptionType CPP_and - ql::concepts::same_as) - ConstConfigOptionProxy addOption( - std::string optionName, std::string_view optionDescription, - OptionType* variableToPutValueOfTheOptionIn, - DefaultValueType defaultValue) { + CPP_template( + typename OptionType, + typename DefaultValueType = + OptionType) (requires SupportedConfigOptionType CPP_and + ql::concepts::same_as) + ConstConfigOptionProxy addOption( + std::string optionName, std::string_view optionDescription, + OptionType* variableToPutValueOfTheOptionIn, + DefaultValueType defaultValue) { return addOption( std::vector{std::move(optionName)}, optionDescription, variableToPutValueOfTheOptionIn, std::move(defaultValue)); @@ -325,17 +328,14 @@ class ConfigManager { values will be passed to the validator function as function arguments. Will keep the same order. */ - CPP_template(typename ValidatorFunc, typename... ValidatorParameterTypes)( - requires(sizeof...(ValidatorParameterTypes) > 0) CPP_and ValidatorFunction< - ValidatorFunc, - ValidatorParameterTypes...>) void addValidator(ValidatorFunc - validatorFunction, - std::string - errorMessage, - std::string - validatorDescriptor, - ConstConfigOptionProxy< - ValidatorParameterTypes>... configOptionsToBeChecked) { + CPP_template( + typename ValidatorFunc, + typename... ValidatorParameterTypes) (requires(sizeof...(ValidatorParameterTypes) > 0) CPP_and + ValidatorFunction) + void addValidator(ValidatorFunc validatorFunction, std::string errorMessage, + std::string validatorDescriptor, + ConstConfigOptionProxy< + ValidatorParameterTypes>... configOptionsToBeChecked) { addValidatorImpl( "addValidator", [](auto opt) { @@ -367,15 +367,15 @@ class ConfigManager { arguments. Will keep the same order. */ CPP_template(typename ExceptionalValidatorFunc, - typename... ExceptionValidatorParameterTypes)( - requires(sizeof...(ExceptionValidatorParameterTypes) > 0) CPP_and ExceptionValidatorFunction< - ExceptionalValidatorFunc, - ExceptionValidatorParameterTypes...>) void addValidator(ExceptionalValidatorFunc - exceptionValidatorFunction, - std::string - exceptionValidatorDescriptor, - ConstConfigOptionProxy< - ExceptionValidatorParameterTypes>... configOptionsToBeChecked) { + typename... ExceptionValidatorParameterTypes) ( + requires(sizeof...(ExceptionValidatorParameterTypes) > 0) + CPP_and ExceptionValidatorFunction< + ExceptionalValidatorFunc, ExceptionValidatorParameterTypes...>) + void addValidator( + ExceptionalValidatorFunc exceptionValidatorFunction, + std::string exceptionValidatorDescriptor, + ConstConfigOptionProxy< + ExceptionValidatorParameterTypes>... configOptionsToBeChecked) { addValidatorImpl( "addValidator", [](auto opt) { @@ -400,16 +400,16 @@ class ConfigManager { will be passed to the validator function as function arguments. Will keep the same order. */ - CPP_template(typename ValidatorFunc, typename... ConfigOptions)(requires( - sizeof...(ConfigOptions) > - 0)) auto addOptionValidator(ValidatorFunc validatorFunction, - std::string errorMessage, - std::string validatorDescriptor, - ConfigOptions&&... configOptionsToBeChecked) - -> CPP_ret(void)( - requires(ValidatorFunction< - ValidatorFunc, - decltype(configOptionsToBeChecked.getConfigOption())...>)) { + CPP_template( + typename ValidatorFunc, + typename... ConfigOptions) (requires(sizeof...(ConfigOptions) > 0)) + auto addOptionValidator(ValidatorFunc validatorFunction, + std::string errorMessage, + std::string validatorDescriptor, + ConfigOptions&&... configOptionsToBeChecked) -> CPP_ret(void)(requires( + ValidatorFunction)) + { addValidatorImpl( "addOptionValidator", [](auto opt) { return opt.getConfigOption(); }, transformValidatorIntoExceptionValidator< @@ -433,17 +433,15 @@ class ConfigManager { will be passed to the validator function as function arguments. Will keep the same order. */ - CPP_template(typename ExceptionValidatorT, - typename... ConfigOptions)(requires( - sizeof...(ConfigOptions) > - 0)) auto addOptionValidator(ExceptionValidatorT - exceptionValidatorFunction, - std::string exceptionValidatorDescriptor, - ConfigOptions&&... configOptionsToBeChecked) - -> CPP_ret(void)( - requires(ExceptionValidatorFunction< - ExceptionValidatorT, - decltype(configOptionsToBeChecked.getConfigOption())...>)) { + CPP_template( + typename ExceptionValidatorT, + typename... ConfigOptions) (requires(sizeof...(ConfigOptions) > 0)) + auto addOptionValidator(ExceptionValidatorT exceptionValidatorFunction, + std::string exceptionValidatorDescriptor, + ConfigOptions&&... configOptionsToBeChecked) -> CPP_ret(void)(requires(ExceptionValidatorFunction< + ExceptionValidatorT, + decltype(configOptionsToBeChecked.getConfigOption())...>)) + { addValidatorImpl( "addOptionValidator", [](auto opt) { return opt.getConfigOption(); }, exceptionValidatorFunction, std::move(exceptionValidatorDescriptor), @@ -478,15 +476,13 @@ class ConfigManager { path, so that information will only be included in generated error messages, if you pass it along. */ - CPP_template(typename Visitor)( - requires ad_utility::InvocableWithExactReturnType< - Visitor, void, std::string_view, ConfigManager&> - CPP_and ad_utility::InvocableWithExactReturnType< - Visitor, void, std::string_view, - ConfigOption&>) void visitHashMapEntries(Visitor&& vis, - bool sortByCreationOrder, - std::string_view - pathPrefix) const; + CPP_template( + typename Visitor) (requires ad_utility::InvocableWithExactReturnType< + Visitor, void, std::string_view, ConfigManager&> + CPP_and ad_utility::InvocableWithExactReturnType< + Visitor, void, std::string_view, ConfigOption&>) + void visitHashMapEntries(Visitor&& vis, bool sortByCreationOrder, + std::string_view pathPrefix) const; /* @brief Collect all `HashMapEntry` contained in the `hashMap`, including the @@ -499,20 +495,17 @@ class ConfigManager { @param predicate Only the `HashMapEntry` for which a true is returned, will be given back. */ - CPP_template(typename HashMapType, typename Callable)( - requires SimilarTo, - HashMapType> - CPP_and std::is_object_v) static std:: - conditional_t< - std::is_const_v, - const std::vector>, - std::vector>> allHashMapEntries(HashMapType& - hashMap, - std::string_view - pathPrefix, - const Callable& - predicate); + CPP_template( + typename HashMapType, + typename Callable) (requires SimilarTo, + HashMapType> + CPP_and std::is_object_v) + static std::conditional_t< + std::is_const_v, + const std::vector>, + std::vector>> + allHashMapEntries(HashMapType& hashMap, std::string_view pathPrefix, + const Callable& predicate); /* @brief Creates the string representation of a valid `nlohmann::json` pointer @@ -565,14 +558,14 @@ class ConfigManager { @return A reference to the newly created configuration option. Will stay valid, even after more options. */ - CPP_template(typename OptionType)(requires ad_utility::SameAsAnyTypeIn< - OptionType, ConfigOption::AvailableTypes>) - ConstConfigOptionProxy addOptionImpl( - const std::vector& pathToOption, - std::string_view optionDescription, - OptionType* variableToPutValueOfTheOptionIn, - std::optional defaultValue = - std::optional(std::nullopt)) { + CPP_template(typename OptionType) (requires ad_utility::SameAsAnyTypeIn< + OptionType, ConfigOption::AvailableTypes>) + ConstConfigOptionProxy addOptionImpl( + const std::vector& pathToOption, + std::string_view optionDescription, + OptionType* variableToPutValueOfTheOptionIn, + std::optional defaultValue = + std::optional(std::nullopt)) { verifyPath(pathToOption); /* @@ -605,12 +598,12 @@ class ConfigManager { @tparam ReturnReference Should be either `ConfigOption&`, or `const ConfigOption&`. */ - CPP_template(typename ConfigOptions, typename ReturnReference)( - requires SameAsAny - CPP_and SimilarTo, - ConfigOptions>) static std:: - vector> configurationOptionsImpl( - ConfigOptions& configurationOptions); + CPP_template(typename ConfigOptions, typename ReturnReference) ( + requires SameAsAny + CPP_and SimilarTo, + ConfigOptions>) + static std::vector> + configurationOptionsImpl(ConfigOptions& configurationOptions); /* @brief Return all `ConfigOptionValidatorManager` held by this manager and its @@ -741,11 +734,9 @@ class ConfigManager { @brief Add a validator to the list of validators, that are assigned to a `ConfigOption`/`ConfigManager`. */ - CPP_template(typename T)( - requires ConfigOptionOrManager< - T>) void addEntryUnderKey(const T& key, - const ConfigOptionValidatorManager& - manager); + CPP_template(typename T) (requires ConfigOptionOrManager) + void addEntryUnderKey(const T& key, + const ConfigOptionValidatorManager& manager); /* @brief Retrieve the list of validators, that are assigned to a @@ -753,22 +744,21 @@ class ConfigManager { @returns If there is no entry for `Key`, return an empty `std::vector`. */ - CPP_template(typename T)(requires ConfigOptionOrManager) - ValueGetterReturnType getEntriesUnderKey(const T& key) const; + CPP_template(typename T) (requires ConfigOptionOrManager) + ValueGetterReturnType getEntriesUnderKey(const T& key) const; private: // Return either `configOption_` or `configManager_`, based on type. - CPP_template(typename T)(requires ConfigOptionOrManager) constexpr const - MemoryAdressHashMap& getHashMapBasedOnType() const { + CPP_template(typename T) (requires ConfigOptionOrManager) + constexpr const MemoryAdressHashMap& getHashMapBasedOnType() const { if constexpr (ql::concepts::same_as) { return configOption_; } else if constexpr (ql::concepts::same_as) { return configManager_; } } - CPP_template(typename T)( - requires ConfigOptionOrManager< - T>) constexpr MemoryAdressHashMap& getHashMapBasedOnType() { + CPP_template(typename T) (requires ConfigOptionOrManager) + constexpr MemoryAdressHashMap& getHashMapBasedOnType() { if constexpr (ql::concepts::same_as) { return configOption_; } else if constexpr (ql::concepts::same_as) { diff --git a/src/util/ConfigManager/ConfigOption.h b/src/util/ConfigManager/ConfigOption.h index 4e1b97a8a9..5e888f8e0b 100644 --- a/src/util/ConfigManager/ConfigOption.h +++ b/src/util/ConfigManager/ConfigOption.h @@ -93,9 +93,9 @@ class ConfigOption { bool wasSet() const; // Returns, if this configuration option holds values of the given type. - CPP_template(typename Type)( - requires ad_utility::SameAsAnyTypeIn< - Type, AvailableTypes>) constexpr bool holdsType() const { + CPP_template( + typename Type) (requires ad_utility::SameAsAnyTypeIn) + constexpr bool holdsType() const { return std::holds_alternative>(data_); } @@ -104,8 +104,9 @@ class ConfigOption { exception, should the given value have a different type, than what the configuration option was set to. */ - CPP_template(typename T)(requires ad_utility::SameAsAnyTypeIn< - T, AvailableTypes>) void setValue(const T& value) { + CPP_template( + typename T) (requires ad_utility::SameAsAnyTypeIn) + void setValue(const T& value) { // Only set the variable, that our internal pointer points to, if the given // value is of the right type. if (auto* data = std::get_if>(&data_); data != nullptr) { @@ -130,9 +131,9 @@ class ConfigOption { there is no default value, or `T` is the wrong type, then it will throw an exception. */ - CPP_template(typename T)( - requires ad_utility::SameAsAnyTypeIn) T - getDefaultValue() const { + CPP_template( + typename T) (requires ad_utility::SameAsAnyTypeIn) + T getDefaultValue() const { if (hasDefaultValue() && std::holds_alternative>(data_)) { return std::get>(data_).defaultValue_.value(); } else if (!hasDefaultValue()) { @@ -160,9 +161,9 @@ class ConfigOption { @brief Return the content of the variable, that the internal pointer points to. If `T` is the wrong type, then it will throw an exception. */ - CPP_template(typename T)( - requires ad_utility::SameAsAnyTypeIn) T - getValue() const { + CPP_template( + typename T) (requires ad_utility::SameAsAnyTypeIn) + T getValue() const { if (wasSet() && std::holds_alternative>(data_)) { return *(std::get>(data_).variablePointer_); } else if (!wasSet()) { @@ -217,11 +218,10 @@ class ConfigOption { @param defaultValue The optional default value. An empty `std::optional` is for no default value and a non empty for a default value. */ - CPP_template(typename T)( - requires ad_utility::SameAsAnyTypeIn) - ConfigOption(std::string_view identifier, std::string_view description, - T* variablePointer, - std::optional defaultValue = std::nullopt) + CPP_template( + typename T) (requires ad_utility::SameAsAnyTypeIn) + ConfigOption(std::string_view identifier, std::string_view description, + T* variablePointer, std::optional defaultValue = std::nullopt) : data_{Data{std::move(defaultValue), variablePointer}}, identifier_{identifier}, description_{description} { @@ -244,9 +244,9 @@ class ConfigOption { /* @brief Return the string representation/name of the type. */ - CPP_template(typename T)(requires ad_utility::SameAsAnyTypeIn< - T, AvailableTypes>) static std::string - availableTypesToString() { + CPP_template( + typename T) (requires ad_utility::SameAsAnyTypeIn) + static std::string availableTypesToString() { return availableTypesToString(T{}); } diff --git a/src/util/ConfigManager/ConfigOptionProxy.h b/src/util/ConfigManager/ConfigOptionProxy.h index a2d89341f6..45bffe567e 100644 --- a/src/util/ConfigManager/ConfigOptionProxy.h +++ b/src/util/ConfigManager/ConfigOptionProxy.h @@ -28,10 +28,11 @@ access to the referenced config option. @tparam ConfigOptionType The kind of config option, this proxy will reference to. Must be `ConfigOption`, or `const ConfigOption`. */ -CPP_template(typename T, typename ConfigOptionType)( - requires SupportedConfigOptionType CPP_and ad_utility::SameAsAny< - ConfigOptionType, ConfigOption, - const ConfigOption>) class ConfigOptionProxyImplementation { +CPP_template( + typename T, + typename ConfigOptionType) (requires SupportedConfigOptionType CPP_and ad_utility::SameAsAny< + ConfigOptionType, ConfigOption, const ConfigOption>) +class ConfigOptionProxyImplementation { ConfigOptionType* option_; public: diff --git a/src/util/ConfigManager/Validator.h b/src/util/ConfigManager/Validator.h index 6d2a053b4b..9970d00441 100644 --- a/src/util/ConfigManager/Validator.h +++ b/src/util/ConfigManager/Validator.h @@ -60,13 +60,10 @@ That is, instead of returning `bool`, it now returns @param errorMessage Content for `ErrorMessage`. */ -CPP_template(typename ValidatorFunc, typename... ValidatorParameterTypes)( - requires ValidatorFunction< - ValidatorFunc, - ValidatorParameterTypes...>) inline auto transformValidatorIntoExceptionValidator(ValidatorFunc - validatorFunction, - std::string - errorMessage) { +CPP_template(typename ValidatorFunc, typename... ValidatorParameterTypes) ( + requires ValidatorFunction) +inline auto transformValidatorIntoExceptionValidator( + ValidatorFunc validatorFunction, std::string errorMessage) { // The whole 'transformation' is simply a wrapper. return [validatorFunction = std::move(validatorFunction), errorMessage = ErrorMessage{std::move(errorMessage)}]( @@ -130,21 +127,22 @@ class ConfigOptionValidatorManager { will be passed to the exception validator function as function arguments, after being transformed. Will keep the same order. */ - CPP_template(typename TranslationFunction, typename ExceptionValidatorFunc, - typename... ExceptionValidatorParameterTypes)( - requires(...&& isInstantiation) - CPP_and(...&& ql::concepts::invocable< - TranslationFunction, const ExceptionValidatorParameterTypes>) - CPP_and ExceptionValidatorFunction< - ExceptionValidatorFunc, - std::invoke_result_t< - TranslationFunction, - const ExceptionValidatorParameterTypes>...>) - ConfigOptionValidatorManager( - ExceptionValidatorFunc exceptionValidatorFunction, - std::string descriptor, TranslationFunction translationFunction, - const ExceptionValidatorParameterTypes... configOptionsToBeChecked) + CPP_template( + typename TranslationFunction, typename ExceptionValidatorFunc, + typename... ExceptionValidatorParameterTypes) (requires(...&& isInstantiation) + CPP_and(... && ql::concepts::invocable< + TranslationFunction, + const ExceptionValidatorParameterTypes>) + CPP_and ExceptionValidatorFunction< + ExceptionValidatorFunc, + std::invoke_result_t< + TranslationFunction, + const ExceptionValidatorParameterTypes>...>) + ConfigOptionValidatorManager( + ExceptionValidatorFunc exceptionValidatorFunction, std::string descriptor, + TranslationFunction translationFunction, + const ExceptionValidatorParameterTypes... configOptionsToBeChecked) : descriptor_{std::move(descriptor)}, configOptionsToBeChecked_{ &configOptionsToBeChecked.getConfigOption()...} { @@ -197,21 +195,21 @@ class ConfigOptionValidatorManager { after being transformed. Will keep the same order. */ CPP_template(typename TranslationFunction, typename ValidatorFunc, - typename... ValidatorParameterTypes)( - requires(...&& isInstantiation) - CPP_and(... && - (ql::concepts::invocable)) - CPP_and(ValidatorFunction< - ValidatorFunc, - std::invoke_result_t...>) - CPP_and(sizeof...(ValidatorParameterTypes) > 0)) - ConfigOptionValidatorManager( - ValidatorFunc validatorFunction, std::string errorMessage, - std::string descriptor, TranslationFunction translationFunction, - const ValidatorParameterTypes... configOptionsToBeChecked) + typename... ValidatorParameterTypes) ( + requires(...&& isInstantiation) + CPP_and(... && + (ql::concepts::invocable)) + CPP_and(ValidatorFunction< + ValidatorFunc, + std::invoke_result_t...>) + CPP_and(sizeof...(ValidatorParameterTypes) > 0)) + ConfigOptionValidatorManager( + ValidatorFunc validatorFunction, std::string errorMessage, + std::string descriptor, TranslationFunction translationFunction, + const ValidatorParameterTypes... configOptionsToBeChecked) : ConfigOptionValidatorManager( transformValidatorIntoExceptionValidator< ValidatorFunc, diff --git a/src/util/ConstexprUtils.h b/src/util/ConstexprUtils.h index fe166001a4..a1976f496c 100644 --- a/src/util/ConstexprUtils.h +++ b/src/util/ConstexprUtils.h @@ -80,16 +80,15 @@ CPP_concept InvocableWithCase = // `function.operator()(args...)`. template struct ConstexprSwitch { - CPP_template(typename FuncType, typename ValueType, typename... Args)( - requires((sizeof...(Cases) == 0) || - ad_utility::SameAsAny) - CPP_and ql::concepts::equality_comparable_with - CPP_and InvocableWithCase - CPP_and(InvocableWithCase&&...)) constexpr auto - operator()(FuncType&& function, const ValueType& value, Args&&... args) const - -> decltype(auto) { + CPP_template(typename FuncType, typename ValueType, typename... Args) ( + requires((sizeof...(Cases) == 0) || + ad_utility::SameAsAny) + CPP_and ql::concepts::equality_comparable_with + CPP_and InvocableWithCase + CPP_and(InvocableWithCase && ...)) + constexpr auto operator()(FuncType&& function, const ValueType& value, + Args&&... args) const -> decltype(auto) { if (value == FirstCase) { return AD_FWD(function).template operator()(AD_FWD(args)...); } else if constexpr (sizeof...(Cases) > 0) { @@ -235,9 +234,10 @@ auto toIntegerSequenceRef() { // NumIntegers - 1 to an array of `NumIntegers` many integers that are each in // the range // `[0, ..., (maxValue)]` -CPP_template(typename Int, size_t NumIntegers)( - requires ql::concepts::integral) constexpr std:: - array integerToArray(Int value, Int numValues) { +CPP_template(typename Int, + size_t NumIntegers) (requires ql::concepts::integral) +constexpr std::array integerToArray(Int value, + Int numValues) { std::array res{}; for (auto& el : res | ql::views::reverse) { el = value % numValues; @@ -257,9 +257,9 @@ constexpr inline std::array integerToArrayStaticVar = // the type of `Upper`) that contains each // value from `[0, ..., Upper - 1] ^ Num` exactly once. `^` denotes the // cartesian power. -CPP_template(auto Upper, size_t Num)( - requires ql::concepts::integral< - decltype(Upper)>) constexpr auto cartesianPowerAsArray() { +CPP_template(auto Upper, + size_t Num) (requires ql::concepts::integral) +constexpr auto cartesianPowerAsArray() { using Int = decltype(Upper); constexpr auto numValues = pow(Upper, Num); std::array, numValues> arr{}; @@ -272,18 +272,17 @@ CPP_template(auto Upper, size_t Num)( // Store the result of `cartesianPowerAsArray()` from above in a `constexpr` // variable with linkage that can be used as a `const&` template parameter in // C++17 mode. -CPP_template(auto Upper, size_t Num)( - requires ql::concepts::integral< - decltype(Upper)>) constexpr auto cartesianPowerAsArrayVal = - cartesianPowerAsArray(); +CPP_template(auto Upper, + size_t Num) (requires ql::concepts::integral) +constexpr auto cartesianPowerAsArrayVal = cartesianPowerAsArray(); // Return a `ad_utility::ValueSequence` that contains each // value from `[0, ..., Upper - 1] X Num` exactly once. `X` denotes the // cartesian product of sets. The elements of the `integer_sequence` are // of type `std::array` where `Int` is the type of `Upper`. CPP_template(auto Upper, - size_t Num)(requires ql::concepts::integral< - decltype(Upper)>) auto cartesianPowerAsIntegerArray() { + size_t Num) (requires ql::concepts::integral) +auto cartesianPowerAsIntegerArray() { return toIntegerSequenceRef>(); } diff --git a/src/util/CopyableUniquePtr.h b/src/util/CopyableUniquePtr.h index e3886c0d23..a24da4fcfe 100644 --- a/src/util/CopyableUniquePtr.h +++ b/src/util/CopyableUniquePtr.h @@ -21,9 +21,11 @@ of the object for the `unique_ptr`. Currently not written with support for dynamically-allocated array of objects in mind, so that may not work. */ -CPP_template(typename T, typename Deleter = std::default_delete)( - requires std::is_copy_constructible_v) class CopyableUniquePtr - : public std::unique_ptr { +CPP_template( + typename T, + typename Deleter = + std::default_delete) (requires std::is_copy_constructible_v) +class CopyableUniquePtr : public std::unique_ptr { // This makes calling functions, etc. from the base class so much easier. using Base = std::unique_ptr; @@ -51,9 +53,8 @@ CPP_template(typename T, typename Deleter = std::default_delete)( CopyableUniquePtr& operator=(CopyableUniquePtr&& ptr) = default; // Json serialization. - CPP_template_2(typename S)( - requires OrderedOrUnorderedJson< - S>) friend void to_json(S& j, const CopyableUniquePtr& p) { + CPP_template_2(typename S)(requires OrderedOrUnorderedJson) + friend void to_json(S& j, const CopyableUniquePtr& p) { /* The serialization of `CopyableUniquePtr` would have identical code to the serialization of a normal unique pointer, so we just re-cast it, to save on diff --git a/src/util/DefaultValueSizeGetter.h b/src/util/DefaultValueSizeGetter.h index 15db85ee5c..7f988c1433 100644 --- a/src/util/DefaultValueSizeGetter.h +++ b/src/util/DefaultValueSizeGetter.h @@ -28,17 +28,16 @@ struct SizeOfSizeGetter { than you will have to define custom move/copy constructor and assignment operators. */ - CPP_template(typename T)(requires std::is_trivially_copyable_v) - ad_utility::MemorySize - operator()(const T& obj) const { + CPP_template(typename T) (requires std::is_trivially_copyable_v) + ad_utility::MemorySize operator()(const T& obj) const { return ad_utility::MemorySize::bytes(sizeof(obj)); } }; // `ValueSizeGetter` for instances of `std::basic_string`. -CPP_template(typename StringType)( - requires ad_utility::isInstantiation< - StringType, std::basic_string>) struct StringSizeGetter { +CPP_template( + typename StringType) (requires ad_utility::isInstantiation) +struct StringSizeGetter { ad_utility::MemorySize operator()(const StringType& str) const { return ad_utility::MemorySize::bytes( str.size() * sizeof(typename StringType::value_type)); diff --git a/src/util/Exception.h b/src/util/Exception.h index a3722a0411..94a31fd3be 100644 --- a/src/util/Exception.h +++ b/src/util/Exception.h @@ -99,13 +99,13 @@ CPP_concept CanStrCat = CPP_requires_ref(is_str_catable_, S); // * A type that can be passed to `absl::StrCat` (e.g. `string`, `string_views`, // builtin numeric types) [first overload] // * A callbable that takes no arguments and returns a string [second overload] -CPP_template(typename S)(requires CanStrCat) std::string - getMessageImpl(S&& s) { +CPP_template(typename S) (requires CanStrCat) +std::string getMessageImpl(S&& s) { return absl::StrCat(AD_FWD(s)); } -CPP_template(typename T)( - requires ad_utility::InvocableWithConvertibleReturnType) - std::string getMessageImpl(T&& f) { +CPP_template(typename T) ( + requires ad_utility::InvocableWithConvertibleReturnType) +std::string getMessageImpl(T&& f) { return std::invoke(f); } diff --git a/src/util/ExceptionHandling.h b/src/util/ExceptionHandling.h index 522ee15687..d0e0553ecc 100644 --- a/src/util/ExceptionHandling.h +++ b/src/util/ExceptionHandling.h @@ -25,11 +25,10 @@ struct CallStdTerminate { // propagate it. Can be used to make destructors `noexcept` when the destructor // has to perform actions that might throw, but when handling these exceptions // is not important. -CPP_template(typename F)( - requires ql::concepts::invocable>) void ignoreExceptionIfThrows(F&& f, - std::string_view additionalNote = - "") noexcept { +CPP_template( + typename F) (requires ql::concepts::invocable>) +void ignoreExceptionIfThrows(F&& f, + std::string_view additionalNote = "") noexcept { if constexpr (std::is_nothrow_invocable_v>) { std::invoke(AD_FWD(f)); return; @@ -53,15 +52,14 @@ CPP_template(typename F)( // also is not easily recoverable. For an example usage see `PatternCreator.h`. // The actual termination call can be configured for testing purposes. Note that // this function must never throw an exception. -CPP_template(typename F, typename TerminateAction = detail::CallStdTerminate)( - requires ql::concepts::invocable> CPP_and - std::is_nothrow_invocable_v< - TerminateAction>) void terminateIfThrows(F&& f, - std::string_view message, - TerminateAction - terminateAction = {}, - ad_utility::source_location l = - AD_CURRENT_SOURCE_LOC()) noexcept { +CPP_template( + typename F, + typename TerminateAction = detail:: + CallStdTerminate) (requires ql::concepts::invocable> CPP_and + std::is_nothrow_invocable_v) +void terminateIfThrows( + F&& f, std::string_view message, TerminateAction terminateAction = {}, + ad_utility::source_location l = AD_CURRENT_SOURCE_LOC()) noexcept { auto getErrorMessage = [&message, &l](const auto&... additionalMessages) -> std::string { return absl::StrCat( @@ -114,10 +112,11 @@ class ThrowInDestructorIfSafe { int numExceptionsDuringConstruction_ = std::uncaught_exceptions(); public: - CPP_template(typename FuncType, typename... Args)( - requires ql::concepts::invocable CPP_and( - ...&& ql::concepts::convertible_to)) void - operator()(FuncType f, const Args&... additionalMessages) const { + CPP_template( + typename FuncType, + typename... Args) (requires ql::concepts::invocable CPP_and( + ... && ql::concepts::convertible_to)) + void operator()(FuncType f, const Args&... additionalMessages) const { auto logIgnoredException = [&additionalMessages...](std::string_view what) { std::string_view sep = sizeof...(additionalMessages) == 0 ? "" : " "; AD_LOG_WARN diff --git a/src/util/FsstCompressor.h b/src/util/FsstCompressor.h index 79180e253d..8401c9f7f4 100644 --- a/src/util/FsstCompressor.h +++ b/src/util/FsstCompressor.h @@ -23,9 +23,9 @@ namespace detail { // unsigned character types. Note that this is one of the few cases where a // `reinterpret_cast` is safe. struct CastToUnsignedPtr { - CPP_template(typename T)( - requires ad_utility::SameAsAny) auto - operator()(T ptr) const { + CPP_template( + typename T) (requires ad_utility::SameAsAny) + auto operator()(T ptr) const { using Res = std::conditional_t, const unsigned char*, unsigned char*>; return reinterpret_cast(ptr); @@ -64,9 +64,9 @@ class FsstDecoder { return output; } // Allow this type to be trivially serializable, - CPP_template(typename T, typename U)( - requires ql::concepts::same_as) friend std::true_type - allowTrivialSerialization(T, U&&) { + CPP_template(typename T, + typename U) (requires ql::concepts::same_as) + friend std::true_type allowTrivialSerialization(T, U&&) { return {}; } }; @@ -106,9 +106,10 @@ class FsstRepeatedDecoder { return result; } // Allow this type to be trivially serializable, - CPP_template_2(typename T, typename U)( - requires ql::concepts::same_as) - [[maybe_unused]] friend std::true_type allowTrivialSerialization(T, U) { + CPP_template_2( + typename T, + typename U)(requires ql::concepts::same_as) + [[maybe_unused]] friend std::true_type allowTrivialSerialization(T, U) { return {}; } }; diff --git a/src/util/Generator.h b/src/util/Generator.h index 6c253dc3cf..298adecfd2 100644 --- a/src/util/Generator.h +++ b/src/util/Generator.h @@ -85,9 +85,9 @@ class generator_promise { } // Don't allow any use of 'co_await' inside the generator coroutine. - CPP_template_2(typename U)( - requires CPP_NOT(ad_utility::SimilarTo)) std::suspend_never - await_transform(U&& value) = delete; + CPP_template_2( + typename U)(requires CPP_NOT(ad_utility::SimilarTo)) + std::suspend_never await_transform(U&& value) = delete; void rethrow_if_exception() const { if (m_exception) { @@ -104,9 +104,9 @@ class generator_promise { Details& await_resume() noexcept { return promise_.details(); } }; - CPP_template(typename DetailT)( - requires ad_utility::SimilarTo) DetailAwaiter - await_transform([[maybe_unused]] DetailT&& detail) { + CPP_template( + typename DetailT) (requires ad_utility::SimilarTo) + DetailAwaiter await_transform([[maybe_unused]] DetailT&& detail) { return {*this}; } @@ -136,26 +136,34 @@ class generator_promise { static constexpr bool hasDetails = !std::is_same_v; SetDetailsPointerAwaiter await_transform(SetDetailsPointer
details) - requires hasDetails { + requires hasDetails + { return {*this, details}; } SetDetailsAwaiter await_transform(SetDetails
details) - requires hasDetails { + requires hasDetails + { return {*this, details}; } - Details& details() requires hasDetails { + Details& details() + requires hasDetails + { return std::holds_alternative
(m_details) ? std::get
(m_details) : *std::get(m_details); } - void setDetailsPointer(Details* pointer) requires hasDetails { + void setDetailsPointer(Details* pointer) + requires hasDetails + { AD_CONTRACT_CHECK(pointer != nullptr); m_details = pointer; } - void setDetails(Details details) requires hasDetails { + void setDetails(Details details) + requires hasDetails + { m_details = std::move(details); } diff --git a/src/util/Generators.h b/src/util/Generators.h index 91489a2ddf..db61289ba1 100644 --- a/src/util/Generators.h +++ b/src/util/Generators.h @@ -22,16 +22,15 @@ namespace ad_utility { // returns false. If the `aggregator` returns false, the cached value is // discarded. If the cached value is still present once the generator is fully // consumed, `onFullyCached` is called with the cached value. -CPP_template(typename InputRange, typename AggregatorT, - typename T = ql::ranges::range_value_t, - typename FullyCachedFuncT = int)( - requires InvocableWithExactReturnType&, - const T&> - CPP_and InvocableWithExactReturnType< - FullyCachedFuncT, void, - T>) auto wrapGeneratorWithCache(InputRange generator, - AggregatorT aggregator, - FullyCachedFuncT onFullyCached) { +CPP_template( + typename InputRange, typename AggregatorT, + typename T = ql::ranges::range_value_t, + typename FullyCachedFuncT = + int) (requires InvocableWithExactReturnType&, const T&> + CPP_and InvocableWithExactReturnType) +auto wrapGeneratorWithCache(InputRange generator, AggregatorT aggregator, + FullyCachedFuncT onFullyCached) { struct CachingWrapper : public InputRangeFromGet { InputRange generator_; AggregatorT aggregator_; @@ -84,10 +83,11 @@ CPP_template(typename InputRange, typename AggregatorT, // callable that takes a `callback` with signature `void(T)`. The arguments with // which this callback is called when running the `functionWithCallback` become // the elements that are yielded by the created `generator`. -CPP_template(typename T, typename F)( - requires ql::concepts::invocable>) - InputRangeTypeErased generatorFromActionWithCallback( - F functionWithCallback) { +CPP_template( + typename T, + typename F) (requires ql::concepts::invocable>) +InputRangeTypeErased generatorFromActionWithCallback( + F functionWithCallback) { class CallbackToRangeAdapter : public InputRangeFromGet { F functionWithCallback_; std::mutex mutex_; diff --git a/src/util/InputRangeUtils.h b/src/util/InputRangeUtils.h index 84fa7eb1be..e256233769 100644 --- a/src/util/InputRangeUtils.h +++ b/src/util/InputRangeUtils.h @@ -385,8 +385,8 @@ CachingContinuableTransformInputRange(Range&&, F) // A function that returns a lazy range that yields a single value. The value // is the result of invoking `singleValueGetter`. -CPP_template(typename F)(requires std::is_invocable_v< - F>) auto lazySingleValueRange(F singleValueGetter) { +CPP_template(typename F) (requires std::is_invocable_v) +auto lazySingleValueRange(F singleValueGetter) { using T = std::invoke_result_t; static_assert(std::is_object_v, "The functor of `lazySingleValueRange` must yield an " diff --git a/src/util/Iterators.h b/src/util/Iterators.h index 38bf5a52d0..59ab0f4441 100644 --- a/src/util/Iterators.h +++ b/src/util/Iterators.h @@ -167,20 +167,24 @@ class IteratorForAccessOperator { decltype(auto) operator*() const { return accessor_(*vector_, index_); } - CPP_template(typename = void)(requires(!isConst)) decltype(auto) operator*() { + CPP_template(typename = void) (requires(!isConst)) + decltype(auto) operator*() { return accessor_(*vector_, index_); } // Only allowed, if `RandomAccessContainer` yields references and not values - CPP_template(typename A = Accessor, typename P = RandomAccessContainerPtr)( - requires HasValidAccessor CPP_and(!isConst)) auto - operator->() { + CPP_template( + typename A = Accessor, + typename P = + RandomAccessContainerPtr) (requires HasValidAccessor CPP_and(!isConst)) + auto operator->() { return &(*(*this)); } - CPP_template(typename A = Accessor, typename P = RandomAccessContainerPtr)( - requires HasValidAccessor) auto - operator->() const { + CPP_template( + typename A = Accessor, + typename P = RandomAccessContainerPtr) (requires HasValidAccessor) + auto operator->() const { return &(*(*this)); } @@ -296,8 +300,9 @@ class DetailsProvider { // Allows to store a pointer to external details. Only available if // `hasDetails` is true. - CPP_member auto setDetailsPointer(Details* pointer) - -> CPP_ret(void)(requires hasDetails) { + CPP_member auto setDetailsPointer(Details* pointer) -> CPP_ret( + void)(requires hasDetails) + { AD_CONTRACT_CHECK(pointer != nullptr); static_cast(this)->getDetails() = pointer; } @@ -404,10 +409,10 @@ class InputRangeFromGet // A simple helper to define an `InputRangeFromGet` where the `get()` function // is a simple callable. -CPP_template(typename T, typename F)( - requires ad_utility::InvocableWithConvertibleReturnType< - F, std::optional>) struct InputRangeFromGetCallable - : public InputRangeFromGet { +CPP_template(typename T, typename F) ( + requires ad_utility::InvocableWithConvertibleReturnType>) +struct InputRangeFromGetCallable : public InputRangeFromGet { private: ::ranges::semiregular_box_t function_; @@ -479,29 +484,29 @@ class InputRangeTypeErased using value_type = ValueType; // Constructor for ranges that directly inherit from // `InputRangeOptionalMixin`. - CPP_template(typename Range)( - requires std::is_base_of_v< - InputRangeFromGet, - Range>) explicit InputRangeTypeErased(Range range) + CPP_template( + typename Range) (requires std::is_base_of_v< + InputRangeFromGet, Range>) + explicit InputRangeTypeErased(Range range) : impl_{std::make_unique(std::move(range))} {} // Constructor for ranges that are not movable - CPP_template(typename Range)( - requires std::is_base_of_v< - InputRangeFromGet, - Range>) explicit InputRangeTypeErased(std::unique_ptr range) + CPP_template( + typename Range) (requires std::is_base_of_v< + InputRangeFromGet, Range>) + explicit InputRangeTypeErased(std::unique_ptr range) : impl_{std::move(range)} {} // Constructor for all other ranges. We first pass them through the // `InputRangeToOptional` class from above to make it compatible with the base // class. - CPP_template(typename Range)( - requires CPP_NOT( - std::is_base_of_v, Range>) - CPP_and ql::ranges::range - CPP_and ql::concepts::same_as< - ql::ranges::range_value_t, - ValueType>) explicit InputRangeTypeErased(Range range) + CPP_template( + typename Range) (requires CPP_NOT( + std::is_base_of_v, Range>) + CPP_and ql::ranges::range + CPP_and ql::concepts::same_as< + ql::ranges::range_value_t, ValueType>) + explicit InputRangeTypeErased(Range range) : impl_{std::make_unique>( std::move(range))} {} @@ -542,9 +547,11 @@ InputRangeTypeErased(std::unique_ptr>) // `ql::ranges::subrange`, but yields the iterators instead of the values when // being iterated over. Currently, the iterators must be random-access and the // resulting range thus also is random access. -CPP_template(typename It, typename End)( - requires ql::concepts::random_access_iterator CPP_and - ql::concepts::sized_sentinel_for) struct IteratorRange +CPP_template( + typename It, + typename End) (requires ql::concepts::random_access_iterator CPP_and + ql::concepts::sized_sentinel_for) +struct IteratorRange : public ql::ranges::view_interface> { private: It it_; diff --git a/src/util/JoinAlgorithms/FindUndefRanges.h b/src/util/JoinAlgorithms/FindUndefRanges.h index d42f81fe90..2432c7bc43 100644 --- a/src/util/JoinAlgorithms/FindUndefRanges.h +++ b/src/util/JoinAlgorithms/FindUndefRanges.h @@ -40,11 +40,12 @@ namespace ad_utility { // is the number of matching elements. // TODO This can be optimized when we also know which columns of // `[begin, end)` can possibly contain UNDEF values. -CPP_template(typename R, - typename It)(requires ql::concepts::random_access_iterator) // - auto findSmallerUndefRangesForRowsWithoutUndef( - const R& row, It begin, It end, - [[maybe_unused]] bool& resultMightBeUnsorted) { +CPP_template( + typename R, + typename It) (requires ql::concepts::random_access_iterator) // +auto findSmallerUndefRangesForRowsWithoutUndef( + const R& row, It begin, It end, + [[maybe_unused]] bool& resultMightBeUnsorted) { using Row = typename std::iterator_traits::value_type; assert(row.size() == (*begin).size()); assert( @@ -85,10 +86,11 @@ CPP_template(typename R, // TODO We could also implement a version that is optimized on the // [begin, end] range not having UNDEF values in some of the columns -CPP_template(typename It)(requires ql::concepts::random_access_iterator) // - auto findSmallerUndefRangesForRowsWithUndefInLastColumns( - const auto& row, const size_t numLastUndefined, It begin, It end, - bool& resultMightBeUnsorted) { +CPP_template( + typename It) (requires ql::concepts::random_access_iterator) // +auto findSmallerUndefRangesForRowsWithUndefInLastColumns( + const auto& row, const size_t numLastUndefined, It begin, It end, + bool& resultMightBeUnsorted) { using Row = typename std::iterator_traits::value_type; const size_t numJoinColumns = row.size(); assert(row.size() == (*begin).size()); @@ -138,9 +140,10 @@ CPP_template(typename It)(requires ql::concepts::random_access_iterator) // // This function has no additional preconditions, but runs in `O((end - begin) * // numColumns)`. -CPP_template(typename It)(requires ql::concepts::random_access_iterator) // - auto findSmallerUndefRangesArbitrary(const auto& row, It begin, It end, - bool& resultMightBeUnsorted) { +CPP_template( + typename It) (requires ql::concepts::random_access_iterator) // +auto findSmallerUndefRangesArbitrary(const auto& row, It begin, It end, + bool& resultMightBeUnsorted) { assert(row.size() == (*begin).size()); assert( ql::ranges::is_sorted(begin, end, ql::ranges::lexicographical_compare)); @@ -185,10 +188,10 @@ CPP_template(typename It)(requires ql::concepts::random_access_iterator) // // columns contain no UNDEF at all) and therefore a more specialized routine // should be chosen. struct FindSmallerUndefRanges { - CPP_template(typename Row, typename It)( - requires ql::concepts::random_access_iterator) auto - operator()(const Row& row, It begin, It end, - bool& resultMightBeUnsorted) const { + CPP_template(typename Row, + typename It) (requires ql::concepts::random_access_iterator) + auto operator()(const Row& row, It begin, It end, + bool& resultMightBeUnsorted) const { size_t numLastUndefined = 0; assert(row.size() > 0); auto it = ql::ranges::rbegin(row); diff --git a/src/util/JoinAlgorithms/JoinAlgorithms.h b/src/util/JoinAlgorithms/JoinAlgorithms.h index aa8858936c..30510b6664 100644 --- a/src/util/JoinAlgorithms/JoinAlgorithms.h +++ b/src/util/JoinAlgorithms/JoinAlgorithms.h @@ -371,20 +371,17 @@ CPP_template(typename Range1, typename Range2, typename LessThan, * a proper exception. Typically implementations will just * CancellationHandle::throwIfCancelled(). */ -CPP_template(typename RangeSmaller, typename RangeLarger, typename LessThan, - typename Action, typename ElementFromSmallerNotFoundAction = Noop, - typename CheckCancellation = Noop)( - requires ql::ranges::random_access_range CPP_and - ql::ranges::random_access_range< - RangeLarger>) void gallopingJoin(const RangeSmaller& smaller, - const RangeLarger& larger, - LessThan const& lessThan, - Action const& action, - ElementFromSmallerNotFoundAction - elementFromSmallerNotFoundAction = - {}, - CheckCancellation - checkCancellation = {}) { +CPP_template( + typename RangeSmaller, typename RangeLarger, typename LessThan, + typename Action, typename ElementFromSmallerNotFoundAction = Noop, + typename CheckCancellation = + Noop)(requires ql::ranges::random_access_range CPP_and + ql::ranges::random_access_range) +void gallopingJoin( + const RangeSmaller& smaller, const RangeLarger& larger, + LessThan const& lessThan, Action const& action, + ElementFromSmallerNotFoundAction elementFromSmallerNotFoundAction = {}, + CheckCancellation checkCancellation = {}) { auto itSmall = std::begin(smaller); auto endSmall = std::end(smaller); auto itLarge = std::begin(larger); @@ -486,21 +483,16 @@ CPP_template(typename RangeSmaller, typename RangeLarger, typename LessThan, * @param compatibleRowAction Same as in `zipperJoinWithUndef` * @param elFromFirstNotFoundAction Same as in `zipperJoinWithUndef` */ -CPP_template(typename CompatibleActionT, typename NotFoundActionT, - typename CancellationFuncT)( - requires BinaryIteratorFunction> CPP_and UnaryIteratorFunction< - NotFoundActionT, IdTableView<0>> - CPP_and ql::concepts::invocable< - CancellationFuncT>) void specialOptionalJoin(const IdTableView<0>& - left, - const IdTableView<0>& - right, - const CompatibleActionT& - compatibleRowAction, - const NotFoundActionT& - elFromFirstNotFoundAction, - const CancellationFuncT& - checkCancellation) { +CPP_template( + typename CompatibleActionT, typename NotFoundActionT, + typename CancellationFuncT) (requires BinaryIteratorFunction> + CPP_and UnaryIteratorFunction> + CPP_and ql::concepts::invocable) +void specialOptionalJoin(const IdTableView<0>& left, + const IdTableView<0>& right, + const CompatibleActionT& compatibleRowAction, + const NotFoundActionT& elFromFirstNotFoundAction, + const CancellationFuncT& checkCancellation) { auto it1 = std::begin(left); auto end1 = std::end(left); auto it2 = std::begin(right); @@ -832,12 +824,14 @@ static constexpr size_t FETCH_BLOCKS = 3; // After adding the Cartesian product we start a new round with a new // `currentEl` (5 in this example). New blocks are added to one of the buffers // if they become empty at one point in the algorithm. -CPP_template(typename LeftSide, typename RightSide, typename LessThan, - typename CompatibleRowAction, typename IsUndef = AlwaysFalse)( - requires IsJoinSide CPP_and IsJoinSide CPP_and - InvocableWithExactReturnType< - IsUndef, bool, - typename LeftSide::ProjectedEl>) struct BlockZipperJoinImpl { +CPP_template( + typename LeftSide, typename RightSide, typename LessThan, + typename CompatibleRowAction, + typename IsUndef = + AlwaysFalse)(requires IsJoinSide CPP_and IsJoinSide CPP_and + InvocableWithExactReturnType) +struct BlockZipperJoinImpl { // The left and right inputs of the join LeftSide leftSide_; RightSide rightSide_; diff --git a/src/util/LruCache.h b/src/util/LruCache.h index 55276b5853..e42e6c8a29 100644 --- a/src/util/LruCache.h +++ b/src/util/LruCache.h @@ -35,10 +35,10 @@ class LRUCache { // found. Otherwise, compute the value using `computeFunction` and store it in // the cache. If the cache is already at maximum capacity, evict the least // recently used element. - CPP_template(typename Func)( - requires ad_utility::InvocableWithConvertibleReturnType< - Func, V, const K&>) const V& getOrCompute(const K& key, - Func computeFunction) { + CPP_template( + typename Func) (requires ad_utility::InvocableWithConvertibleReturnType) + const V& getOrCompute(const K& key, Func computeFunction) { auto it = cache_.find(key); if (it != cache_.end()) { const auto& [value, listIterator] = it->second; diff --git a/src/util/MemorySize/MemorySize.h b/src/util/MemorySize/MemorySize.h index 04c2a2858d..93d45637eb 100644 --- a/src/util/MemorySize/MemorySize.h +++ b/src/util/MemorySize/MemorySize.h @@ -75,16 +75,16 @@ class MemorySize { memory size saved internally. Always requires the exact memory size unit and size wanted. */ - CPP_template(typename T)(requires ql::concepts::integral) // - constexpr static MemorySize bytes(T numBytes); - CPP_template(typename T)(requires Arithmetic) // - constexpr static MemorySize kilobytes(T numKilobytes); - CPP_template(typename T)(requires Arithmetic) // - constexpr static MemorySize megabytes(T numMegabytes); - CPP_template(typename T)(requires Arithmetic) // - constexpr static MemorySize gigabytes(T numGigabytes); - CPP_template(typename T)(requires Arithmetic) // - constexpr static MemorySize terabytes(T numTerabytes); + CPP_template(typename T) (requires ql::concepts::integral) // + constexpr static MemorySize bytes(T numBytes); + CPP_template(typename T) (requires Arithmetic) // + constexpr static MemorySize kilobytes(T numKilobytes); + CPP_template(typename T) (requires Arithmetic) // + constexpr static MemorySize megabytes(T numMegabytes); + CPP_template(typename T) (requires Arithmetic) // + constexpr static MemorySize gigabytes(T numGigabytes); + CPP_template(typename T) (requires Arithmetic) // + constexpr static MemorySize terabytes(T numTerabytes); // Factory for max size instance. constexpr static MemorySize max(); @@ -129,23 +129,20 @@ class MemorySize { constexpr MemorySize operator-(const MemorySize& m) const; constexpr MemorySize& operator-=(const MemorySize& m); - CPP_template(typename T)(requires Arithmetic) // - constexpr MemorySize - operator*(const T c) const; + CPP_template(typename T) (requires Arithmetic) // + constexpr MemorySize operator*(const T c) const; template - friend constexpr auto operator*(const T c, const MemorySize m) - -> CPP_ret(MemorySize)(requires Arithmetic); + friend constexpr auto operator*(const T c, const MemorySize m) -> CPP_ret(MemorySize)(requires Arithmetic); - CPP_template(typename T)(requires Arithmetic) // - constexpr MemorySize& - operator*=(const T c); + CPP_template(typename T) (requires Arithmetic) // + constexpr MemorySize& operator*=(const T c); - CPP_template(typename T)(requires Arithmetic) constexpr MemorySize - operator/(const T c) const; + CPP_template(typename T) (requires Arithmetic) + constexpr MemorySize operator/(const T c) const; - CPP_template(typename T)(requires Arithmetic) constexpr MemorySize& - operator/=(const T c); + CPP_template(typename T) (requires Arithmetic) + constexpr MemorySize& operator/=(const T c); private: // Constructor for the factory functions. @@ -213,8 +210,8 @@ static constexpr auto maxAmountOfUnit = []() { }(); // Converts a given number to `size_t`. Rounds up, if needed. -CPP_template(typename T)(requires Arithmetic) constexpr size_t - ceilAndCastToSizeT(const T d) { +CPP_template(typename T) (requires Arithmetic) +constexpr size_t ceilAndCastToSizeT(const T d) { if constexpr (std::is_floating_point_v) { // TODO As of `c++23`, `std::ceil` is constexpr and can be used. const auto unrounded = static_cast(d); @@ -233,9 +230,9 @@ CPP_template(typename T)(requires Arithmetic) constexpr size_t @return The amount of bytes. Rounded up, if needed. */ -CPP_template(typename T)(requires Arithmetic) // - constexpr size_t convertMemoryUnitsToBytes(const T amountOfUnits, - std::string_view unitName) { +CPP_template(typename T) (requires Arithmetic) // +constexpr size_t convertMemoryUnitsToBytes(const T amountOfUnits, + std::string_view unitName) { if constexpr (std::is_signed_v) { // Negative values makes no sense. AD_CONTRACT_CHECK(amountOfUnits >= 0); @@ -284,11 +281,11 @@ multiplied/divied with. `double.` Note, that the rounding and casting to `size_t` for floating point return types will be automatically done, and can be ignored by `func`. */ -CPP_template(typename T, typename Func)(requires Arithmetic CPP_and( - ql::concepts::invocable || - ql::concepts::invocable)) // - constexpr MemorySize magicImplForDivAndMul(const MemorySize& m, // - const T c, Func func) { +CPP_template(typename T, typename Func) (requires Arithmetic CPP_and( + ql::concepts::invocable || + ql::concepts::invocable)) // +constexpr MemorySize magicImplForDivAndMul(const MemorySize& m, // + const T c, Func func) { // In order for the results to be as precise as possible, we cast to highest // precision data type variant of `T`. using PrecisionType = @@ -301,9 +298,8 @@ CPP_template(typename T, typename Func)(requires Arithmetic CPP_and( } // namespace detail // _____________________________________________________________________________ -CPP_template_def(typename T)( - requires ql::concepts::integral) constexpr MemorySize - MemorySize::bytes(T numBytes) { +CPP_template_def(typename T)(requires ql::concepts::integral) +constexpr MemorySize MemorySize::bytes(T numBytes) { if constexpr (std::is_signed_v) { // Doesn't make much sense to a negative amount of memory. AD_CONTRACT_CHECK(numBytes >= 0); @@ -313,26 +309,26 @@ CPP_template_def(typename T)( } // _____________________________________________________________________________ -CPP_template_def(typename T)(requires Arithmetic) constexpr MemorySize - MemorySize::kilobytes(T numKilobytes) { +CPP_template_def(typename T)(requires Arithmetic) +constexpr MemorySize MemorySize::kilobytes(T numKilobytes) { return MemorySize{detail::convertMemoryUnitsToBytes(numKilobytes, "kB")}; } // _____________________________________________________________________________ -CPP_template_def(typename T)(requires Arithmetic) constexpr MemorySize - MemorySize::megabytes(T numMegabytes) { +CPP_template_def(typename T)(requires Arithmetic) +constexpr MemorySize MemorySize::megabytes(T numMegabytes) { return MemorySize{detail::convertMemoryUnitsToBytes(numMegabytes, "MB")}; } // _____________________________________________________________________________ -CPP_template_def(typename T)(requires Arithmetic) constexpr MemorySize - MemorySize::gigabytes(T numGigabytes) { +CPP_template_def(typename T)(requires Arithmetic) +constexpr MemorySize MemorySize::gigabytes(T numGigabytes) { return MemorySize{detail::convertMemoryUnitsToBytes(numGigabytes, "GB")}; } // _____________________________________________________________________________ -CPP_template_def(typename T)(requires Arithmetic) constexpr MemorySize - MemorySize::terabytes(T numTerabytes) { +CPP_template_def(typename T)(requires Arithmetic) +constexpr MemorySize MemorySize::terabytes(T numTerabytes) { return MemorySize{detail::convertMemoryUnitsToBytes(numTerabytes, "TB")}; } @@ -404,8 +400,8 @@ constexpr MemorySize& MemorySize::operator-=(const MemorySize& m) { } // _____________________________________________________________________________ -CPP_template_def(typename T)(requires Arithmetic) constexpr MemorySize - MemorySize::operator*(const T c) const { +CPP_template_def(typename T)(requires Arithmetic) +constexpr MemorySize MemorySize::operator*(const T c) const { if constexpr (std::is_signed_v) { // A negative amount of memory wouldn't make much sense. AD_CONTRACT_CHECK(c >= static_cast(0)); @@ -425,15 +421,15 @@ CPP_template_def(typename T)(requires Arithmetic) constexpr MemorySize // _____________________________________________________________________________ template -constexpr auto operator*(const T c, const MemorySize m) - -> CPP_ret(MemorySize)(requires Arithmetic) { +constexpr auto operator*(const T c, const MemorySize m) -> CPP_ret( + MemorySize)(requires Arithmetic) +{ return m * c; } // _____________________________________________________________________________ -CPP_template_def(typename T)( - requires Arithmetic< - T>) constexpr MemorySize& MemorySize::operator*=(const T c) { +CPP_template_def(typename T)(requires Arithmetic) +constexpr MemorySize& MemorySize::operator*=(const T c) { *this = *this * c; return *this; } @@ -455,8 +451,8 @@ struct DivisionFunctor { } // namespace detail // _____________________________________________________________________________ -CPP_template_def(typename T)(requires Arithmetic) constexpr MemorySize - MemorySize::operator/(const T c) const { +CPP_template_def(typename T)(requires Arithmetic) +constexpr MemorySize MemorySize::operator/(const T c) const { if constexpr (std::is_signed_v) { // A negative amount of memory wouldn't make much sense. AD_CONTRACT_CHECK(c > static_cast(0)); @@ -490,9 +486,8 @@ CPP_template_def(typename T)(requires Arithmetic) constexpr MemorySize } // _____________________________________________________________________________ -CPP_template_def(typename T)( - requires Arithmetic< - T>) constexpr MemorySize& MemorySize::operator/=(const T c) { +CPP_template_def(typename T)(requires Arithmetic) +constexpr MemorySize& MemorySize::operator/=(const T c) { *this = *this / c; return *this; } diff --git a/src/util/MmapVector.h b/src/util/MmapVector.h index 9ea38adf74..8280ddbb2b 100644 --- a/src/util/MmapVector.h +++ b/src/util/MmapVector.h @@ -148,10 +148,9 @@ class MmapVector { MmapVector(MmapVector&& other) noexcept; MmapVector& operator=(MmapVector&& other) noexcept; - CPP_template(class Arg, typename... Args)(requires CPP_NOT( - ql::concepts::derived_from, MmapVector>)) - MmapVector(Arg&& arg, Args&&... args) - : MmapVector() { + CPP_template(class Arg, typename... Args) (requires CPP_NOT( + ql::concepts::derived_from, MmapVector>)) + MmapVector(Arg&& arg, Args&&... args) : MmapVector() { this->open(AD_FWD(arg), AD_FWD(args)...); } @@ -306,10 +305,9 @@ class MmapVectorView : private MmapVector { // construct with any combination of arguments that is supported by the open() // member function - CPP_template(typename Arg, typename... Args)(requires CPP_NOT( - ql::concepts::same_as< - ql::remove_cvref_t, - MmapVectorView>)) explicit MmapVectorView(Arg&& arg, Args&&... args) { + CPP_template(typename Arg, typename... Args) (requires CPP_NOT( + ql::concepts::same_as, MmapVectorView>)) + explicit MmapVectorView(Arg&& arg, Args&&... args) { open(AD_FWD(arg), AD_FWD(args)...); } @@ -369,11 +367,9 @@ class MmapVectorTmp : public MmapVector { : MmapVector(std::move(rhs)) {} MmapVectorTmp(const MmapVectorTmp& rhs) = delete; - CPP_template(class Arg, typename... Args)(requires CPP_NOT( - ql::concepts::derived_from< - ql::remove_cvref_t, - MmapVectorTmp>)) explicit MmapVectorTmp(Arg&& arg, Args&&... args) - : MmapVector() { + CPP_template(class Arg, typename... Args) (requires CPP_NOT( + ql::concepts::derived_from, MmapVectorTmp>)) + explicit MmapVectorTmp(Arg&& arg, Args&&... args) : MmapVector() { this->open(AD_FWD(arg), AD_FWD(args)...); } diff --git a/src/util/MmapVectorImpl.h b/src/util/MmapVectorImpl.h index 4f2e1a8aa6..f62bbd9d47 100644 --- a/src/util/MmapVectorImpl.h +++ b/src/util/MmapVectorImpl.h @@ -243,7 +243,9 @@ void MmapVector::open(size_t size, std::string filename, // open the file in case it does not exist yet // (data will be overwritten anyway) - { auto ofs = ad_utility::makeOfstream(_filename); } + { + auto ofs = ad_utility::makeOfstream(_filename); + } auto info = convertArraySizeToFileSize(std::max(size, MinCapacity)); _bytesize = info._bytesize; _capacity = info._capacity; diff --git a/src/util/NBitInteger.h b/src/util/NBitInteger.h index dff1c20a2a..1be621ad51 100644 --- a/src/util/NBitInteger.h +++ b/src/util/NBitInteger.h @@ -10,8 +10,8 @@ namespace ad_utility { // A type for signed integers that only need `N` bits to represent. -CPP_template(uint8_t N)(requires(N <= 64) CPP_and(N >= 1)) // - class NBitInteger { +CPP_template(uint8_t N) (requires(N <= 64) CPP_and(N >= 1)) // +class NBitInteger { using T = uint64_t; static constexpr uint8_t UNUSED_BITS = 64 - N; diff --git a/src/util/OnDestructionDontThrowDuringStackUnwinding.h b/src/util/OnDestructionDontThrowDuringStackUnwinding.h index c64d1b76a9..77879b0c37 100644 --- a/src/util/OnDestructionDontThrowDuringStackUnwinding.h +++ b/src/util/OnDestructionDontThrowDuringStackUnwinding.h @@ -12,8 +12,8 @@ namespace detail { // The implementation of `makeOnDestructionDontThrowDuringStackUnwinding` (see // below). -CPP_template(typename F)(requires std::is_invocable_v< - F>) class OnDestructionDontThrowDuringStackUnwinding { +CPP_template(typename F) (requires std::is_invocable_v) +class OnDestructionDontThrowDuringStackUnwinding { static_assert( !std::is_nothrow_invocable_v, "When using a non-throwing callback, use the simpler `absl::Cleanup`"); @@ -73,9 +73,10 @@ class OnDestructionCreator { // return object in a container because all of its constructors are either // private or deleted. This is disabled deliberately as it might lead to program // termination (for `std::vector`) or to uncalled destructors. -CPP_template(typename F)(requires ql::concepts::invocable) - QL_NODISCARD("") detail::OnDestructionDontThrowDuringStackUnwinding< - F> makeOnDestructionDontThrowDuringStackUnwinding(F f) { +CPP_template(typename F) (requires ql::concepts::invocable) +QL_NODISCARD("") +detail::OnDestructionDontThrowDuringStackUnwinding< + F> makeOnDestructionDontThrowDuringStackUnwinding(F f) { static_assert( !std::is_nothrow_invocable_v, "When using a non-throwing callback, use the simpler `absl::Cleanup`"); diff --git a/src/util/ParallelMultiwayMerge.h b/src/util/ParallelMultiwayMerge.h index 76f39c2f33..96052296d1 100644 --- a/src/util/ParallelMultiwayMerge.h +++ b/src/util/ParallelMultiwayMerge.h @@ -24,8 +24,9 @@ using namespace ad_utility::memory_literals; // moved. It is necessary to explicitly pass the type `T` stored in the vector // to enable the usage of this lambda in combination with `std::bind_front` and // `std::ref`. -CPP_template(bool moveElements, typename T, typename SizeGetter)( - requires ValueSizeGetter) constexpr auto pushSingleElement = +CPP_template(bool moveElements, typename T, + typename SizeGetter) (requires ValueSizeGetter) +constexpr auto pushSingleElement = [](std::vector& buffer, MemorySize& sz, auto& el) { sz += SizeGetter{}(el); if constexpr (moveElements) { @@ -57,11 +58,11 @@ CPP_concept RandomAccessRangeOfRanges = // buffers. CPP_template(typename T, bool moveElements, typename SizeGetter, typename Range1, typename Range2, typename ComparisonFuncT)( - requires ValueSizeGetter CPP_and RangeWithValue - CPP_and RangeWithValue - CPP_and ad_utility::InvocableWithExactReturnType< - ComparisonFuncT, bool, const T&, - const T&>) class LazyBinaryMerge + requires ValueSizeGetter CPP_and RangeWithValue + CPP_and RangeWithValue + CPP_and ad_utility::InvocableWithExactReturnType< + ComparisonFuncT, bool, const T&, const T&>) +class LazyBinaryMerge : public ad_utility::InputRangeMixin> { private: @@ -164,11 +165,10 @@ CPP_template(typename T, bool moveElements, typename SizeGetter, // Return the elements of the `range` in blocks of the given `blocksize`. // TODO This gets much simpler with the buffering generator. -CPP_template(typename T, bool moveElements, typename SizeGetter, - typename R)(requires ValueSizeGetter CPP_and - RangeWithValue) class BatchToVector - : public ad_utility::InputRangeMixin< - BatchToVector> { +CPP_template(typename T, bool moveElements, typename SizeGetter, typename R) ( + requires ValueSizeGetter CPP_and RangeWithValue) +class BatchToVector : public ad_utility::InputRangeMixin< + BatchToVector> { private: MemorySize maxMem_; size_t blocksize_; @@ -213,15 +213,15 @@ CPP_template(typename T, bool moveElements, typename SizeGetter, // The recursive implementation of `parallelMultiwayMerge` (see below). The // difference is, that the memory limit in this function is per node in the // recursion tree. -CPP_template(typename T, bool moveElements, typename SizeGetter, typename R, - typename ComparisonFuncT)( - requires detail::RandomAccessRangeOfRanges CPP_and - ValueSizeGetter - CPP_and InvocableWithExactReturnType) - ad_utility::InputRangeTypeErased> parallelMultiwayMergeImpl( - MemorySize maxMemPerNode, size_t blocksize, R&& rangeOfRanges, - ComparisonFuncT comparison) { +CPP_template( + typename T, bool moveElements, typename SizeGetter, typename R, + typename ComparisonFuncT)(requires detail::RandomAccessRangeOfRanges CPP_and + ValueSizeGetter + CPP_and InvocableWithExactReturnType) +ad_utility::InputRangeTypeErased> parallelMultiwayMergeImpl( + MemorySize maxMemPerNode, size_t blocksize, R&& rangeOfRanges, + ComparisonFuncT comparison) { AD_CORRECTNESS_CHECK(!rangeOfRanges.empty()); auto moveIf = [](auto& range) -> decltype(auto) { if constexpr (moveElements) { @@ -281,17 +281,18 @@ CPP_template(typename T, bool moveElements, typename SizeGetter, typename R, // implementation. It can be tweaked for maximum performance, currently values // of at least `50-100` seem to work well. CPP_template(typename T, bool moveElements, - typename SizeGetter)(requires ValueSizeGetter) // - struct ParallelMultiwayMergeStruct { - CPP_template_2(typename R, typename Comp)( - requires detail::RandomAccessRangeOfRanges CPP_and - ValueSizeGetter - CPP_and - InvocableWithExactReturnType) - ad_utility::InputRangeTypeErased> - operator()(MemorySize memoryLimit, R&& rangeOfRanges, Comp comparison, - size_t blocksize = 100) const { + typename SizeGetter) (requires ValueSizeGetter) // +struct ParallelMultiwayMergeStruct { + CPP_template_2( + typename R, + typename Comp)(requires detail::RandomAccessRangeOfRanges CPP_and + ValueSizeGetter + CPP_and InvocableWithExactReturnType) + ad_utility::InputRangeTypeErased> operator()( + MemorySize memoryLimit, R&& rangeOfRanges, Comp comparison, + size_t blocksize = 100) const { // There is one suboperation per input in the recursion tree, so we have to // divide the memory limit. auto maxMemPerNode = memoryLimit / ql::ranges::size(rangeOfRanges); diff --git a/src/util/Parameters.h b/src/util/Parameters.h index 3d10a8cede..055f5166a3 100644 --- a/src/util/Parameters.h +++ b/src/util/Parameters.h @@ -49,11 +49,12 @@ CPP_concept ParameterToStringType = /// (representation of a `Type`) and converts it to `Type`. /// \tparam ToString A function type, that takes a `Type` and produces /// a std::string representation. -CPP_template(typename Type, typename FromString, typename ToString)( - requires ql::concepts::semiregular CPP_and - ParameterFromStringType - CPP_and ParameterToStringType) struct Parameter - : public ParameterBase { +CPP_template( + typename Type, typename FromString, + typename ToString) (requires ql::concepts::semiregular CPP_and + ParameterFromStringType + CPP_and ParameterToStringType) +struct Parameter : public ParameterBase { public: using value_type = Type; diff --git a/src/util/ProgramOptionsHelpers.h b/src/util/ProgramOptionsHelpers.h index 7f39e3c4b2..f43ef6839d 100644 --- a/src/util/ProgramOptionsHelpers.h +++ b/src/util/ProgramOptionsHelpers.h @@ -29,9 +29,9 @@ class NonNegative { size_t _value; }; -CPP_template(typename Stream, typename NN)( - requires ad_utility::SimilarTo) Stream& -operator<<(Stream& stream, NN&& nonNegative) { +CPP_template(typename Stream, + typename NN) (requires ad_utility::SimilarTo) +Stream& operator<<(Stream& stream, NN&& nonNegative) { return stream << static_cast(nonNegative); } diff --git a/src/util/ProgressBar.h b/src/util/ProgressBar.h index 5e7fac4983..b423056b90 100644 --- a/src/util/ProgressBar.h +++ b/src/util/ProgressBar.h @@ -68,12 +68,12 @@ class ProgressBar { // outside (and be incremented there). That is because the calling code // typically has such a variable anyway (also for other purposes) and it // would we unnatural to have it originally in this class. - CPP_template(typename SizeT)(requires ad_utility::SimilarTo) - ProgressBar(SizeT& numStepsProcessed, std::string displayStringPrefix, - size_t statisticsBatchSize = DEFAULT_PROGRESS_BAR_BATCH_SIZE, - SpeedDescriptionFunction getSpeedDescription = - DEFAULT_SPEED_DESCRIPTION_FUNCTION, - DisplayUpdateOptions displayUpdateOptions = ReuseLine) + CPP_template(typename SizeT) (requires ad_utility::SimilarTo) + ProgressBar(SizeT& numStepsProcessed, std::string displayStringPrefix, + size_t statisticsBatchSize = DEFAULT_PROGRESS_BAR_BATCH_SIZE, + SpeedDescriptionFunction getSpeedDescription = + DEFAULT_SPEED_DESCRIPTION_FUNCTION, + DisplayUpdateOptions displayUpdateOptions = ReuseLine) : numStepsProcessed_(numStepsProcessed), displayStringPrefix_(std::move(displayStringPrefix)), statisticsBatchSize_(statisticsBatchSize), diff --git a/src/util/Random.h b/src/util/Random.h index 000885c60c..719892a9d7 100644 --- a/src/util/Random.h +++ b/src/util/Random.h @@ -33,8 +33,9 @@ using RandomSeed = ad_utility::TypedIndex; * match (because of the std::enable_if) and there will be a compile-time * error. */ -CPP_template(typename Int)(requires std::is_integral_v CPP_and( - sizeof(Int) <= sizeof(uint64_t))) class FastRandomIntGenerator { +CPP_template(typename Int) ( + requires std::is_integral_v CPP_and(sizeof(Int) <= sizeof(uint64_t))) +class FastRandomIntGenerator { public: explicit FastRandomIntGenerator( RandomSeed seed = RandomSeed::make(std::random_device{}())) { diff --git a/src/util/Serializer/SerializeArrayOrTuple.h b/src/util/Serializer/SerializeArrayOrTuple.h index ed3a886294..772c61c84b 100644 --- a/src/util/Serializer/SerializeArrayOrTuple.h +++ b/src/util/Serializer/SerializeArrayOrTuple.h @@ -19,10 +19,10 @@ namespace ad_utility::serialization { // Allow trivial serialization for `std::array` if the `value_type` is already // `TriviallySerializable`. -CPP_template(typename T, typename U)( - requires ad_utility::SimilarToArray CPP_and - TriviallySerializable) std::true_type - allowTrivialSerialization(T, U); +CPP_template(typename T, + typename U) (requires ad_utility::SimilarToArray CPP_and + TriviallySerializable) +std::true_type allowTrivialSerialization(T, U); // A helper function to figure out whether all types contained in a tuple are // trivially seraizliable. diff --git a/src/util/Serializer/SerializeVector.h b/src/util/Serializer/SerializeVector.h index 7fa1eb0254..2ed34358d3 100644 --- a/src/util/Serializer/SerializeVector.h +++ b/src/util/Serializer/SerializeVector.h @@ -37,8 +37,9 @@ AD_SERIALIZE_FUNCTION_WITH_CONSTRAINT( /// Incrementally serialize a std::vector to disk without materializing it. /// Call `push` for each of the elements that will become part of the vector. -CPP_template(typename T, typename Serializer)( - requires WriteSerializer) class VectorIncrementalSerializer { +CPP_template(typename T, + typename Serializer) (requires WriteSerializer) +class VectorIncrementalSerializer { private: Serializer _serializer; uint64_t _startPosition; diff --git a/src/util/Serializer/Serializer.h b/src/util/Serializer/Serializer.h index b722283581..a4c27399c5 100644 --- a/src/util/Serializer/Serializer.h +++ b/src/util/Serializer/Serializer.h @@ -92,8 +92,8 @@ CPP_concept Serializer = WriteSerializer || ReadSerializer; /// If we try to serialize from a const object or reference, the serializer must /// be a `WriteSerializer`. The following type trait can be used to check this /// constraint at compile time. -CPP_template(typename S, typename T)( - requires Serializer) static constexpr bool SerializerMatchesConstness = +CPP_template(typename S, typename T) (requires Serializer) +static constexpr bool SerializerMatchesConstness = WriteSerializer || !std::is_const_v>; /** @@ -178,20 +178,20 @@ CPP_template(typename S, typename T)( * instead of * `serialize(serializer, t)` */ -CPP_template(typename S, typename T)(requires Serializer) void operator|( - S& serializer, T&& t) { +CPP_template(typename S, typename T) (requires Serializer) +void operator|(S& serializer, T&& t) { serialize(serializer, AD_FWD(t)); } /// Serialization operator for explicitly writing to a serializer. -CPP_template(typename S, typename T)(requires WriteSerializer) void -operator<<(S& serializer, const T& t) { +CPP_template(typename S, typename T) (requires WriteSerializer) +void operator<<(S& serializer, const T& t) { serializer | t; } /// Serialization operator for explicitly reading from a serializer. -CPP_template(typename S, typename T)(requires ReadSerializer) void -operator>>(S& serializer, T&& t) { +CPP_template(typename S, typename T) (requires ReadSerializer) +void operator>>(S& serializer, T&& t) { serializer | t; } @@ -247,9 +247,10 @@ CPP_concept TriviallySerializable = /// Serialize function for `TriviallySerializable` types that works by simply /// serializing the binary object representation. -CPP_template(typename S, typename T)( - requires Serializer CPP_and - TriviallySerializable) void serialize(S& serializer, T&& t) { +CPP_template( + typename S, + typename T) (requires Serializer CPP_and TriviallySerializable) +void serialize(S& serializer, T&& t) { if constexpr (WriteSerializer) { serializer.serializeBytes(reinterpret_cast(&t), sizeof(t)); } else { @@ -261,8 +262,8 @@ CPP_template(typename S, typename T)( /// Arithmetic types (the builtins like int, char, double) can be trivially /// serialized. CPP_template(typename T, - typename U)(requires std::is_arithmetic_v>) - [[maybe_unused]] std::true_type allowTrivialSerialization(T, U) { + typename U) (requires std::is_arithmetic_v>) +[[maybe_unused]] std::true_type allowTrivialSerialization(T, U) { return {}; } diff --git a/src/util/Serializer/TripleSerializer.h b/src/util/Serializer/TripleSerializer.h index d2bc025657..103d170bb5 100644 --- a/src/util/Serializer/TripleSerializer.h +++ b/src/util/Serializer/TripleSerializer.h @@ -30,9 +30,10 @@ constexpr std::array magicBytes{'Q', 'L', 'E', 'V', 'E', 'R', '.', 'U', 'P', 'D', 'A', 'T', 'E'}; // Read a value of type T from the `serializer`. -CPP_template(typename T, typename Serializer)( - requires serialization::ReadSerializer) T - readValue(Serializer& serializer) { +CPP_template( + typename T, + typename Serializer) (requires serialization::ReadSerializer) +T readValue(Serializer& serializer) { T value; serializer >> value; return value; @@ -40,9 +41,9 @@ CPP_template(typename T, typename Serializer)( // Write the header of the file format to the output stream. We are currently at // version 0. -CPP_template(typename Serializer)( - requires serialization::WriteSerializer< - Serializer>) void writeHeader(Serializer& serializer) { +CPP_template( + typename Serializer) (requires serialization::WriteSerializer) +void writeHeader(Serializer& serializer) { serializer << magicBytes; uint16_t version = 0; serializer << version; @@ -50,9 +51,9 @@ CPP_template(typename Serializer)( // Read the header of the file format from the input stream and ensure that it // is correct. -CPP_template(typename Serializer)( - requires serialization::ReadSerializer< - Serializer>) void readHeader(Serializer& serializer) { +CPP_template( + typename Serializer) (requires serialization::ReadSerializer) +void readHeader(Serializer& serializer) { std::decay_t magicByteBuffer{}; serializer >> magicByteBuffer; AD_CORRECTNESS_CHECK(magicByteBuffer == magicBytes); @@ -63,10 +64,9 @@ CPP_template(typename Serializer)( // Serialize the local vocabulary to the output stream. Returns a mapping from // Ids that map to their string position in the file. -CPP_template(typename Serializer)( - requires serialization::WriteSerializer< - Serializer>) void serializeLocalVocab(Serializer& serializer, - const LocalVocab& vocab) { +CPP_template( + typename Serializer) (requires serialization::WriteSerializer) +void serializeLocalVocab(Serializer& serializer, const LocalVocab& vocab) { AD_CONTRACT_CHECK(vocab.numSets() == 1); const auto& words = vocab.primaryWordSet(); serializer << words.size(); @@ -77,10 +77,10 @@ CPP_template(typename Serializer)( } // Deserialize the local vocabulary from the input stream. -CPP_template(typename Serializer)( - requires serialization::ReadSerializer) std:: - tuple> deserializeLocalVocab( - Serializer& serializer) { +CPP_template( + typename Serializer) (requires serialization::ReadSerializer) +std::tuple> deserializeLocalVocab( + Serializer& serializer) { LocalVocab vocab; auto size = readValue(serializer); // Note:: It might happen that the `size` is zero because the local vocab was @@ -99,9 +99,9 @@ CPP_template(typename Serializer)( // Serialize a range of Ids to the output stream. If an Id is of type // LocalVocabIndex, apply the mapping to the Id before writing it. -CPP_template(typename Range, typename Serializer)( - requires ql::ranges::range) void serializeIds(Serializer& serializer, - Range&& range) { +CPP_template(typename Range, + typename Serializer) (requires ql::ranges::range) +void serializeIds(Serializer& serializer, Range&& range) { ad_utility::serialization::VectorIncrementalSerializer vectorSerializer{std::move(serializer)}; for (const Id& value : range) { @@ -113,12 +113,13 @@ CPP_template(typename Range, typename Serializer)( // Deserialize a range of Ids from the input stream. If an Id is of type // LocalVocabIndex, apply the mapping to the Id after reading it. -CPP_template(typename Serializer, typename BlankNodeFunc)( - requires ad_utility::InvocableWithConvertibleReturnType) - std::vector deserializeIds( - Serializer& serializer, const absl::flat_hash_map& mapping, - BlankNodeFunc newBlankNodeIndex) { +CPP_template( + typename Serializer, + typename BlankNodeFunc) (requires ad_utility::InvocableWithConvertibleReturnType< + BlankNodeFunc, BlankNodeIndex>) +std::vector deserializeIds(Serializer& serializer, + const absl::flat_hash_map& mapping, + BlankNodeFunc newBlankNodeIndex) { std::vector ids = readValue>(serializer); absl::flat_hash_map blankNodeMapping; for (Id& id : ids) { @@ -136,10 +137,9 @@ CPP_template(typename Serializer, typename BlankNodeFunc)( } // namespace detail // Serialize the local vocabulary and the given ranges of Ids to the given path. -CPP_template(typename Range)( - requires ql::ranges::range< - Range>) void serializeIds(const std::filesystem::path& path, - const LocalVocab& vocab, Range&& idRanges) { +CPP_template(typename Range) (requires ql::ranges::range) +void serializeIds(const std::filesystem::path& path, const LocalVocab& vocab, + Range&& idRanges) { serialization::FileWriteSerializer serializer{path.c_str()}; detail::writeHeader(serializer); detail::serializeLocalVocab(serializer, vocab); diff --git a/src/util/StringUtils.h b/src/util/StringUtils.h index 3d665f77ff..3a4b467af1 100644 --- a/src/util/StringUtils.h +++ b/src/util/StringUtils.h @@ -102,18 +102,17 @@ streams. @param separator Will be put between each of the string representations of the range elements. */ -CPP_template(typename Range)( - requires ql::ranges::input_range CPP_and - ad_utility::Streamable>>) void lazyStrJoin(std::ostream* stream, Range&& r, - std::string_view separator); +CPP_template(typename Range) ( + requires ql::ranges::input_range CPP_and ad_utility::Streamable< + ql::iter_reference_t>>) +void lazyStrJoin(std::ostream* stream, Range&& r, std::string_view separator); // Similar to the overload of `lazyStrJoin` above, but the result is returned as // a string. -CPP_template(typename Range)( - requires ql::ranges::input_range CPP_and ad_utility::Streamable< - ql::iter_reference_t>>) std::string - lazyStrJoin(Range&& r, std::string_view separator); +CPP_template(typename Range) ( + requires ql::ranges::input_range CPP_and ad_utility::Streamable< + ql::iter_reference_t>>) +std::string lazyStrJoin(Range&& r, std::string_view separator); /* @brief Adds indentation before the given string and directly after new line @@ -188,11 +187,10 @@ inline QL_CONSTEXPR bool constantTimeEquals(std::string_view view1, } // _________________________________________________________________________ -CPP_template_def(typename Range)( - requires ql::ranges::input_range CPP_and_def - ad_utility::Streamable>>) void lazyStrJoin(std::ostream* stream, Range&& r, - std::string_view separator) { +CPP_template_def( + typename Range)(requires ql::ranges::input_range CPP_and_def ad_utility:: + Streamable>>) +void lazyStrJoin(std::ostream* stream, Range&& r, std::string_view separator) { auto begin = std::begin(r); auto end = std::end(r); @@ -214,10 +212,10 @@ CPP_template_def(typename Range)( } // _________________________________________________________________________ -CPP_template_def(typename Range)( - requires ql::ranges::input_range CPP_and_def ad_utility::Streamable< - ql::iter_reference_t>>) std::string - lazyStrJoin(Range&& r, std::string_view separator) { +CPP_template_def( + typename Range)(requires ql::ranges::input_range CPP_and_def ad_utility:: + Streamable>>) +std::string lazyStrJoin(Range&& r, std::string_view separator) { std::ostringstream stream; lazyStrJoin(&stream, AD_FWD(r), separator); return std::move(stream).str(); diff --git a/src/util/Synchronized.h b/src/util/Synchronized.h index 8c5eb452fd..c71a502d49 100644 --- a/src/util/Synchronized.h +++ b/src/util/Synchronized.h @@ -99,9 +99,10 @@ class Synchronized { /// Constructor that is not copy or move, tries to instantiate the underlying /// type via perfect forwarding (this includes the default constructor) - CPP_template(typename Arg, typename... Args)(requires CPP_NOT( - ql::concepts::same_as, Synchronized>)) - QL_EXPLICIT(sizeof...(Args) == 0) Synchronized(Arg&& arg, Args&&... args) + CPP_template(typename Arg, typename... Args) (requires CPP_NOT( + ql::concepts::same_as, Synchronized>)) + QL_EXPLICIT(sizeof...(Args) == 0) + Synchronized(Arg&& arg, Args&&... args) : data_{AD_FWD(arg), AD_FWD(args)...}, m_{} {} template @@ -222,7 +223,7 @@ class Synchronized { // Return a `Synchronized` that uses a reference to this `Synchronized`'s // `_data` and `mutext_`. The reference is a reference of the Base class U. CPP_template_2(typename U)(requires std::is_base_of_v) - Synchronized toBaseReference() { + Synchronized toBaseReference() { return {ConstructWithMutex{}, mutex(), data_}; } diff --git a/src/util/TaskQueue.h b/src/util/TaskQueue.h index d4890fa31c..bd0f43704f 100644 --- a/src/util/TaskQueue.h +++ b/src/util/TaskQueue.h @@ -93,7 +93,8 @@ class TaskQueue { finishImpl(); } - CPP_member auto resetTimers() -> CPP_ret(void)(requires TrackTimes) { + CPP_member auto resetTimers() -> CPP_ret(void)(requires TrackTimes) + { pushTime_ = 0; popTime_ = 0; } @@ -115,8 +116,9 @@ class TaskQueue { } // __________________________________________________________________________ - CPP_member auto getTimeStatistics() const - -> CPP_ret(std::string)(requires TrackTimes) { + CPP_member auto getTimeStatistics() const -> CPP_ret( + std::string)(requires TrackTimes) + { return "Time spent waiting in queue " + name_ + ": " + std::to_string(pushTime_) + "ms (push), " + std::to_string(popTime_) + "ms (pop)"; diff --git a/src/util/ThreadSafeQueue.h b/src/util/ThreadSafeQueue.h index 4730f40493..f1dda99eb4 100644 --- a/src/util/ThreadSafeQueue.h +++ b/src/util/ThreadSafeQueue.h @@ -239,10 +239,11 @@ namespace detail { // queue. If the producer returns `nullopt`, `numThreads` is decremented, // and the queue is finished if `numThreads <= 0`. All exceptions that // happen during the execution of `producer` are propagated to the queue. -CPP_template(typename Queue, typename Producer)( - requires IsThreadsafeQueue CPP_and ql::concepts::invocable< - Producer>) auto makeQueueTask(Queue& queue, Producer producer, - std::atomic& numThreads) { +CPP_template(typename Queue, + typename Producer) (requires IsThreadsafeQueue CPP_and + ql::concepts::invocable) +auto makeQueueTask(Queue& queue, Producer producer, + std::atomic& numThreads) { return [&queue, producer = std::move(producer), &numThreads] { try { while (auto opt = producer()) { diff --git a/src/util/TimeTracer.h b/src/util/TimeTracer.h index 0a9552cd48..42d1d42beb 100644 --- a/src/util/TimeTracer.h +++ b/src/util/TimeTracer.h @@ -63,7 +63,7 @@ class TimeTracer { public: explicit TimeTracer(const std::string& name) : rootTrace_{name, std::chrono::milliseconds::zero()}, - activeTraces_({rootTrace_}){}; + activeTraces_({rootTrace_}) {}; virtual ~TimeTracer() = default; virtual void beginTrace(const std::string& name) { diff --git a/src/util/Timer.h b/src/util/Timer.h index b8eddac408..8488cdfe2b 100644 --- a/src/util/Timer.h +++ b/src/util/Timer.h @@ -48,9 +48,9 @@ class Timer { // Convert any `std::chrono::duration` to the underlying `Duration` type // of the `Timer` class. - CPP_template(typename T)( - requires ad_utility::isInstantiation) static Duration - toDuration(T duration) { + CPP_template( + typename T) (requires ad_utility::isInstantiation) + static Duration toDuration(T duration) { return chr::duration_cast(duration); } diff --git a/src/util/TransparentFunctors.h b/src/util/TransparentFunctors.h index adc6e88673..c81db478cb 100644 --- a/src/util/TransparentFunctors.h +++ b/src/util/TransparentFunctors.h @@ -61,14 +61,14 @@ struct GetImpl { // Implementation of `getIf` (see below). template struct GetIfImpl { - CPP_template(typename Ptr)(requires std::is_pointer_v< - ql::remove_cvref_t>) constexpr decltype(auto) - operator()(Ptr& variantPtr) const { + CPP_template( + typename Ptr) (requires std::is_pointer_v>) + constexpr decltype(auto) operator()(Ptr& variantPtr) const { return std::get_if(variantPtr); } - CPP_template(typename Ptr)(requires CPP_NOT( - std::is_pointer_v>)) constexpr decltype(auto) - operator()(Ptr& variant) const { + CPP_template( + typename Ptr) (requires CPP_NOT(std::is_pointer_v>)) + constexpr decltype(auto) operator()(Ptr& variant) const { return std::get_if(&variant); } }; diff --git a/src/util/TypeTraits.h b/src/util/TypeTraits.h index 9815b59d7e..bd5acc1222 100644 --- a/src/util/TypeTraits.h +++ b/src/util/TypeTraits.h @@ -209,10 +209,9 @@ constexpr static bool alwaysFalse = false; /// From the type Tuple (std::tuple) creates the type /// std::tuple, TypeLifter,...> CPP_template(typename Tuple, - template - typename TypeLifter)(requires isTuple) using LiftedTuple = - typename detail::LiftInnerTypes< - std::tuple, TypeLifter>::template TypeToLift::LiftedType; + template typename TypeLifter) (requires isTuple) +using LiftedTuple = typename detail::LiftInnerTypes< + std::tuple, TypeLifter>::template TypeToLift::LiftedType; // Examples: static_assert( std::is_same_v, std::optional>, @@ -221,10 +220,11 @@ static_assert( /// From the type Variant (std::variant) creates the type /// std::variant, TypeLifter,...> -CPP_template(typename Variant, template typename TypeLifter)( - requires isVariant) using LiftedVariant = - typename detail::LiftInnerTypes< - std::variant, TypeLifter>::template TypeToLift::LiftedType; +CPP_template(typename Variant, + template + typename TypeLifter) (requires isVariant) +using LiftedVariant = typename detail::LiftInnerTypes< + std::variant, TypeLifter>::template TypeToLift::LiftedType; // Examples: static_assert( std::is_same_v, std::optional>, @@ -232,8 +232,8 @@ static_assert( std::optional>>); /// From the type std::tuple makes the type std::variant -CPP_template(typename Tuple)(requires isTuple) using TupleToVariant = - typename detail::TupleToVariantImpl::type; +CPP_template(typename Tuple) (requires isTuple) +using TupleToVariant = typename detail::TupleToVariantImpl::type; // Examples: static_assert(std::is_same_v>, std::variant>); diff --git a/src/util/UniqueCleanup.h b/src/util/UniqueCleanup.h index d1fb023091..f4beef2b37 100644 --- a/src/util/UniqueCleanup.h +++ b/src/util/UniqueCleanup.h @@ -13,8 +13,11 @@ namespace ad_utility::unique_cleanup { /// Wrapper class that allows to call a function /// just before the wrapper value T is destroyed. -CPP_template(typename T, typename Func = std::function)( - requires ql::concepts::move_constructible) class UniqueCleanup { +CPP_template( + typename T, + typename Func = + std::function) (requires ql::concepts::move_constructible) +class UniqueCleanup { /// Boolean indicating if object was not moved out of ResetWhenMoved active_ = true; /// Wrapped value diff --git a/src/util/Views.h b/src/util/Views.h index 3f12094328..b0fe1f0e85 100644 --- a/src/util/Views.h +++ b/src/util/Views.h @@ -38,9 +38,11 @@ CPP_concept RangeCanEmpty = CPP_requires_ref(can_empty_, R); // `range-v3`. The implementation is taken from libstdc++-13. The additional // optional `supportsConst` argument explicitly disables const iteration for // this view when set to false, see `OwningViewNoConst` below for details. -CPP_template(typename UnderlyingRange, bool supportConst = true)( - requires ql::ranges::range CPP_and - ql::concepts::movable) class OwningView +CPP_template(typename UnderlyingRange, + bool supportConst = + true) (requires ql::ranges::range CPP_and + ql::concepts::movable) +class OwningView : public ql::ranges::view_interface> { private: UnderlyingRange underlyingRange_; @@ -73,39 +75,42 @@ CPP_template(typename UnderlyingRange, bool supportConst = true)( constexpr auto end() { return ql::ranges::end(underlyingRange_); } - CPP_auto_member constexpr auto CPP_fun(begin)()( + CPP_auto_member constexpr auto CPP_fun(begin) ()( const // requires(supportConst&& ql::ranges::range)) { return ql::ranges::begin(underlyingRange_); } - CPP_auto_member constexpr auto CPP_fun(end)()( + CPP_auto_member constexpr auto CPP_fun(end) ()( const // requires(supportConst&& ql::ranges::range)) { return ql::ranges::end(underlyingRange_); } - CPP_member constexpr auto empty() const - -> CPP_ret(bool)(requires detail::RangeCanEmpty) { + CPP_member constexpr auto empty() const -> CPP_ret( + bool)(requires detail::RangeCanEmpty) + { return ql::ranges::empty(underlyingRange_); } - CPP_member constexpr auto size() - -> CPP_ret(size_t)(requires ql::ranges::sized_range) { + CPP_member constexpr auto size() -> CPP_ret( + size_t)(requires ql::ranges::sized_range) + { return ql::ranges::size(underlyingRange_); } - CPP_member constexpr auto size() const -> CPP_ret(size_t)( - requires ql::ranges::sized_range) { + CPP_member constexpr auto size() const -> CPP_ret( + size_t)(requires ql::ranges::sized_range) + { return ql::ranges::size(underlyingRange_); } - CPP_auto_member constexpr auto CPP_fun(data)()( - requires ql::ranges::contiguous_range) { + CPP_auto_member constexpr auto + CPP_fun(data) ()(requires ql::ranges::contiguous_range) { return ql::ranges::data(underlyingRange_); } - CPP_auto_member constexpr auto CPP_fun(data)()( + CPP_auto_member constexpr auto CPP_fun(data) ()( const // requires ql::ranges::contiguous_range) { return ql::ranges::data(underlyingRange_); @@ -207,9 +212,11 @@ using all_t = decltype(allView(std::declval())); // This view is an input view that wraps another `view` transparently. When the // view is destroyed, or the iteration reaches `end`, whichever happens first, // the given `callback` is invoked. -CPP_template(typename V, typename F)( - requires ql::ranges::input_range CPP_and ql::ranges::view&& - ql::concepts::invocable) class CallbackOnEndView +CPP_template( + typename V, + typename F) (requires ql::ranges::input_range CPP_and ql::ranges::view && + ql::concepts::invocable) +class CallbackOnEndView : public ql::ranges::view_interface> { private: V base_; @@ -284,9 +291,10 @@ CallbackOnEndView(R&&, F) -> CallbackOnEndView, F>; // It yields the same elements as the underlying range, but casts them to // rvalue references via `std::move`. It is implemented via // `ql::make_move_iterator`. -CPP_template(typename UnderlyingRange)( - requires ql::ranges::view CPP_and - ql::ranges::input_range) class RvalueView +CPP_template( + typename UnderlyingRange) (requires ql::ranges::view CPP_and + ql::ranges::input_range) +class RvalueView : public ql::ranges::view_interface> { private: UnderlyingRange underlyingRange_; @@ -336,13 +344,15 @@ CPP_template(typename UnderlyingRange)( // Size function. Note: The member functions `empty` and `data` are present // via the inheritance from `view_interface` iff they are supported by the // `UnderlyingRange`. - CPP_member constexpr auto size() - -> CPP_ret(size_t)(requires ql::ranges::sized_range) { + CPP_member constexpr auto size() -> CPP_ret( + size_t)(requires ql::ranges::sized_range) + { return ql::ranges::size(underlyingRange_); } - CPP_member constexpr auto size() const -> CPP_ret(size_t)( - requires ql::ranges::sized_range) { + CPP_member constexpr auto size() const -> CPP_ret( + size_t)(requires ql::ranges::sized_range) + { return ql::ranges::size(underlyingRange_); } }; @@ -357,9 +367,9 @@ RvalueView(Range&&) -> RvalueView>; // fulfill the predicate anymore. This is technically undefined behavior, but // works in practice if the filter_view is treated as an `input_range`. // In C++26 this will become obsolete by `std::views::to_input`. -CPP_template(typename V)(requires ql::ranges::view CPP_and - ql::ranges::input_range) class ForceInputView - : public ql::ranges::view_interface> { +CPP_template( + typename V) (requires ql::ranges::view CPP_and ql::ranges::input_range) +class ForceInputView : public ql::ranges::view_interface> { private: V base_; bool beginWasCalled_ = false; @@ -446,8 +456,8 @@ CPP_template(typename V)(requires ql::ranges::view CPP_and }; // Deduction guides -CPP_template(typename Range)(requires ql::ranges::input_range) - ForceInputView(Range&&) -> ForceInputView>; +CPP_template(typename Range) (requires ql::ranges::input_range) +ForceInputView(Range&&) -> ForceInputView>; namespace detail { // The implementation of `bufferedAsyncView` (see below). It yields its result @@ -518,8 +528,8 @@ auto bufferedAsyncView(View view, uint64_t blockSize) { // `ql::views::iota(0, size_t(INT_MAX) + 1)` leads to undefined behavior // because of an integer overflow, but `ad_utility::integerRange(size_t(INT_MAX) // + 1)` is perfectly safe and behaves as expected. -CPP_template(typename Int)(requires ql::concepts::unsigned_integral< - Int>) auto integerRange(Int upperBound) { +CPP_template(typename Int) (requires ql::concepts::unsigned_integral) +auto integerRange(Int upperBound) { return ql::views::iota(Int{0}, upperBound); } diff --git a/src/util/antlr/ANTLRErrorHandling.h b/src/util/antlr/ANTLRErrorHandling.h index 40c0782488..c8af69ef8b 100644 --- a/src/util/antlr/ANTLRErrorHandling.h +++ b/src/util/antlr/ANTLRErrorHandling.h @@ -32,12 +32,12 @@ antlr error message are included as exception cause. For an example of a valid `GrammarParseException` see `InvalidSparqlQueryException`. */ -CPP_template(typename GrammarParseException)( - requires ql::concepts::derived_from - CPP_and ql::concepts::constructible_from< - GrammarParseException, std::string_view, - std::optional>) struct ThrowingErrorListener - : public antlr4::BaseErrorListener { +CPP_template(typename GrammarParseException) ( + requires ql::concepts::derived_from + CPP_and ql::concepts::constructible_from< + GrammarParseException, std::string_view, + std::optional>) +struct ThrowingErrorListener : public antlr4::BaseErrorListener { void syntaxError(antlr4::Recognizer* recognizer, antlr4::Token* offendingSymbol, size_t line, size_t charPositionInLine, const std::string& msg, diff --git a/src/util/http/HttpServer.h b/src/util/http/HttpServer.h index c58b8c4617..a3ae85d40c 100644 --- a/src/util/http/HttpServer.h +++ b/src/util/http/HttpServer.h @@ -50,11 +50,12 @@ ad_utility::MemorySize getRequestBodyLimit(); * a `net::awaitable`. It is only called if the request is a valid * websocket upgrade request and the URL represents a valid path. */ -CPP_template(typename HttpHandler, typename WebSocketHandler)( - requires ad_utility::InvocableWithExactReturnType< - WebSocketHandler, net::awaitable, - const http::request&, - tcp::socket>) class HttpServer { +CPP_template( + typename HttpHandler, + typename WebSocketHandler) (requires ad_utility::InvocableWithExactReturnType< + WebSocketHandler, net::awaitable, + const http::request&, tcp::socket>) +class HttpServer { private: HttpHandler httpHandler_; int numServerThreads_; @@ -81,17 +82,12 @@ CPP_template(typename HttpHandler, typename WebSocketHandler)( static constexpr bool isSupplier = ad_utility::InvocableWithConvertibleReturnType< HandlerSupplier, WebSocketHandler, net::io_context&>; - CPP_template_2(typename HandlerSupplier)( - requires isSupplier< - HandlerSupplier>) explicit HttpServer(unsigned short port, - std::string_view ipAddress = - "0.0.0.0", - int numServerThreads = 1, - HttpHandler handler = - HttpHandler{}, - HandlerSupplier - webSocketHandlerSupplier = - {}) + CPP_template_2(typename HandlerSupplier)(requires isSupplier) + explicit HttpServer(unsigned short port, + std::string_view ipAddress = "0.0.0.0", + int numServerThreads = 1, + HttpHandler handler = HttpHandler{}, + HandlerSupplier webSocketHandlerSupplier = {}) : httpHandler_{std::move(handler)}, // We need at least two threads to avoid blocking. // TODO why is that? diff --git a/src/util/http/HttpUtils.h b/src/util/http/HttpUtils.h index 8878ab8d9b..6ba7643ec8 100644 --- a/src/util/http/HttpUtils.h +++ b/src/util/http/HttpUtils.h @@ -128,25 +128,19 @@ inline http::response createHttpResponseFromString( * @param mediaType The media type of the response. * @return A http::response which is ready to be sent. */ -CPP_template(typename RequestType)( - requires HttpRequest< - RequestType>) auto createHttpResponseFromString(std::string body, - http::status status, - const RequestType& - request, - std::optional - mediaType) { +CPP_template(typename RequestType) (requires HttpRequest) +auto createHttpResponseFromString(std::string body, http::status status, + const RequestType& request, + std::optional mediaType) { return createHttpResponseFromString(std::move(body), status, mediaType, request.keep_alive(), request.version()); } /// Create a HttpResponse from a string with status 200 OK. Otherwise behaves /// the same as createHttpResponseFromString. -CPP_template(typename RequestType)( - requires HttpRequest< - RequestType>) static auto createOkResponse(std::string text, - const RequestType& request, - MediaType mediaType) { +CPP_template(typename RequestType) (requires HttpRequest) +static auto createOkResponse(std::string text, const RequestType& request, + MediaType mediaType) { return createHttpResponseFromString(std::move(text), http::status::ok, request, mediaType); } @@ -154,13 +148,10 @@ CPP_template(typename RequestType)( /// Assign the generator to the body of the response. If a supported /// compression is specified in the request, this method is applied to the /// body and the corresponding response headers are set. -CPP_template(typename RequestType)( - requires HttpRequest< - RequestType>) static void setBody(http::response& - response, - const RequestType& request, - cppcoro::generator&& - generator) { +CPP_template(typename RequestType) (requires HttpRequest) +static void setBody(http::response& response, + const RequestType& request, + cppcoro::generator&& generator) { using ad_utility::content_encoding::CompressionMethod; CompressionMethod method = @@ -184,13 +175,9 @@ CPP_template(typename RequestType)( } /// Create a HttpResponse from a generator with status 200 OK. -CPP_template(typename RequestType)( - requires HttpRequest< - RequestType>) static auto createOkResponse(cppcoro:: - generator&& - generator, - const RequestType& request, - MediaType mediaType) { +CPP_template(typename RequestType) (requires HttpRequest) +static auto createOkResponse(cppcoro::generator&& generator, + const RequestType& request, MediaType mediaType) { http::response response{http::status::ok, request.version()}; response.set(http::field::content_type, toString(mediaType)); response.keep_alive(request.keep_alive()); @@ -217,44 +204,33 @@ CPP_concept IsJson = SameAsAny; /// Create a HttpResponse from a json object with status 200 OK and mime type /// "application/json". -CPP_template(typename Json)( - requires IsJson< - Json>) static auto createJsonResponse(const Json& j, - const auto& request, - http::status status = - http::status::ok) { +CPP_template(typename Json) (requires IsJson) +static auto createJsonResponse(const Json& j, const auto& request, + http::status status = http::status::ok) { // Argument `4` leads to a human-readable indentation. return createJsonResponse(j.dump(4), request, status); } /// Create a HttpResponse with status 404 Not Found. -CPP_template(typename RequestType)( - requires HttpRequest< - RequestType>) static auto createNotFoundResponse(const std::string& - errorMsg, - const RequestType& - request) { +CPP_template(typename RequestType) (requires HttpRequest) +static auto createNotFoundResponse(const std::string& errorMsg, + const RequestType& request) { return createHttpResponseFromString(errorMsg, http::status::not_found, request, MediaType::textPlain); } /// Create a HttpResponse with status 403 Forbidden. -CPP_template(typename RequestType)( - requires HttpRequest< - RequestType>) static auto createForbiddenResponse(const std::string& - errorMsg, - const RequestType& - request) { +CPP_template(typename RequestType) (requires HttpRequest) +static auto createForbiddenResponse(const std::string& errorMsg, + const RequestType& request) { return createHttpResponseFromString(errorMsg, http::status::forbidden, request, MediaType::textPlain); } /// Create a HttpResponse with status 400 Bad Request. -CPP_template(typename RequestType)( - requires HttpRequest< - RequestType>) static auto createBadRequestResponse(std::string body, - const RequestType& - request) { +CPP_template(typename RequestType) (requires HttpRequest) +static auto createBadRequestResponse(std::string body, + const RequestType& request) { return createHttpResponseFromString(std::move(body), http::status::bad_request, request, MediaType::textPlain); diff --git a/src/util/json.h b/src/util/json.h index 6e0c8b7df0..230c41eb6f 100644 --- a/src/util/json.h +++ b/src/util/json.h @@ -49,8 +49,8 @@ CPP_concept OrderedOrUnorderedJson = @param jsonFileName Name of the file, or path to the file. Must describe a `.json` file. */ -CPP_template(typename Json)(requires OrderedOrUnorderedJson) Json - fileToJson(std::string_view jsonFileName) { +CPP_template(typename Json) (requires OrderedOrUnorderedJson) +Json fileToJson(std::string_view jsonFileName) { // Check, if the filename/-path ends with ".json". Checking, if it's a valid // file, is done by `ad_utility::makeIfstream`. if (!ql::ends_with(jsonFileName, ".json")) { @@ -72,8 +72,8 @@ CPP_template(typename Json)(requires OrderedOrUnorderedJson) Json @brief Returns the string representation of the type of the given `nlohmann::json`. Only supports official json types. */ -CPP_template(typename T)(requires OrderedOrUnorderedJson) inline std::string - jsonToTypeString(const T& j) { +CPP_template(typename T) (requires OrderedOrUnorderedJson) +inline std::string jsonToTypeString(const T& j) { if (j.is_array()) { return "array"; } else if (j.is_boolean()) { @@ -107,9 +107,8 @@ in such cases will always return a `std::optional`, that contains no value. namespace nlohmann { template struct adl_serializer> { - CPP_template(typename S)( - requires OrderedOrUnorderedJson< - S>) static void to_json(S& j, const std::optional& opt) { + CPP_template(typename S) (requires OrderedOrUnorderedJson) + static void to_json(S& j, const std::optional& opt) { if (opt.has_value()) { j = opt.value(); } else { @@ -117,9 +116,8 @@ struct adl_serializer> { } } - CPP_template(typename S)(requires OrderedOrUnorderedJson< - S>) static void from_json(const S& j, - std::optional& opt) { + CPP_template(typename S) (requires OrderedOrUnorderedJson) + static void from_json(const S& j, std::optional& opt) { if (j.is_null()) { opt = std::nullopt; } else { @@ -134,16 +132,14 @@ struct adl_serializer> { namespace nlohmann { template <> struct adl_serializer { - CPP_template(typename S)(requires OrderedOrUnorderedJson< - S>) static void to_json(S& j, - const std::monostate&) { + CPP_template(typename S) (requires OrderedOrUnorderedJson) + static void to_json(S& j, const std::monostate&) { // Monostate is just an empty placeholder value. j = nullptr; } - CPP_template(typename S)(requires OrderedOrUnorderedJson< - S>) static void from_json(const S& j, - const std::monostate&) { + CPP_template(typename S) (requires OrderedOrUnorderedJson) + static void from_json(const S& j, const std::monostate&) { /* Monostate holds no values, so the given monostate is already identical to the serialized one. @@ -174,9 +170,8 @@ Example: The serialized format for a `std::variant` containing a namespace nlohmann { template struct adl_serializer> { - CPP_template(typename S)( - requires OrderedOrUnorderedJson< - S>) static void to_json(S& j, const std::variant& var) { + CPP_template(typename S) (requires OrderedOrUnorderedJson) + static void to_json(S& j, const std::variant& var) { // We need to save, which of the types the std::variant actually // uses. j["index"] = var.index(); @@ -189,9 +184,8 @@ struct adl_serializer> { std::visit([&j](const auto& value) { j["value"] = value; }, var); } - CPP_template(typename S)( - requires OrderedOrUnorderedJson< - S>) static void from_json(const S& j, std::variant& var) { + CPP_template(typename S) (requires OrderedOrUnorderedJson) + static void from_json(const S& j, std::variant& var) { // Which of the `sizeof...(Types)` possible value types, was the // serialized std::variant using? size_t index = j["index"].template get(); @@ -227,9 +221,8 @@ namespace nlohmann { template struct adl_serializer, std::enable_if_t>> { - CPP_template(typename S)( - requires OrderedOrUnorderedJson< - S>) static void to_json(S& j, const std::unique_ptr& ptr) { + CPP_template(typename S) (requires OrderedOrUnorderedJson) + static void to_json(S& j, const std::unique_ptr& ptr) { // Does the `unique_ptr` hold anything? If yes, save the dereferenced // object, if no, save a `nullptr`. if (ptr) { @@ -239,9 +232,8 @@ struct adl_serializer, } } - CPP_template(typename S)(requires OrderedOrUnorderedJson< - S>) static void from_json(const S& j, - std::unique_ptr& ptr) { + CPP_template(typename S) (requires OrderedOrUnorderedJson) + static void from_json(const S& j, std::unique_ptr& ptr) { if (j.is_null()) { // If `json` is null, we just delete the content of ptr, because it // should be an empty `unique_ptr`. diff --git a/src/util/stream_generator.h b/src/util/stream_generator.h index 4e8d3b3084..79bc25cf45 100644 --- a/src/util/stream_generator.h +++ b/src/util/stream_generator.h @@ -107,8 +107,8 @@ class stream_generator_promise { // Overload so we can also pass char values, template such that all types that // implicitly convert to char are not accepted. - CPP_template(typename CharT)(requires SimilarTo) - suspend_sometimes yield_value(CharT value) { + CPP_template(typename CharT) (requires SimilarTo) + suspend_sometimes yield_value(CharT value) { std::string_view singleView{&value, 1}; // This is only safe to do if we can write into the buffer immediately. AD_CORRECTNESS_CHECK(isBufferLargeEnough(singleView)); diff --git a/src/util/views/TakeUntilInclusiveView.h b/src/util/views/TakeUntilInclusiveView.h index d07d473ac8..aeb889c593 100644 --- a/src/util/views/TakeUntilInclusiveView.h +++ b/src/util/views/TakeUntilInclusiveView.h @@ -30,10 +30,13 @@ namespace ad_utility { // caveat however, that `operator*` is NOT THREADSAFE, although it is marked // `const` because it has to modify mutable state that tracks, whether the // predicate has already been evaluated for the current element. -CPP_template(typename V, typename Pred)( - requires ql::ranges::input_range&& ql::ranges::view&& - std::is_object_v&& ql::concepts::indirect_unary_predicate< - const Pred, ql::ranges::iterator_t>) class TakeUntilInclusiveView +CPP_template( + typename V, + typename Pred) (requires ql::ranges::input_range && ql::ranges::view && + std::is_object_v && + ql::concepts::indirect_unary_predicate>) +class TakeUntilInclusiveView : public ql::ranges::view_interface> { private: V base_; @@ -159,8 +162,8 @@ namespace views { // other views. struct takeUntilInclusiveFn { CPP_template(typename R, - typename Pred)(requires ql::ranges::viewable_range) auto - operator()(R&& r, Pred pred) const { + typename Pred) (requires ql::ranges::viewable_range) + auto operator()(R&& r, Pred pred) const { return TakeUntilInclusiveView{ad_utility::allView(std::forward(r)), std::move(pred)}; } diff --git a/test/AsioHelpersTest.cpp b/test/AsioHelpersTest.cpp index 0537b69e6d..670e6f0f1e 100644 --- a/test/AsioHelpersTest.cpp +++ b/test/AsioHelpersTest.cpp @@ -20,8 +20,7 @@ TEST(AsioHelpers, runFunctionOnExecutorVoid) { net::io_context ctx; bool a = false; auto workGuard = makeWorkGuard(ctx); - runFunctionOnExecutor( - ctx.get_executor(), [&]() { a = true; }, net::detached); + runFunctionOnExecutor(ctx.get_executor(), [&]() { a = true; }, net::detached); EXPECT_FALSE(a); ctx.poll(); EXPECT_TRUE(a); diff --git a/test/BenchmarkMeasurementContainerTest.cpp b/test/BenchmarkMeasurementContainerTest.cpp index 095e78b695..98b36219ac 100644 --- a/test/BenchmarkMeasurementContainerTest.cpp +++ b/test/BenchmarkMeasurementContainerTest.cpp @@ -26,8 +26,7 @@ namespace ad_benchmark { static auto createWaitLambda(std::chrono::milliseconds waitDuration) { return [waitDuration]() { auto end = std::chrono::steady_clock::now() + waitDuration; - while (std::chrono::steady_clock::now() < end) - ; + while (std::chrono::steady_clock::now() < end); }; } diff --git a/test/ChunkedForLoopTest.cpp b/test/ChunkedForLoopTest.cpp index b04c6ca6c7..43be32a10f 100644 --- a/test/ChunkedForLoopTest.cpp +++ b/test/ChunkedForLoopTest.cpp @@ -14,8 +14,7 @@ using ad_utility::chunkedForLoop; TEST(ChunkedForLoop, testEmptyRange) { bool flag = false; - chunkedForLoop<1>( - 0, 0, [&](size_t) { flag = true; }, [&]() { flag = true; }); + chunkedForLoop<1>(0, 0, [&](size_t) { flag = true; }, [&]() { flag = true; }); chunkedForLoop<10>( 0, 0, [&](size_t) { flag = true; }, [&]() { flag = true; }); chunkedForLoop<100>( @@ -29,8 +28,7 @@ TEST(ChunkedForLoop, testEmptyRange) { // _____________________________________________________________________________________________________________________ TEST(ChunkedForLoop, testReverseRange) { bool flag = false; - chunkedForLoop<1>( - 1, 0, [&](size_t) { flag = true; }, [&]() { flag = true; }); + chunkedForLoop<1>(1, 0, [&](size_t) { flag = true; }, [&]() { flag = true; }); chunkedForLoop<10>( 2, 0, [&](size_t) { flag = true; }, [&]() { flag = true; }); chunkedForLoop<100>( diff --git a/test/ConcurrentCacheTest.cpp b/test/ConcurrentCacheTest.cpp index b5f97f2914..0acd8cef36 100644 --- a/test/ConcurrentCacheTest.cpp +++ b/test/ConcurrentCacheTest.cpp @@ -540,8 +540,7 @@ TEST(ConcurrentCache, computeButDontStore) { // the cache. auto alwaysSuitable = [](auto&&) { return true; }; // Store the element in the cache. - cache.computeOnce( - 42, []() { return "42"; }, false, alwaysSuitable); + cache.computeOnce(42, []() { return "42"; }, false, alwaysSuitable); // The result is read from the cache, so we get "42", not "blubb". auto res = cache.computeButDontStore( diff --git a/test/ConfigManagerTest.cpp b/test/ConfigManagerTest.cpp index f030458bc7..39bdf79b42 100644 --- a/test/ConfigManagerTest.cpp +++ b/test/ConfigManagerTest.cpp @@ -1204,7 +1204,8 @@ struct AddValidatorToConfigManager { template void operator()(size_t variant, ConfigManager& m, ConstConfigOptionProxy... validatorArguments) const - requires(sizeof...(Ts) == sizeof...(validatorArguments)) { + requires(sizeof...(Ts) == sizeof...(validatorArguments)) + { // Add the new validator addValidatorFunction( AdjustVariantArgument{}.template operator()(variant), @@ -1237,9 +1238,8 @@ struct TestGeneratedValidatorsOfConfigManager { const nlohmann::json& defaultValues, const QL_CONCEPT_OR_NOTHING( ql::concepts::same_as< - nlohmann::json::json_pointer>) auto&... configOptionPaths) - -> CPP_ret(void)(requires(sizeof...(Ts) == - sizeof...(configOptionPaths))) { + nlohmann::json::json_pointer>) auto&... configOptionPaths) -> CPP_ret(void)(requires(sizeof...(Ts) == sizeof...(configOptionPaths))) + { // Using the invariant of our function generator, to create valid // and none valid values for all added validators. for (size_t validatorNumber = variantStart; validatorNumber < variantEnd; @@ -1301,7 +1301,8 @@ struct DoTestNoValidatorInSubManager { ConfigManager& m, const nlohmann::json& defaultValues, const std::pair>&... validatorArguments) const - requires(sizeof...(Ts) == sizeof...(validatorArguments)) { + requires(sizeof...(Ts) == sizeof...(validatorArguments)) + { // How many validators are to be added? constexpr size_t NUMBER_OF_VALIDATORS{5}; @@ -1350,7 +1351,8 @@ struct DoTestAlwaysValidatorInSubManager { const nlohmann::json& defaultValues, const std::pair>&... validatorArguments) const - requires(sizeof...(Ts) == sizeof...(validatorArguments)) { + requires(sizeof...(Ts) == sizeof...(validatorArguments)) + { // How many validators are to be added to each of the managers? constexpr size_t NUMBER_OF_VALIDATORS{5}; @@ -2311,7 +2313,7 @@ struct ConfigOptionsAndValidatorsOrder { // Appends the content of an different `ConfigOptionsAndValidatorsOrder`. template - requires isSimilar + requires isSimilar void append(T&& order) { appendVector(configOptions_, AD_FWD(order).configOptions_); appendVector(validators_, AD_FWD(order).validators_); diff --git a/test/ConfigOptionProxyTest.cpp b/test/ConfigOptionProxyTest.cpp index 11eb8ae43e..2b1e186aaa 100644 --- a/test/ConfigOptionProxyTest.cpp +++ b/test/ConfigOptionProxyTest.cpp @@ -52,9 +52,10 @@ struct DoTest { @tparam OptionType Exists to define, if the test should be done with `ConfigOption`, or `const ConfigOption`. */ -CPP_template(template typename ProxyType, typename OptionType)( - requires SameAsAny) void basicConstructorTest() { +CPP_template( + template typename ProxyType, + typename OptionType) (requires SameAsAny) +void basicConstructorTest() { // Do the test for all possible types. doForTypeInConfigOptionValueType(DoTest{}); } diff --git a/test/ConfigOptionTest.cpp b/test/ConfigOptionTest.cpp index b140f5258d..1e3005dc7d 100644 --- a/test/ConfigOptionTest.cpp +++ b/test/ConfigOptionTest.cpp @@ -351,11 +351,9 @@ struct CheckConfigOptionSetValue { void operator()() const { if constexpr (!std::is_same_v && !(std::is_same_v && - std::is_same_v< - CurrentType, - size_t>)&&!(std::is_same_v> && - std::is_same_v>)) { + std::is_same_v) && + !(std::is_same_v> && + std::is_same_v>)) { ASSERT_THROW( option.setValueWithJson( getConversionTestCase().jsonRepresentation), diff --git a/test/ConstexprUtilsTest.cpp b/test/ConstexprUtilsTest.cpp index 48be9e6daa..6404464d21 100644 --- a/test/ConstexprUtilsTest.cpp +++ b/test/ConstexprUtilsTest.cpp @@ -194,7 +194,8 @@ TEST(ConstexprUtils, RuntimeValueToCompileTimeValue) { // A helper struct for the following test. struct F1 { - CPP_template(int i)(requires(i == 0 || i == 1)) int operator()() const { + CPP_template(int i) (requires(i == 0 || i == 1)) + int operator()() const { return i + 1; } }; diff --git a/test/GetPrefilterExpressionFromSparqlExpressionTest.cpp b/test/GetPrefilterExpressionFromSparqlExpressionTest.cpp index abfeb3b508..e61a53c559 100644 --- a/test/GetPrefilterExpressionFromSparqlExpressionTest.cpp +++ b/test/GetPrefilterExpressionFromSparqlExpressionTest.cpp @@ -49,8 +49,8 @@ const auto equalityCheckPrefilterVectors = const PrefilterExprVariablePair& expPair) { if (*resPair.first != *expPair.first || resPair.second != expPair.second) { std::stringstream stream; - stream << "The following value pairs don't match:" - << "\nRESULT: " << *resPair.first << "EXPECTED: " << *expPair.first + stream << "The following value pairs don't match:" << "\nRESULT: " + << *resPair.first << "EXPECTED: " << *expPair.first << "RESULT: VARIABLE" << resPair.second.name() << "\nEXPECTED: VARIABLE" << expPair.second.name() << std::endl; ADD_FAILURE() << stream.str(); diff --git a/test/IdTableHelpersTest.cpp b/test/IdTableHelpersTest.cpp index 9550d1be41..4f3f4218a8 100644 --- a/test/IdTableHelpersTest.cpp +++ b/test/IdTableHelpersTest.cpp @@ -30,10 +30,11 @@ elements will not be ignored. @param setToCalculateFor The container to calculate all sub-sets for. Will only be read. */ -CPP_template(typename R, - typename E = std::iter_value_t>)( - requires ql::ranges::forward_range) - std::vector> calculateAllSubSets(R&& setToCalculateFor) { +CPP_template( + typename R, + typename E = std::iter_value_t< + ql::ranges::iterator_t>) (requires ql::ranges::forward_range) +std::vector> calculateAllSubSets(R&& setToCalculateFor) { // Getting rid of duplicated elements. std::vector> calculatedSubSets; diff --git a/test/JsonUtilTest.cpp b/test/JsonUtilTest.cpp index 3140a172fb..dd186c01bd 100644 --- a/test/JsonUtilTest.cpp +++ b/test/JsonUtilTest.cpp @@ -14,11 +14,10 @@ /* @brief Do the `fileToJson` test with the wanted json class type. */ -CPP_template(typename WantedJsonClassType)( - requires OrderedOrUnorderedJson< - WantedJsonClassType>) static void doFileToJsonTest(ad_utility:: - source_location l = - AD_CURRENT_SOURCE_LOC()) { +CPP_template( + typename WantedJsonClassType) (requires OrderedOrUnorderedJson) +static void doFileToJsonTest( + ad_utility::source_location l = AD_CURRENT_SOURCE_LOC()) { // For generating better messages, when failing a test. auto trace{generateLocationTrace(l, "doFileToJsonTest")}; diff --git a/test/MessageSenderTest.cpp b/test/MessageSenderTest.cpp index f64b07683c..e091e6017a 100644 --- a/test/MessageSenderTest.cpp +++ b/test/MessageSenderTest.cpp @@ -35,7 +35,9 @@ ASYNC_TEST(MessageSender, destructorCallsSignalEnd) { // Create and immediately destroy a `MessageSender` s.t. we can test the side // effects of the destructor. - { MessageSender dummy{std::move(queryId), queryHub}; } + { + MessageSender dummy{std::move(queryId), queryHub}; + } auto impl = [&]() -> net::awaitable { net::steady_timer timer{ioContext, 2s}; diff --git a/test/PrefilterExpressionTestHelpers.h b/test/PrefilterExpressionTestHelpers.h index e0eb136a52..310640467d 100644 --- a/test/PrefilterExpressionTestHelpers.h +++ b/test/PrefilterExpressionTestHelpers.h @@ -237,10 +237,10 @@ std::unique_ptr makeIsDatatypeStartsWithExpression( } // namespace //______________________________________________________________________________ -CPP_template(typename... Args)( - requires(ql::concepts::convertible_to&&...)) - std::unique_ptr inSprqlExpr(VariantArgs first, - Args&&... argList) { +CPP_template( + typename... Args) (requires(ql::concepts::convertible_to&&...)) +std::unique_ptr inSprqlExpr(VariantArgs first, + Args&&... argList) { std::vector> childrenSparql; childrenSparql.reserve(sizeof...(argList)); (childrenSparql.push_back( diff --git a/test/QueryIdTest.cpp b/test/QueryIdTest.cpp index b8118bdb92..08505e6234 100644 --- a/test/QueryIdTest.cpp +++ b/test/QueryIdTest.cpp @@ -37,7 +37,9 @@ TEST(QueryId, checkEmptyIdDisallowedByConstruction) { // moved out of, but we check for it anyway to provide a reference case TEST(QueryId, checkEmptyAfterMove) { auto queryId = QueryId::idFromString("53.32794768794578, -2.230040905974742"); - { auto temporary = std::move(queryId); } + { + auto temporary = std::move(queryId); + } EXPECT_TRUE(queryId.empty()); } diff --git a/test/QueryPlannerTestHelpers.h b/test/QueryPlannerTestHelpers.h index a73f2541d7..0c3f05156c 100644 --- a/test/QueryPlannerTestHelpers.h +++ b/test/QueryPlannerTestHelpers.h @@ -77,11 +77,10 @@ QetMatcher RootOperation(M matcher) { } // Match the `getChildren` method of an `Operation`. -CPP_template(typename... ChildArgs)( - requires(...&& ql::concepts::same_as)) // - inline Matcher children( - const ChildArgs&... childMatchers) { +CPP_template( + typename... ChildArgs) (requires(...&& ql::concepts::same_as)) // +inline Matcher children(const ChildArgs&... childMatchers) { return Property("getChildren", &Operation::getChildren, ElementsAre(Pointee(childMatchers)...)); } @@ -91,9 +90,9 @@ CPP_template(typename... ChildArgs)( // `childMatcher`s. Note that the child matchers are not ordered. template struct MatchTypeAndUnorderedChildrenImpl { - CPP_template(typename... ChildArgs)( - requires(...&& ql::concepts::same_as)) auto - operator()(const ChildArgs&... childMatchers) const { + CPP_template( + typename... ChildArgs) (requires(...&& ql::concepts::same_as)) + auto operator()(const ChildArgs&... childMatchers) const { return RootOperation( AllOf(Property("getChildren", &Operation::getChildren, UnorderedElementsAre(Pointee(childMatchers)...)))); @@ -108,9 +107,9 @@ auto MatchTypeAndUnorderedChildren = // appear in exact the correct order. template struct MatchTypeAndOrderedChildrenImpl { - CPP_template(typename... ChildArgs)( - requires(...&& ql::concepts::same_as)) auto - operator()(const ChildArgs&... childMatchers) const { + CPP_template( + typename... ChildArgs) (requires(...&& ql::concepts::same_as)) + auto operator()(const ChildArgs&... childMatchers) const { return RootOperation(AllOf(children(childMatchers...))); } }; diff --git a/test/RandomTest.cpp b/test/RandomTest.cpp index 6544f03442..c90f529f9a 100644 --- a/test/RandomTest.cpp +++ b/test/RandomTest.cpp @@ -28,9 +28,9 @@ numbers for the same seed. @param randomNumberGeneratorFactory An invocable object, that should return a random number generator, using the given seed. */ -CPP_template(typename T)(requires std::invocable) void testSeed( - T randomNumberGeneratorFactory, - ad_utility::source_location l = AD_CURRENT_SOURCE_LOC()) { +CPP_template(typename T) (requires std::invocable) +void testSeed(T randomNumberGeneratorFactory, + ad_utility::source_location l = AD_CURRENT_SOURCE_LOC()) { // For generating better messages, when failing a test. auto trace{generateLocationTrace(l, "testSeed")}; @@ -103,15 +103,14 @@ random number generator, using the given range and seed. Functionparameters should be `RangeNumberType rangeMin, RangeNumberType rangeMax, Seed seed`. @param ranges The ranges, that should be used. */ -CPP_template(typename RangeNumberType, typename GeneratorFactory)( - requires std::invocable< - GeneratorFactory, RangeNumberType, RangeNumberType, - RandomSeed>) void testSeedWithRange(GeneratorFactory - randomNumberGeneratorFactory, - const std::vector>& ranges, - ad_utility::source_location l = - AD_CURRENT_SOURCE_LOC()) { +CPP_template( + typename RangeNumberType, + typename GeneratorFactory) (requires std::invocable) +void testSeedWithRange( + GeneratorFactory randomNumberGeneratorFactory, + const std::vector>& ranges, + ad_utility::source_location l = AD_CURRENT_SOURCE_LOC()) { // For generating better messages, when failing a test. auto trace{generateLocationTrace(l, "testSeedWithRange")}; @@ -133,16 +132,13 @@ of the range. @param ranges The ranges, for which should be tested for. */ -CPP_template(typename Generator, typename RangeNumberType)( - requires std::constructible_from&& - ql::concepts::invocable&& ad_utility::isSimilar< - std::invoke_result_t, - RangeNumberType>) void testRange(const std:: - vector>& ranges, - ad_utility::source_location l = - AD_CURRENT_SOURCE_LOC()) { +CPP_template(typename Generator, typename RangeNumberType) ( + requires std::constructible_from && + ql::concepts::invocable && + ad_utility::isSimilar, RangeNumberType>) +void testRange(const std::vector>& ranges, + ad_utility::source_location l = AD_CURRENT_SOURCE_LOC()) { // For generating better messages, when failing a test. auto trace{generateLocationTrace(l, "testRange")}; diff --git a/test/RdfParserTest.cpp b/test/RdfParserTest.cpp index f7fcd6506b..3dc7275adf 100644 --- a/test/RdfParserTest.cpp +++ b/test/RdfParserTest.cpp @@ -1436,7 +1436,7 @@ TEST(RdfParserTest, EncodedIriManagerUsage) { // Test lambda that reduces boilerplate auto testIriAtPosition = [&](auto parserFactory, const std::string& tripleStr, - TripleComponent TurtleTriple::*position, + TripleComponent TurtleTriple::* position, bool shouldEncode, const std::string& expectedValue) { auto parser = parserFactory(); @@ -1502,7 +1502,7 @@ TEST(RdfParserTest, EncodedIriManagerPrefixedNames) { // Meta-matcher that creates matchers for encoded IRIs at any position in a // triple - auto makeTripleMatcher = [&](TripleComponent TurtleTriple::*memberPtr) { + auto makeTripleMatcher = [&](TripleComponent TurtleTriple::* memberPtr) { return [&, memberPtr](const std::string& expectedDecodedIri) { return ::testing::Field( memberPtr, diff --git a/test/RelationalExpressionTest.cpp b/test/RelationalExpressionTest.cpp index 4dbdbbf725..edb5972307 100644 --- a/test/RelationalExpressionTest.cpp +++ b/test/RelationalExpressionTest.cpp @@ -42,10 +42,9 @@ const auto NaN = std::numeric_limits::quiet_NaN(); // Create and return a `RelationalExpression` with the given Comparison and the // given operands `leftValue` and `rightValue`. -CPP_template(Comparison comp, typename L, typename R)( - requires SingleExpressionResult CPP_and - SingleExpressionResult) auto makeExpression(L leftValue, - R rightValue) { +CPP_template(Comparison comp, typename L, typename R) ( + requires SingleExpressionResult CPP_and SingleExpressionResult) +auto makeExpression(L leftValue, R rightValue) { auto leftChild = std::make_unique(std::move(leftValue)); auto rightChild = std::make_unique(std::move(rightValue)); @@ -55,9 +54,9 @@ CPP_template(Comparison comp, typename L, typename R)( } CPP_template(typename L, - typename... R)(requires SingleExpressionResult CPP_and( - SingleExpressionResult&&...)) auto makeInExpression(L leftValue, - R... rightValues) { + typename... R) (requires SingleExpressionResult CPP_and( + SingleExpressionResult && ...)) +auto makeInExpression(L leftValue, R... rightValues) { auto leftChild = std::make_unique(std::move(leftValue)); std::vector rightChildren; (..., (rightChildren.push_back( diff --git a/test/SparqlExpressionTest.cpp b/test/SparqlExpressionTest.cpp index 47ef93c95b..2f823e0975 100644 --- a/test/SparqlExpressionTest.cpp +++ b/test/SparqlExpressionTest.cpp @@ -112,8 +112,8 @@ concept VectorOrExpressionResult = // Convert a `VectorOrExpressionResult` (see above) to a type that is supported // by the expression module. -CPP_template(typename T)( - requires VectorOrExpressionResult) auto toExpressionResult(T vec) { +CPP_template(typename T) (requires VectorOrExpressionResult) +auto toExpressionResult(T vec) { if constexpr (SingleExpressionResult) { return vec; } else if constexpr (ranges::convertible_to) { @@ -150,7 +150,8 @@ ::testing::Matcher matchId(Id id) { // If it is an ID (possibly contained in the `IdOrLiteralOrIri` variant), then // the `matchId` matcher from above is used, else we test for equality. template -requires(!isVectorResult) auto nonVectorResultMatcher(const T& expected) { + requires(!isVectorResult) +auto nonVectorResultMatcher(const T& expected) { if constexpr (std::is_same_v) { return matchId(expected); } else if constexpr (std::is_same_v) { diff --git a/test/SparqlProtocolTest.cpp b/test/SparqlProtocolTest.cpp index 9b1904a8d0..7177d3134d 100644 --- a/test/SparqlProtocolTest.cpp +++ b/test/SparqlProtocolTest.cpp @@ -38,52 +38,49 @@ const std::string QUERY = "application/sparql-query"; const std::string UPDATE = "application/sparql-update"; const std::string TURTLE = "text/turtle"; -auto testAccessTokenCombinations = [](auto parse, const http::verb& method, - std::string_view pathBase, - const Operation& expectedOperation, - const ad_utility::HashMap& - headers = {}, - const std::optional& body = - std::nullopt, - ad_utility::source_location l = - AD_CURRENT_SOURCE_LOC()) { - auto t = generateLocationTrace(l); - // Test the cases: - // 1. No access token - // 2. Access token in query - // 3. Access token in `Authorization` header - // 4. Different access tokens - // 5. Same access token - boost::urls::url pathWithAccessToken{pathBase}; - pathWithAccessToken.params().append({"access-token", "foo"}); - ad_utility::HashMap headersWithDifferentAccessToken{ - headers}; - headersWithDifferentAccessToken.insert( - {http::field::authorization, "Bearer bar"}); - ad_utility::HashMap headersWithSameAccessToken{ - headers}; - headersWithSameAccessToken.insert({http::field::authorization, "Bearer foo"}); - EXPECT_THAT(parse(makeRequest(method, pathBase, headers, body)), - ParsedRequestIs("/", std::nullopt, {}, expectedOperation)); - EXPECT_THAT( - parse(makeRequest(method, pathWithAccessToken.buffer(), headers, body)), - ParsedRequestIs("/", "foo", {{"access-token", {"foo"}}}, - expectedOperation)); - EXPECT_THAT(parse(makeRequest(method, pathBase, - headersWithDifferentAccessToken, body)), - ParsedRequestIs("/", "bar", {}, expectedOperation)); - EXPECT_THAT(parse(makeRequest(method, pathWithAccessToken.buffer(), - headersWithSameAccessToken, body)), - ParsedRequestIs("/", "foo", {{"access-token", {"foo"}}}, - expectedOperation)); - AD_EXPECT_THROW_WITH_MESSAGE( - parse(makeRequest(method, pathWithAccessToken.buffer(), - headersWithDifferentAccessToken, body)), - testing::HasSubstr("Access token is specified both in the " - "`Authorization` header and by the `access-token` " - "parameter, but they are not the same")); -}; +auto testAccessTokenCombinations = + [](auto parse, const http::verb& method, std::string_view pathBase, + const Operation& expectedOperation, + const ad_utility::HashMap& headers = {}, + const std::optional& body = std::nullopt, + ad_utility::source_location l = AD_CURRENT_SOURCE_LOC()) { + auto t = generateLocationTrace(l); + // Test the cases: + // 1. No access token + // 2. Access token in query + // 3. Access token in `Authorization` header + // 4. Different access tokens + // 5. Same access token + boost::urls::url pathWithAccessToken{pathBase}; + pathWithAccessToken.params().append({"access-token", "foo"}); + ad_utility::HashMap + headersWithDifferentAccessToken{headers}; + headersWithDifferentAccessToken.insert( + {http::field::authorization, "Bearer bar"}); + ad_utility::HashMap headersWithSameAccessToken{ + headers}; + headersWithSameAccessToken.insert( + {http::field::authorization, "Bearer foo"}); + EXPECT_THAT(parse(makeRequest(method, pathBase, headers, body)), + ParsedRequestIs("/", std::nullopt, {}, expectedOperation)); + EXPECT_THAT(parse(makeRequest(method, pathWithAccessToken.buffer(), + headers, body)), + ParsedRequestIs("/", "foo", {{"access-token", {"foo"}}}, + expectedOperation)); + EXPECT_THAT(parse(makeRequest(method, pathBase, + headersWithDifferentAccessToken, body)), + ParsedRequestIs("/", "bar", {}, expectedOperation)); + EXPECT_THAT(parse(makeRequest(method, pathWithAccessToken.buffer(), + headersWithSameAccessToken, body)), + ParsedRequestIs("/", "foo", {{"access-token", {"foo"}}}, + expectedOperation)); + AD_EXPECT_THROW_WITH_MESSAGE( + parse(makeRequest(method, pathWithAccessToken.buffer(), + headersWithDifferentAccessToken, body)), + testing::HasSubstr("Access token is specified both in the " + "`Authorization` header and by the `access-token` " + "parameter, but they are not the same")); + }; auto testAccessTokenCombinationsUrlEncoded = [](auto parse, const std::string& bodyBase, const Operation& diff --git a/test/TypeTraitsTest.cpp b/test/TypeTraitsTest.cpp index ae77362736..b81a4a21d4 100644 --- a/test/TypeTraitsTest.cpp +++ b/test/TypeTraitsTest.cpp @@ -380,8 +380,8 @@ TEST(TypeTraits, InvocableWithConvertibleReturnType) { if constexpr ((!ql::concepts::same_as || !ql::concepts::same_as)&&!ql::concepts:: - same_as) { + bool&>) && + !ql::concepts::same_as) { static_assert( !bothInvocableWithExactReturnType.template operator() CPP_concept Something = (... && (sizeof(T) <= 4)); // A templated class with a variety of members. -CPP_template(typename T)(requires(Something)) struct C { +CPP_template(typename T) (requires(Something)) +struct C { // A constructor that takes an int only exists for certain `T` explicit constexpr CPP_ctor(C)([[maybe_unused]] int i)( requires Something) {} // A member function that is templated and constrained on an independent // type `F`. - CPP_template_2(typename F)(requires Something) void f(F arg) { (void)arg; } + CPP_template_2(typename F)(requires Something) + void f(F arg) { + (void)arg; + } // Same, but the constraint combines F and T. Note that you have to use // `CPP_and_2` instead of `CPP_and`. - CPP_template_2(typename F)( - requires Something CPP_and_2 Something) auto i() { - } // Additional template parameter + `auto` + CPP_template_2(typename F)(requires Something CPP_and_2 Something) + auto i() {} // Additional template parameter + `auto` // Member function with explicit return type that has no other template // arguments but poses additional constraints on `T`. - CPP_member auto g() -> CPP_ret(void)(requires Something) { - } // only exists for some `T` + CPP_member auto g() -> CPP_ret(void)(requires Something) + {} // only exists for some `T` // Member function with `auto` return type that has no other template // arguments but poses additional constraints on `T`. - CPP_auto_member auto CPP_fun(h)()(requires Something) {} + CPP_auto_member auto CPP_fun(h) ()(requires Something) {} }; // A variadic function template. NOTE: you currently have to use plain `&&`, // the `CPP_and...` macros won't work here. -CPP_variadic_template(typename... Ts)( - requires(Something&& Something)) void f(Ts...) {} +CPP_variadic_template( + typename... Ts)(requires(Something&& Something)) +void f(Ts...) {} TEST(ConceptBackports, lambdas) { int i = 3; diff --git a/test/index/vocabulary/VocabularyInMemoryBinSearchTest.cpp b/test/index/vocabulary/VocabularyInMemoryBinSearchTest.cpp index c271aeeaa5..91f96a4e19 100644 --- a/test/index/vocabulary/VocabularyInMemoryBinSearchTest.cpp +++ b/test/index/vocabulary/VocabularyInMemoryBinSearchTest.cpp @@ -63,7 +63,9 @@ class VocabularyCreator { auto createVocabularyFromDiskImpl( const std::vector& words, std::optional> ids = std::nullopt) { - { createVocabularyImpl(words, std::move(ids)); } + { + createVocabularyImpl(words, std::move(ids)); + } VocabularyInMemoryBinSearch vocabulary; vocabulary.open(vocabFilename_); return vocabulary; diff --git a/test/index/vocabulary/VocabularyInMemoryTest.cpp b/test/index/vocabulary/VocabularyInMemoryTest.cpp index 44a53e19ea..bc80627390 100644 --- a/test/index/vocabulary/VocabularyInMemoryTest.cpp +++ b/test/index/vocabulary/VocabularyInMemoryTest.cpp @@ -70,7 +70,9 @@ TEST(VocabularyInMemory, WordWriterDestructorBehavior) { writer("alpha", false); } v.open(filename); - { auto writerPtr = v.makeDiskWriterPtr(filename); }; + { + auto writerPtr = v.makeDiskWriterPtr(filename); + }; { VocabularyInMemory vocab; { diff --git a/test/index/vocabulary/VocabularyInternalExternalTest.cpp b/test/index/vocabulary/VocabularyInternalExternalTest.cpp index 72830bbe84..c3d0e0319d 100644 --- a/test/index/vocabulary/VocabularyInternalExternalTest.cpp +++ b/test/index/vocabulary/VocabularyInternalExternalTest.cpp @@ -57,7 +57,9 @@ class VocabularyCreator { // Like `createVocabularyImpl` above, but the resulting vocabulary will be // destroyed and re-initialized from disk before it is returned. auto createVocabularyFromDiskImpl(const std::vector& words) { - { createVocabularyImpl(words); } + { + createVocabularyImpl(words); + } VocabularyInternalExternal vocabulary; vocabulary.open(vocabFilename_); return vocabulary; diff --git a/test/index/vocabulary/VocabularyOnDiskTest.cpp b/test/index/vocabulary/VocabularyOnDiskTest.cpp index 1c737f67f6..42ebe528a5 100644 --- a/test/index/vocabulary/VocabularyOnDiskTest.cpp +++ b/test/index/vocabulary/VocabularyOnDiskTest.cpp @@ -69,7 +69,9 @@ class VocabularyCreator { auto createVocabularyFromDiskImpl( const std::vector& words, std::optional> ids = std::nullopt) { - { createVocabularyImpl(words, std::move(ids)); } + { + createVocabularyImpl(words, std::move(ids)); + } VocabularyOnDisk vocabulary; vocabulary.open(vocabFilename_); return vocabulary; diff --git a/test/parser/SparqlAntlrParserTestHelpers.h b/test/parser/SparqlAntlrParserTestHelpers.h index 35f78114bf..cab7e4631b 100644 --- a/test/parser/SparqlAntlrParserTestHelpers.h +++ b/test/parser/SparqlAntlrParserTestHelpers.h @@ -1045,10 +1045,10 @@ auto matchPtrWithChildren(ChildrenMatchers&&... childrenMatchers) } // Same as `matchPtrWithChildren` above, but the children are all variables. -CPP_template(typename Expression, typename... Children)(requires( - ql::concepts::same_as< - ::Variable, - Children>&&...)) auto matchPtrWithVariables(const Children&... children) +CPP_template( + typename Expression, + typename... Children) (requires(ql::concepts::same_as<::Variable, Children>&&...)) +auto matchPtrWithVariables(const Children&... children) -> Matcher { return matchPtrWithChildren( variableExpressionMatcher(children)...); diff --git a/test/util/AsyncTestHelpers.h b/test/util/AsyncTestHelpers.h index b94daef0e9..ffc6a05034 100644 --- a/test/util/AsyncTestHelpers.h +++ b/test/util/AsyncTestHelpers.h @@ -26,7 +26,7 @@ template concept TestableFunction = std::is_invocable_r_v; template -requires(TestableCoroutine || TestableFunction) + requires(TestableCoroutine || TestableFunction) void runAsyncTest(Func innerRun, size_t numThreads) { auto ioContext = std::make_shared(); auto future = [&]() { diff --git a/test/util/BenchmarkMeasurementContainerHelpers.cpp b/test/util/BenchmarkMeasurementContainerHelpers.cpp index 9bc67b9e2f..31cfc22f92 100644 --- a/test/util/BenchmarkMeasurementContainerHelpers.cpp +++ b/test/util/BenchmarkMeasurementContainerHelpers.cpp @@ -11,8 +11,8 @@ using namespace std::string_literals; // ____________________________________________________________________________ CPP_template_def(typename Type)(requires ad_utility::SimilarToAnyTypeIn< - Type, ad_benchmark::ResultTable::EntryType>) - Type createDummyValueEntryType() { + Type, ad_benchmark::ResultTable::EntryType>) +Type createDummyValueEntryType() { if constexpr (ad_utility::isSimilar) { return 4.2f; } else if constexpr (ad_utility::isSimilar) { diff --git a/test/util/BenchmarkMeasurementContainerHelpers.h b/test/util/BenchmarkMeasurementContainerHelpers.h index 29e0a980bd..49378e95e2 100644 --- a/test/util/BenchmarkMeasurementContainerHelpers.h +++ b/test/util/BenchmarkMeasurementContainerHelpers.h @@ -20,9 +20,9 @@ @brief Generate a dummy value of the given type. Used for generating test values for `ad_benchmark::ResultTable`. */ -CPP_template(typename Type)(requires ad_utility::SimilarToAnyTypeIn< - Type, ad_benchmark::ResultTable::EntryType>) Type - createDummyValueEntryType(); +CPP_template(typename Type) (requires ad_utility::SimilarToAnyTypeIn< + Type, ad_benchmark::ResultTable::EntryType>) +Type createDummyValueEntryType(); /* @brief Call the lambda with each of the alternatives in diff --git a/test/util/GTestHelpers.h b/test/util/GTestHelpers.h index 1bb0750558..67c361e67b 100644 --- a/test/util/GTestHelpers.h +++ b/test/util/GTestHelpers.h @@ -149,14 +149,14 @@ class CopyShield { std::shared_ptr pointer_; public: - CPP_variadic_template(typename... Ts)( - requires ql::concepts::constructible_from< - T, Ts&&...>) explicit CopyShield(Ts&&... args) + CPP_variadic_template( + typename... Ts)(requires ql::concepts::constructible_from) + explicit CopyShield(Ts&&... args) : pointer_{std::make_shared(AD_FWD(args)...)} {} - CPP_template(typename Ts)(requires ql::concepts::constructible_from) - CopyShield& - operator=(Ts&& ts) { + CPP_template( + typename Ts) (requires ql::concepts::constructible_from) + CopyShield& operator=(Ts&& ts) { pointer_ = std::make_shared(AD_FWD(ts)); return *this; } @@ -166,8 +166,9 @@ class CopyShield { } QL_DEFINE_CUSTOM_THREEWAY_OPERATOR_LOCAL(T) - CPP_member auto operator==(const T& other) const - -> CPP_ret(bool)(requires ql::concepts::equality_comparable) { + CPP_member auto operator==(const T& other) const -> CPP_ret( + bool)(requires ql::concepts::equality_comparable) + { return *pointer_ == other; } diff --git a/test/util/IdTableHelpers.h b/test/util/IdTableHelpers.h index e6e602e419..d0952ad4c1 100644 --- a/test/util/IdTableHelpers.h +++ b/test/util/IdTableHelpers.h @@ -99,9 +99,9 @@ static constexpr MatchesIdTableFromVector matchesIdTableFromVector; // matcher also deals with `IdTable` not being copyable, which requires a // workaround for GMock/GTest. struct MatchesIdTable { - CPP_template(typename... Ts)( - requires(ql::concepts::constructible_from)) auto - operator()(Ts&&... ts) const { + CPP_template( + typename... Ts) (requires(ql::concepts::constructible_from)) + auto operator()(Ts&&... ts) const { return ::testing::Eq(CopyShield(IdTable{AD_FWD(ts)...})); } diff --git a/test/util/ValidatorHelpers.cpp b/test/util/ValidatorHelpers.cpp index 6a782a725f..f01dad8fb9 100644 --- a/test/util/ValidatorHelpers.cpp +++ b/test/util/ValidatorHelpers.cpp @@ -9,8 +9,8 @@ // ____________________________________________________________________________ CPP_template_def(typename Type)(requires ad_utility::SameAsAnyTypeIn< - Type, ad_utility::ConfigOption::AvailableTypes>) - Type createDummyValueForValidator(size_t variant) { + Type, ad_utility::ConfigOption::AvailableTypes>) +Type createDummyValueForValidator(size_t variant) { if constexpr (std::is_same_v) { return variant % 2; } else if constexpr (std::is_same_v) { @@ -50,7 +50,7 @@ template float createDummyValueForValidator(size_t); template std::vector createDummyValueForValidator>( size_t); template std::vector - createDummyValueForValidator>(size_t); +createDummyValueForValidator>(size_t); template std::vector createDummyValueForValidator>( size_t); template std::vector createDummyValueForValidator>( diff --git a/test/util/ValidatorHelpers.h b/test/util/ValidatorHelpers.h index beb5d96370..46186d8070 100644 --- a/test/util/ValidatorHelpers.h +++ b/test/util/ValidatorHelpers.h @@ -21,9 +21,9 @@ cooperation with `generateSingleParameterValidatorFunction`, while keeping the invariant of `generateValidatorFunction` true. `variant` slightly changes the returned value. */ -CPP_template(typename Type)(requires ad_utility::SameAsAnyTypeIn< - Type, ad_utility::ConfigOption::AvailableTypes>) - Type createDummyValueForValidator(size_t variant); +CPP_template(typename Type) (requires ad_utility::SameAsAnyTypeIn< + Type, ad_utility::ConfigOption::AvailableTypes>) +Type createDummyValueForValidator(size_t variant); /* @brief For easily creating `Validator` functions, that compare given values to @@ -48,9 +48,9 @@ creation of multiple different validator functions. For more information, what the exact difference is, see the code in `createDummyValueForValidator`. */ template -requires((ad_utility::SameAsAnyTypeIn< - ParameterTypes, ad_utility::ConfigOption::AvailableTypes>) && - ...) + requires((ad_utility::SameAsAnyTypeIn< + ParameterTypes, ad_utility::ConfigOption::AvailableTypes>) && + ...) auto generateDummyNonExceptionValidatorFunction(size_t variant) { return [... dummyValuesToCompareTo = createDummyValueForValidator(variant)](