diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..6cfc126 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,19 @@ +Checks: + - -* + - cppcoreguidelines-pro-type-member-init + - modernize-redundant-void-arg + - modernize-use-bool-literals + - modernize-use-default-member-init + - modernize-use-nullptr + - readability-braces-around-statements + - readability-redundant-member-init +HeaderFileExtensions: ['', h, hh, hpp, hxx, inc] +ImplementationFileExtensions: [c, cc, cpp, cxx] +HeaderFilterRegex: (extension/src/openvic-dataloader)/ +FormatStyle: file +CheckOptions: + cppcoreguidelines-pro-type-member-init.IgnoreArrays: true + cppcoreguidelines-pro-type-member-init.UseAssignment: true + modernize-use-bool-literals.IgnoreMacros: false + modernize-use-default-member-init.IgnoreMacros: false + modernize-use-default-member-init.UseAssignment: true \ No newline at end of file diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index c644fdf..2a6fb31 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -10,9 +10,44 @@ concurrency: cancel-in-progress: true jobs: + static-checks: + name: Code style, file formatting, and docs + runs-on: ubuntu-24.04 + steps: + - name: Checkout project + uses: actions/checkout@v4.1.1 + with: + fetch-depth: 2 + + - name: Install APT dependencies + uses: awalsh128/cache-apt-pkgs-action@latest + with: + packages: libxml2-utils + + - name: Get changed files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git config diff.wsErrorHighlight all + if [ "${{ github.event_name }}" == "pull_request" -o "${{ github.event.forced }}" == "true" -o "${{ github.event.created }}" == "true" ]; then + files=$(git diff-tree --no-commit-id --name-only -r HEAD^1..HEAD 2> /dev/null || true) + elif [ "${{ github.event_name }}" == "push" -a "${{ github.event.created }}" == "false" ]; then + files=$(git diff-tree --no-commit-id --name-only -r ${{ github.event.before }}..${{ github.event.after }} 2> /dev/null || true) + fi + echo "$files" >> changed.txt + cat changed.txt + files=$(echo "$files" | xargs -I {} sh -c 'echo "\"./{}\""' | tr '\n' ' ') + echo "CHANGED_FILES=$files" >> $GITHUB_ENV + + - name: Style checks via pre-commit + uses: pre-commit/action@v3.0.1 + with: + extra_args: --files ${{ env.CHANGED_FILES }} + build: runs-on: ${{matrix.os}} name: ${{matrix.name}} + needs: static-checks permissions: write-all strategy: fail-fast: false diff --git a/.github/workflows/cache_cleanup.yml b/.github/workflows/cache_cleanup.yml new file mode 100644 index 0000000..3029720 --- /dev/null +++ b/.github/workflows/cache_cleanup.yml @@ -0,0 +1,32 @@ +# https://github.com/actions/cache/blob/main/tips-and-workarounds.md#force-deletion-of-caches-overriding-default-cache-eviction-policy +name: 🧹 Cache Cleanup +on: + pull_request: + types: + - closed + +jobs: + cleanup: + name: Cleanup PR caches + runs-on: ubuntu-latest + permissions: + # `actions:write` permission is required to delete caches + actions: write + contents: read + steps: + - name: Cleanup + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + BRANCH: refs/pull/${{ github.event.pull_request.number }}/merge + run: | + echo "Fetching list of cache key" + cache_keys_for_pr=$(gh cache list --ref $BRANCH --limit 100 --json id --jq '.[].id') + # Setting this to not fail the workflow while deleting cache keys. + set +e + echo "Deleting caches..." + for cache_key in $cache_keys_for_pr; do + gh cache delete $cache_key + echo "Deleted: $cache_key" + done + echo "Done" \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..906f79d --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,41 @@ +default_language_version: + python: python3 + +repos: + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: v19.1.3 + hooks: + - id: clang-format + files: \.(c|h|cpp|hpp|cc|hh|cxx|hxx|inc)$ + types_or: [text] + + - repo: https://github.com/pocc/pre-commit-hooks + rev: v1.3.5 + hooks: + - id: clang-tidy + files: \.(c|h|cpp|hpp)$ + args: [--fix, --quiet, --use-color] + types_or: [text] + additional_dependencies: [clang-tidy==19.1.0] + require_serial: true + stages: [manual] # Not automatically triggered, invoked via `pre-commit run --hook-stage manual clang-tidy` + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.9.10 + hooks: + - id: ruff + args: [--fix] + files: (\.py|SConstruct|SCsub)$ + types_or: [text] + - id: ruff-format + files: (\.py|SConstruct|SCsub)$ + types_or: [text] + + - repo: https://github.com/crate-ci/typos + rev: v1.30.2 + hooks: + - id: typos + # exclude: | + # (?x)^( + # ) + additional_dependencies: [tomli] \ No newline at end of file diff --git a/SConstruct b/SConstruct index 1ece1c9..ad0287b 100644 --- a/SConstruct +++ b/SConstruct @@ -1,10 +1,6 @@ #!/usr/bin/env python import os -import platform -import sys - -import SCons BINDIR = "bin" @@ -15,10 +11,22 @@ env.PrependENVPath("PATH", os.getenv("PATH")) opts = env.SetupOptions() opts.Add(BoolVariable("run_ovdl_tests", "Build and run the openvic dataloader tests", env.is_standalone)) -opts.Add(BoolVariable("build_ovdl_library", "Build the openvic dataloader library.", env.get("build_ovdl_library", not env.is_standalone))) +opts.Add( + BoolVariable( + "build_ovdl_library", + "Build the openvic dataloader library.", + env.get("build_ovdl_library", not env.is_standalone), + ) +) opts.Add(BoolVariable("build_ovdl_headless", "Build the openvic dataloader headless executable", env.is_standalone)) -opts.Add(BoolVariable("ubuntu_gcc_invalid_char_hang_bug", "Skips test section which triggers a hang build for gcc-12 on ubuntu-20", False)) +opts.Add( + BoolVariable( + "ubuntu_gcc_invalid_char_hang_bug", + "Skips test section which triggers a hang build for gcc-12 on ubuntu-20", + False, + ) +) env.FinalizeOptions() @@ -88,7 +96,7 @@ if env["build_ovdl_headless"]: headless_program = headless_env.Program( target=os.path.join(BINDIR, headless_name), source=headless_env.headless_sources, - PROGSUFFIX=".headless" + env["PROGSUFFIX"] + PROGSUFFIX=".headless" + env["PROGSUFFIX"], ) default_args += [headless_program] @@ -105,4 +113,4 @@ if "env" in locals(): # FIXME: This method mixes both cosmetic progress stuff and cache handling... env.show_progress(env) -Return("env") \ No newline at end of file +Return("env") diff --git a/deps/SCsub b/deps/SCsub index fd38d9f..74857cb 100644 --- a/deps/SCsub +++ b/deps/SCsub @@ -3,6 +3,7 @@ import os Import("env") + def build_lexy(env): env.Append(CPPDEFINES=["LEXY_HAS_UNICODE_DATABASE=1"]) lexy_env = env.Clone() @@ -17,13 +18,19 @@ def build_lexy(env): else: lexy_env.Append(CXXFLAGS=["-std=c++20"]) - lexy_env.Append(CXXFLAGS=["-pedantic-errors", "-Werror", "-Wall", "-Wextra", "-Wconversion", "-Wsign-conversion"]) + lexy_env.Append( + CXXFLAGS=["-pedantic-errors", "-Werror", "-Wall", "-Wextra", "-Wconversion", "-Wsign-conversion"] + ) if lexy_env["CXX"] == "clang++": lexy_env.Append(CXXFLAGS=["-Wno-shift-op-parentheses", "-Wno-parentheses-equality"]) else: - lexy_env.Append(CXXFLAGS=[ - "-Wno-parentheses", "-Wno-unused-local-typedefs", "-Wno-array-bounds" #, "-Wno-maybe-uninitialized", "-Wno-restrict" - ]) + lexy_env.Append( + CXXFLAGS=[ + "-Wno-parentheses", + "-Wno-unused-local-typedefs", + "-Wno-array-bounds", # , "-Wno-maybe-uninitialized", "-Wno-restrict" + ] + ) include_path = "lexy/include" source_path = "lexy/src" @@ -46,6 +53,7 @@ def build_lexy(env): env.Append(LIBPATH=[source_dir]) env.Prepend(LIBS=[library_name]) + def build_dryad(env): include_path = "dryad/include" include_dir = env.Dir(include_path) @@ -59,6 +67,7 @@ def build_dryad(env): env.exposed_includes += env.dryad["INCPATH"] + def build_fmt(env): fmt_env = env.Clone() @@ -70,26 +79,43 @@ def build_fmt(env): else: fmt_env.Append(CXXFLAGS=["-std=c++20"]) - fmt_env.Append(CXXFLAGS=[ - "-Werror", "-Wall", "-Wextra", "-pedantic", "-Wconversion", "-Wundef" - ]) + fmt_env.Append(CXXFLAGS=["-Werror", "-Wall", "-Wextra", "-pedantic", "-Wconversion", "-Wundef"]) if fmt_env["CXX"] == "clang++": - fmt_env.Append(CXXFLAGS=[ - "-Wweak-vtables", "-Wshadow", - "-Wno-gnu-zero-variadic-macro-arguments" - ]) + fmt_env.Append(CXXFLAGS=["-Wweak-vtables", "-Wshadow", "-Wno-gnu-zero-variadic-macro-arguments"]) else: - fmt_env.Append(CXXFLAGS=[ - "-Wold-style-cast", "-Wundef", "-Wredundant-decls", "-Wwrite-strings", - "-Wpointer-arith", "-Wcast-qual", "-Wformat=2", - "-Wmissing-include-dirs", "-Wcast-align", "-Wctor-dtor-privacy", - "-Wdisabled-optimization", "-Winvalid-pch", "-Woverloaded-virtual", - "-Wconversion", "-Wundef", "-Wno-ctor-dtor-privacy", "-Wno-format-nonliteral", - "-Wno-dangling-else", "-Wno-unused-local-typedefs", "-Wdouble-promotion", - "-Wtrampolines", "-Wzero-as-null-pointer-constant", "-Wuseless-cast", - "-Wvector-operation-performance", "-Wsized-deallocation", "-Wshadow", - "-Wshift-overflow=2", "-Wnull-dereference", "-Wduplicated-cond" - ]) + fmt_env.Append( + CXXFLAGS=[ + "-Wold-style-cast", + "-Wundef", + "-Wredundant-decls", + "-Wwrite-strings", + "-Wpointer-arith", + "-Wcast-qual", + "-Wformat=2", + "-Wmissing-include-dirs", + "-Wcast-align", + "-Wctor-dtor-privacy", + "-Wdisabled-optimization", + "-Winvalid-pch", + "-Woverloaded-virtual", + "-Wconversion", + "-Wundef", + "-Wno-ctor-dtor-privacy", + "-Wno-format-nonliteral", + "-Wno-dangling-else", + "-Wno-unused-local-typedefs", + "-Wdouble-promotion", + "-Wtrampolines", + "-Wzero-as-null-pointer-constant", + "-Wuseless-cast", + "-Wvector-operation-performance", + "-Wsized-deallocation", + "-Wshadow", + "-Wshift-overflow=2", + "-Wnull-dereference", + "-Wduplicated-cond", + ] + ) include_path = "fmt/include" source_path = "fmt/src" @@ -103,7 +129,6 @@ def build_fmt(env): Default(library) include_dir = fmt_env.Dir(include_path) - source_dir = fmt_env.Dir(source_path) env.fmt = {} env.fmt["INCPATH"] = [include_dir] @@ -119,6 +144,7 @@ def build_fmt(env): env.exposed_includes += env.fmt["INCPATH"] + def build_range_v3(env): include_path = "range-v3/include" sources = env.GlobRecursive("*.cpp", [include_path]) @@ -137,6 +163,7 @@ def build_range_v3(env): env.exposed_includes += env.range_v3["INCPATH"] + def build_vmcontainer(env): vmcontainer_env = env.Clone() @@ -167,8 +194,9 @@ def build_vmcontainer(env): env.exposed_includes += env.vmcontainer["INCPATH"] + build_dryad(env) build_fmt(env) build_lexy(env) build_range_v3(env) -build_vmcontainer(env) \ No newline at end of file +build_vmcontainer(env) diff --git a/include/openvic-dataloader/Error.hpp b/include/openvic-dataloader/Error.hpp index 8e182b6..48e0ec3 100644 --- a/include/openvic-dataloader/Error.hpp +++ b/include/openvic-dataloader/Error.hpp @@ -213,7 +213,9 @@ namespace ovdl::error { } inline void AnnotatedError::push_back(AnnotationList p_annotations) { - if (p_annotations.empty()) return; + if (p_annotations.empty()) { + return; + } insert_child_list_after(_last_annotation, p_annotations); _last_annotation = p_annotations.back(); } diff --git a/include/openvic-dataloader/NodeLocation.hpp b/include/openvic-dataloader/NodeLocation.hpp index 7f7a09c..edc586b 100644 --- a/include/openvic-dataloader/NodeLocation.hpp +++ b/include/openvic-dataloader/NodeLocation.hpp @@ -28,10 +28,11 @@ namespace ovdl { void set_from(const BasicNodeLocation& other) { if constexpr (sizeof(CharT) <= sizeof(OtherCharT)) { _begin = reinterpret_cast(other.begin()); - if (other.begin() == other.end()) + if (other.begin() == other.end()) { _end = _begin; - else + } else { _end = reinterpret_cast(other.end()) + (sizeof(OtherCharT) - sizeof(CharT)); + } } else { _begin = reinterpret_cast(other.begin()); if (other.end() - other.begin() <= 0) { @@ -60,7 +61,9 @@ namespace ovdl { static BasicNodeLocation make_from(const char_type* begin, const char_type* end) { end++; - if (begin >= end) return BasicNodeLocation(begin); + if (begin >= end) { + return BasicNodeLocation(begin); + } return BasicNodeLocation(begin, end); } }; diff --git a/include/openvic-dataloader/csv/LineObject.hpp b/include/openvic-dataloader/csv/LineObject.hpp index 5de55ba..43aeea8 100644 --- a/include/openvic-dataloader/csv/LineObject.hpp +++ b/include/openvic-dataloader/csv/LineObject.hpp @@ -57,17 +57,25 @@ namespace ovdl::csv { /// Special Functionality /// Retrieves value, produces "" for empty values constexpr std::string_view get_value_for(std::size_t position) const { - if (position < _prefix_end || position >= _suffix_end) return ""; + if (position < _prefix_end || position >= _suffix_end) { + return ""; + } for (const auto& [pos, val] : *this) { - if (pos == position) return val; + if (pos == position) { + return val; + } } return ""; } /// Tries to retrieve reference, produces nullopt for empty values constexpr std::optional> try_get_string_at(std::size_t position) const { - if (position < _prefix_end || position >= _suffix_end) return std::nullopt; + if (position < _prefix_end || position >= _suffix_end) { + return std::nullopt; + } for (const auto& [pos, val] : *this) { - if (pos == position) return std::cref(val); + if (pos == position) { + return std::cref(val); + } } return std::nullopt; } @@ -85,14 +93,14 @@ namespace ovdl::csv { std::string_view separator; }; - constexpr SepTransformer use_sep(std::string_view seperator) const { - return { *this, seperator }; + constexpr SepTransformer use_sep(std::string_view separator) const { + return { *this, separator }; } private: // Should be position of first valid value on line position_type _prefix_end = 0; - // Should be position after last value or position after last seperator + // Should be position after last value or position after last separator position_type _suffix_end = 0; }; diff --git a/include/openvic-dataloader/detail/SymbolIntern.hpp b/include/openvic-dataloader/detail/SymbolIntern.hpp index 3b2cb1b..9da428d 100644 --- a/include/openvic-dataloader/detail/SymbolIntern.hpp +++ b/include/openvic-dataloader/detail/SymbolIntern.hpp @@ -24,8 +24,9 @@ namespace ovdl { } bool reserve(std::size_t new_capacity) { - if (new_capacity <= _data_buffer.capacity()) + if (new_capacity <= _data_buffer.capacity()) { return true; + } if (new_capacity >= _data_buffer.max_size()) { _data_buffer.reserve(_data_buffer.max_size()); @@ -40,12 +41,14 @@ namespace ovdl { bool reserve_new_string(std::size_t new_string_length) { // +1 for null-terminator. auto new_size = _data_buffer.size() + new_string_length + 1; - if (new_size <= _data_buffer.capacity()) + if (new_size <= _data_buffer.capacity()) { return true; + } auto new_capacity = new_size * 2; - if (new_capacity < min_buffer_size) + if (new_capacity < min_buffer_size) { new_capacity = min_buffer_size; + } if (!reserve(new_capacity)) { return _data_buffer.capacity() >= new_size; @@ -174,12 +177,14 @@ namespace ovdl { } symbol find_intern(const CharT* str, std::size_t length) { - if (_map.should_rehash()) + if (_map.should_rehash()) { return symbol(); + } auto entry = _map.lookup_entry(typename traits::string_view { str, length }, traits { &_buffer }); - if (entry) + if (entry) { return symbol(_buffer.c_str(entry.get())); + } return symbol(); } @@ -190,17 +195,20 @@ namespace ovdl { } symbol intern(const CharT* str, std::size_t length) { - if (_map.should_rehash()) + if (_map.should_rehash()) { _map.rehash(_resource, traits { &_buffer }); + } auto entry = _map.lookup_entry(typename traits::string_view { str, length }, traits { &_buffer }); - if (entry) + if (entry) { // Already interned, return index. return symbol(_buffer.c_str(entry.get())); + } // Copy string data to buffer, as we don't have it yet. - if (!_buffer.reserve_new_string(length)) // Ran out of virtual memory space + if (!_buffer.reserve_new_string(length)) { // Ran out of virtual memory space return symbol(); + } auto begin = _buffer.insert(str, length); auto idx = std::distance(_buffer.c_str(0), begin); diff --git a/include/openvic-dataloader/detail/Utility.hpp b/include/openvic-dataloader/detail/Utility.hpp index 5ecd7a2..3a9e170 100644 --- a/include/openvic-dataloader/detail/Utility.hpp +++ b/include/openvic-dataloader/detail/Utility.hpp @@ -41,8 +41,11 @@ namespace ovdl::detail { static constexpr std::uint32_t type_id() { static_assert(any_of, "Cannot query an non-registered type"); - if constexpr (std::is_same_v) return 0; - else return 1 + TypeRegister::template _id_getter::type_id(); + if constexpr (std::is_same_v) { + return 0; + } else { + return 1 + TypeRegister::template _id_getter::type_id(); + } }; }; diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..d8561bc --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,35 @@ +[tool.mypy] +ignore_missing_imports = true +disallow_any_generics = true +no_implicit_optional = true +pretty = true +show_column_numbers = true +warn_redundant_casts = true +warn_return_any = true +warn_unreachable = true +namespace_packages = true +explicit_package_bases = true + +[tool.ruff] +extend-include = ["SConstruct", "SCsub"] +line-length = 120 +target-version = "py37" + +[tool.ruff.lint] +extend-select = [ + "I", # isort +] + +[tool.ruff.lint.per-file-ignores] +"{SConstruct,SCsub}" = [ + "E402", # Module level import not at top of file + "F821", # Undefined name +] + +[tool.typos] +files.extend-exclude = [".mailmap", "*.gitignore", "*.po", "*.pot", "*.rc"] +default.extend-ignore-re = [ + "(?Rm)^.*(#|//)\\s*spellchecker:disable-line$", # Single line check disable + "(?s)(#|//)\\s*spellchecker:off.*?\\n\\s*(#|//)\\s*spellchecker:on", # Multiline check disable with // spellchecker:off // spellchecker:on (can also use #) + "(?s)(/\\*)\\s*spellchecker:off.*?\\s*spellchecker:on\\s*(\\*/)", # Multiline check disable with /* spellchecker:off ... spellchecker:on */ +] diff --git a/src/headless/main.cpp b/src/headless/main.cpp index 0ad6115..e4776fa 100644 --- a/src/headless/main.cpp +++ b/src/headless/main.cpp @@ -21,18 +21,26 @@ std::string_view trim(std::string_view str) { std::string_view::iterator begin = str.begin(); std::string_view::iterator end = str.end(); for (;; begin++) { - if (begin == end) return std::string_view(); - if (!std::isspace(*begin)) break; + if (begin == end) { + return std::string_view(); + } + if (!std::isspace(*begin)) { + break; + } } end--; for (;; end--) { - if (end == begin) return std::string_view(); - if (!std::isspace(*end)) break; + if (end == begin) { + return std::string_view(); + } + if (!std::isspace(*end)) { + break; + } } return std::string_view(&*begin, std::distance(begin, end)); } -bool insenitive_trim_eq(std::string_view lhs, std::string_view rhs) { +bool insensitive_trim_eq(std::string_view lhs, std::string_view rhs) { lhs = trim(lhs); rhs = trim(rhs); return std::equal( @@ -121,10 +129,10 @@ int main(int argc, char** argv) { VisualizationType type = VisualizationType::Native; if (args.size() >= 2) { std::string_view type_str = args[1]; - if (insenitive_trim_eq(type_str, "list")) { + if (insensitive_trim_eq(type_str, "list")) { type = VisualizationType::List; args.erase(args.begin() + 1); - } else if (insenitive_trim_eq(type_str, "native")) { + } else if (insensitive_trim_eq(type_str, "native")) { type = VisualizationType::Native; args.erase(args.begin() + 1); } @@ -132,15 +140,17 @@ int main(int argc, char** argv) { switch (args.size()) { case 2: - if (insenitive_trim_eq(std::filesystem::path(args[1]).extension().string(), ".lua")) { + if (insensitive_trim_eq(std::filesystem::path(args[1]).extension().string(), ".lua")) { return print_lua(args[1], type); } return print_v2script_simple(args[1], type); case 3: - if (insenitive_trim_eq(args[1], "csv")) + if (insensitive_trim_eq(args[1], "csv")) { return print_csv(args[2]); - if (insenitive_trim_eq(args[1], "lua")) + } + if (insensitive_trim_eq(args[1], "lua")) { return print_lua(args[2], type); + } [[fallthrough]]; default: std::fprintf(stderr, "usage: %s \n", args[0].c_str()); diff --git a/src/openvic-dataloader/DiagnosticLogger.hpp b/src/openvic-dataloader/DiagnosticLogger.hpp index 479a7a0..1de51bc 100644 --- a/src/openvic-dataloader/DiagnosticLogger.hpp +++ b/src/openvic-dataloader/DiagnosticLogger.hpp @@ -92,8 +92,9 @@ namespace ovdl { }(); auto writer = _logger.template parse_error(impl, loc, production_name.c_str()); - if (location.line_nr() != context_location.line_nr()) + if (location.line_nr() != context_location.line_nr()) { writer.secondary(BasicNodeLocation { context.position(), lexy::_detail::next(context.position()) }, "beginning here").finish(); + } if constexpr (std::is_same_v) { auto string = lexy::_detail::make_literal_lexeme(error.string(), error.length()); @@ -407,8 +408,9 @@ namespace ovdl { output.pop_back(); auto message = intern(output); error->_set_message(message); - if (!error->is_linked_in_tree()) + if (!error->is_linked_in_tree()) { insert(error); + } } template @@ -490,10 +492,12 @@ namespace ovdl { log_with_impl(impl, semantic, kind, fmt, std::forward(args)...); }); - if (kind == DiagnosticKind::error) + if (kind == DiagnosticKind::error) { _errored = true; - if (kind == DiagnosticKind::warning) + } + if (kind == DiagnosticKind::warning) { _warned = true; + } return result; } diff --git a/src/openvic-dataloader/csv/CsvGrammar.hpp b/src/openvic-dataloader/csv/CsvGrammar.hpp index 91226c7..acbeafb 100644 --- a/src/openvic-dataloader/csv/CsvGrammar.hpp +++ b/src/openvic-dataloader/csv/CsvGrammar.hpp @@ -21,7 +21,7 @@ // Grammar Definitions // namespace ovdl::csv::grammar { struct ParseOptions { - /// @brief Seperator character + /// @brief Separator character char SepChar; /// @brief Determines whether StringValue is supported bool SupportStrings; @@ -102,8 +102,9 @@ namespace ovdl::csv::grammar { }(); lexy::scan_result str_result = scanner.template parse(rule); - if (!scanner || !str_result) + if (!scanner || !str_result) { return lexy::scan_failed; + } return str_result.value(); } @@ -154,13 +155,15 @@ namespace ovdl::csv::grammar { if constexpr (Options.SupportStrings) { auto lexeme_result = scanner.template parse>(rule); - if (!scanner || !lexeme_result) + if (!scanner || !lexeme_result) { return lexy::scan_failed; + } return std::string { lexeme_result.value().begin(), lexeme_result.value().end() }; } else { lexy::scan_result str_result = scanner.template parse(rule); - if (!scanner || !str_result) + if (!scanner || !str_result) { return lexy::scan_failed; + } return str_result.value(); } } @@ -190,17 +193,17 @@ namespace ovdl::csv::grammar { static constexpr auto value = lexy::constant(1); }; - struct Seperator { + struct Separator { static constexpr auto rule = lexy::dsl::list(lexy::dsl::p); static constexpr auto value = lexy::count; }; struct LineEnd { - static constexpr auto rule = lexy::dsl::list(lexy::dsl::p, lexy::dsl::trailing_sep(lexy::dsl::p)); + static constexpr auto rule = lexy::dsl::list(lexy::dsl::p, lexy::dsl::trailing_sep(lexy::dsl::p)); static constexpr auto value = lexy::fold_inplace( std::initializer_list {}, [](ovdl::csv::LineObject& result, std::size_t&& arg) { - // Count seperators, adds to previous value, making it a position + // Count separators, adds to previous value, making it a position using position_type = ovdl::csv::LineObject::position_type; result.emplace_back(static_cast(arg + result.back().first), ""); }, @@ -225,7 +228,7 @@ namespace ovdl::csv::grammar { } }; - static constexpr auto rule = lexy::dsl::p | lexy::dsl::p >> lexy::dsl::opt(lexy::dsl::p); + static constexpr auto rule = lexy::dsl::p | lexy::dsl::p >> lexy::dsl::opt(lexy::dsl::p); static constexpr auto value = lexy::callback( [](ovdl::csv::LineObject&& line) { diff --git a/src/openvic-dataloader/csv/Parser.cpp b/src/openvic-dataloader/csv/Parser.cpp index e4416b2..25f7fbb 100644 --- a/src/openvic-dataloader/csv/Parser.cpp +++ b/src/openvic-dataloader/csv/Parser.cpp @@ -166,10 +166,11 @@ bool Parser::parse_csv(bool handle_strings) { } std::optional errors = [&] { - if (handle_strings) + if (handle_strings) { return _parse_handler->template parse(); - else + } else { return _parse_handler->template parse(); + } }(); _has_error = _parse_handler->parse_state().logger().errored(); _has_warning = _parse_handler->parse_state().logger().warned(); @@ -227,7 +228,9 @@ const FilePosition Parser::get_error_position(const error::Error* error) const { void Parser::print_errors_to(std::basic_ostream& stream) const { auto errors = get_errors(); - if (errors.empty()) return; + if (errors.empty()) { + return; + } for (const auto error : errors) { dryad::visit_tree( error, diff --git a/src/openvic-dataloader/detail/Detect.cpp b/src/openvic-dataloader/detail/Detect.cpp index 020e59e..a12a6b2 100644 --- a/src/openvic-dataloader/detail/Detect.cpp +++ b/src/openvic-dataloader/detail/Detect.cpp @@ -5,7 +5,7 @@ using namespace ovdl::encoding_detect; static constexpr int64_t INVALID_CLASS = 255; -std::optional Utf8Canidate::read(const std::span& buffer) { +std::optional Utf8Candidate::read(const std::span& buffer) { auto lexy_buffer = lexy::make_buffer_from_raw(buffer.data(), buffer.size()); if (is_utf8(lexy_buffer)) { return 0; @@ -14,7 +14,7 @@ std::optional Utf8Canidate::read(const std::span& buffer) return std::nullopt; } -std::optional AsciiCanidate::read(const std::span& buffer) { +std::optional AsciiCandidate::read(const std::span& buffer) { auto lexy_buffer = lexy::make_buffer_from_raw(buffer.data(), buffer.size()); if (is_ascii(lexy_buffer)) { return 0; @@ -23,7 +23,7 @@ std::optional AsciiCanidate::read(const std::span& buffer) return std::nullopt; } -std::optional NonLatinCasedCanidate::read(const std::span& buffer) { +std::optional NonLatinCasedCandidate::read(const std::span& buffer) { static constexpr cbyte LATIN_LETTER = 1; static constexpr int64_t NON_LATIN_MIXED_CASE_PENALTY = -20; static constexpr int64_t NON_LATIN_ALL_CAPS_PENALTY = -40; @@ -122,7 +122,7 @@ std::optional NonLatinCasedCanidate::read(const std::span& return score; } -std::optional LatinCanidate::read(const std::span& buffer) { +std::optional LatinCandidate::read(const std::span& buffer) { static constexpr int64_t IMPLAUSIBLE_LATIN_CASE_TRANSITION_PENALTY = -180; static constexpr int64_t ORDINAL_BONUS = 300; static constexpr int64_t COPYRIGHT_BONUS = 222; diff --git a/src/openvic-dataloader/detail/Detect.hpp b/src/openvic-dataloader/detail/Detect.hpp index 31427e0..7a9ea64 100644 --- a/src/openvic-dataloader/detail/Detect.hpp +++ b/src/openvic-dataloader/detail/Detect.hpp @@ -416,15 +416,15 @@ namespace ovdl::encoding_detect { return byte_scores[static_cast>(index)]; } - struct Utf8Canidate { + struct Utf8Candidate { std::optional read(const std::span& buffer); }; - struct AsciiCanidate { + struct AsciiCandidate { std::optional read(const std::span& buffer); }; - struct NonLatinCasedCanidate { + struct NonLatinCasedCandidate { enum class CaseState { Space, Upper, @@ -446,7 +446,7 @@ namespace ovdl::encoding_detect { std::optional read(const std::span& buffer); }; - struct LatinCanidate { + struct LatinCandidate { enum class CaseState { Space, Upper, @@ -477,14 +477,14 @@ namespace ovdl::encoding_detect { OrdinalState ordinal_state = OrdinalState::Space; // Used only when `windows1252 == true` bool windows1252; - constexpr LatinCanidate(const ByteScore& data) : score_data(data) { + constexpr LatinCandidate(const ByteScore& data) : score_data(data) { windows1252 = data.encoding == Encoding::Windows1252; } std::optional read(const std::span& buffer); }; - using InnerCanidate = std::variant; + using InnerCandidate = std::variant; template struct overloaded : Ts... { @@ -494,40 +494,40 @@ namespace ovdl::encoding_detect { template overloaded(Ts...) -> overloaded; - struct Canidate { - InnerCanidate inner; + struct Candidate { + InnerCandidate inner; std::optional score_value; - template - static constexpr Canidate create_canidate() { + template + static constexpr Candidate create_candidate() { return { - .inner = CanidateT(), + .inner = CandidateT(), .score_value = 0 }; } - template - static constexpr Canidate create_canidate(const ByteScore& score) { + template + static constexpr Candidate create_candidate(const ByteScore& score) { return { - .inner = CanidateT { score }, + .inner = CandidateT { score }, .score_value = 0 }; } - static constexpr Canidate new_utf8() { - return create_canidate(); + static constexpr Candidate new_utf8() { + return create_candidate(); } - static constexpr Canidate new_ascii() { - return create_canidate(); + static constexpr Candidate new_ascii() { + return create_candidate(); } - static constexpr Canidate new_latin(ScoreIndex index) { - return create_canidate(get_byte_score(index)); + static constexpr Candidate new_latin(ScoreIndex index) { + return create_candidate(get_byte_score(index)); } - static constexpr Canidate new_non_latin_cased(ScoreIndex index) { - return create_canidate(get_byte_score(index)); + static constexpr Candidate new_non_latin_cased(ScoreIndex index) { + return create_candidate(get_byte_score(index)); } constexpr std::optional score(const std::span& buffer, std::size_t encoding, bool expectation_is_valid) { @@ -543,7 +543,7 @@ namespace ovdl::encoding_detect { } } - if (auto nlcc = std::get_if(&inner)) { + if (auto nlcc = std::get_if(&inner)) { if (nlcc->longest_word < 2) { return std::nullopt; } @@ -554,28 +554,28 @@ namespace ovdl::encoding_detect { constexpr Encoding encoding() const { return std::visit( overloaded { - [](const Utf8Canidate& canidate) { + [](const Utf8Candidate& candidate) { return Encoding::Utf8; }, - [](const AsciiCanidate& canidate) { + [](const AsciiCandidate& candidate) { return Encoding::Ascii; }, - [](const LatinCanidate& canidate) { - return canidate.score_data.encoding; + [](const LatinCandidate& candidate) { + return candidate.score_data.encoding; }, - [](const NonLatinCasedCanidate& canidate) { - return canidate.score_data.encoding; + [](const NonLatinCasedCandidate& candidate) { + return candidate.score_data.encoding; } }, inner); } }; struct Detector { - std::vector canidates { - Canidate::new_ascii(), - Canidate::new_utf8(), - Canidate::new_latin(ScoreIndex::Windows1252), - Canidate::new_non_latin_cased(ScoreIndex::Windows1251), + std::vector candidates { + Candidate::new_ascii(), + Candidate::new_utf8(), + Candidate::new_latin(ScoreIndex::Windows1252), + Candidate::new_non_latin_cased(ScoreIndex::Windows1251), }; Encoding default_fallback = Encoding::Unknown; @@ -584,24 +584,24 @@ namespace ovdl::encoding_detect { int64_t max = 0; Encoding encoding = default_fallback; // Presumes fallback, defaults to Unknown encoding if unknown (which skips conversion) std::size_t i = 0; - for (Canidate& canidate : canidates) { - if (!allow_utf8 && canidate.encoding() == Encoding::Utf8) { + for (Candidate& candidate : candidates) { + if (!allow_utf8 && candidate.encoding() == Encoding::Utf8) { continue; } - if (auto score = canidate.score(buffer, i, false)) { - switch (canidate.encoding()) { + if (auto score = candidate.score(buffer, i, false)) { + switch (candidate.encoding()) { using enum Encoding; case Ascii: case Utf8: - return { canidate.encoding(), true }; + return { candidate.encoding(), true }; default: break; } auto value = score.value(); if (value > max) { max = value; - encoding = canidate.encoding(); + encoding = candidate.encoding(); } } i++; diff --git a/src/openvic-dataloader/detail/ParseHandler.cpp b/src/openvic-dataloader/detail/ParseHandler.cpp index abf7acd..5150a0d 100644 --- a/src/openvic-dataloader/detail/ParseHandler.cpp +++ b/src/openvic-dataloader/detail/ParseHandler.cpp @@ -47,7 +47,7 @@ struct LangCodeLiteral { struct LangCodeView { std::string_view view; - bool is_valid; + bool is_valid = false; constexpr LangCodeView() = default; @@ -153,7 +153,7 @@ void ParseHandler::_detect_system_fallback_encoding() { { 0x0035, "zu" }, { 0x0036, "af" }, { 0x0037, "ka" }, - { 0x0038, "fo" }, + { 0x0038, "fo" }, // spellchecker:disable-line { 0x0039, "hi" }, { 0x003A, "mt" }, { 0x003B, "se" }, @@ -206,7 +206,7 @@ void ParseHandler::_detect_system_fallback_encoding() { { 0x006A, "yo" }, { 0x006B, "quz" }, { 0x006C, "nso" }, - { 0x006D, "ba" }, + { 0x006D, "ba" }, // spellchecker:disable-line { 0x006E, "lb" }, { 0x006F, "kl" }, { 0x0070, "ig" }, @@ -294,7 +294,7 @@ void ParseHandler::_detect_system_fallback_encoding() { WIN1252(eu); WIN1252(br); WIN1252(co); - WIN1252(fo); + WIN1252(fo); // spellchecker:disable-line WIN1252(gl); WIN1252(is); WIN1252(io); diff --git a/src/openvic-dataloader/detail/ParseHandler.hpp b/src/openvic-dataloader/detail/ParseHandler.hpp index 28222ae..813af42 100644 --- a/src/openvic-dataloader/detail/ParseHandler.hpp +++ b/src/openvic-dataloader/detail/ParseHandler.hpp @@ -42,13 +42,17 @@ namespace ovdl::detail { buffer_error load_buffer_size(const char* data, std::size_t size, std::optional fallback) { lexy::buffer buffer(data, size); - if (buffer.data() == nullptr) return buffer_error::buffer_is_null; + if (buffer.data() == nullptr) { + return buffer_error::buffer_is_null; + } return load_buffer_impl(std::move(buffer), "", fallback); } buffer_error load_buffer(const char* start, const char* end, std::optional fallback) { lexy::buffer buffer(start, end); - if (buffer.data() == nullptr) return buffer_error::buffer_is_null; + if (buffer.data() == nullptr) { + return buffer_error::buffer_is_null; + } return load_buffer_impl(std::move(buffer), "", fallback); } @@ -98,8 +102,9 @@ namespace ovdl::detail { bool is_bad_fallback = false; if (fallback.has_value()) { is_bad_fallback = fallback.value() == Encoding::Ascii || fallback.value() == Encoding::Utf8; - if (is_bad_fallback) + if (is_bad_fallback) { fallback = _system_fallback_encoding.value(); + } } else { fallback = _system_fallback_encoding.value(); } @@ -186,7 +191,9 @@ namespace ovdl::detail { } constexpr virtual buffer_error load_buffer_impl(lexy::buffer&& buffer, const char* path, std::optional fallback) { - if (buffer.data() == nullptr) return buffer_error::buffer_is_null; + if (buffer.data() == nullptr) { + return buffer_error::buffer_is_null; + } create_state(&_parse_state, path, std::move(buffer), fallback); return is_valid_impl() ? buffer_error::success : buffer_error::buffer_is_null; } diff --git a/src/openvic-dataloader/detail/StringLiteral.hpp b/src/openvic-dataloader/detail/StringLiteral.hpp index 985b087..f546729 100644 --- a/src/openvic-dataloader/detail/StringLiteral.hpp +++ b/src/openvic-dataloader/detail/StringLiteral.hpp @@ -43,8 +43,9 @@ namespace ovdl::detail { constexpr string_literal() noexcept = default; constexpr string_literal(const value_type (&literal)[N]) noexcept { - for (auto i = 0u; i != N; i++) + for (auto i = 0u; i != N; i++) { _data[i] = literal[i]; + } } constexpr string_literal(value_type c) noexcept : _data {} { @@ -101,19 +102,22 @@ namespace ovdl::detail { constexpr auto pop_back() const noexcept { string_literal result {}; - for (auto i = 0u; i != N - 2; i++) + for (auto i = 0u; i != N - 2; i++) { result._data[i] = _data[i]; + } return result; } template constexpr auto append(value_type ch) const noexcept { string_literal result {}; - for (auto i = 0u; i != N; i++) + for (auto i = 0u; i != N; i++) { result._data[i] = _data[i]; + } - for (auto i = N; i != N + count; i++) + for (auto i = N; i != N + count; i++) { result._data[i] = ch; + } return result; } @@ -134,8 +138,9 @@ namespace ovdl::detail { constexpr size_type result_size = std::min(count - pos, N - pos); string_literal result {}; - for (size_type i = 0u, i2 = pos; i != result_size; i++, i2++) + for (size_type i = 0u, i2 = pos; i != result_size; i++, i2++) { result._data[i] = _data[i2]; + } return result; } @@ -192,11 +197,13 @@ namespace ovdl::detail { template constexpr auto operator+(const string_literal& other) const noexcept { string_literal result {}; - for (size_type i = 0u; i != N; i++) + for (size_type i = 0u; i != N; i++) { result._data[i] = _data[i]; + } - for (size_type i = N - 1, i2 = 0; i2 != N2; i++, i2++) + for (size_type i = N - 1, i2 = 0; i2 != N2; i++, i2++) { result._data[i] = other._data[i2]; + } return result; } diff --git a/src/openvic-dataloader/detail/dsl.hpp b/src/openvic-dataloader/detail/dsl.hpp index fd8981a..79e93ed 100644 --- a/src/openvic-dataloader/detail/dsl.hpp +++ b/src/openvic-dataloader/detail/dsl.hpp @@ -77,10 +77,11 @@ namespace ovdl::dsl { template constexpr auto construct = callback( [](detail::IsParseState auto& state, ovdl::NodeLocation loc, auto&& arg) { - if constexpr (std::same_as, lexy::nullopt>) + if constexpr (std::same_as, lexy::nullopt>) { return state.ast().template create(loc); - else + } else { return state.ast().template create(loc, DRYAD_FWD(arg)); + } }, [](detail::IsParseState auto& state, ovdl::NodeLocation loc, auto&&... args) { return state.ast().template create(loc, DRYAD_FWD(args)...); @@ -125,17 +126,20 @@ namespace ovdl::dsl { static LEXY_CONSTEVAL auto char_class_ascii() { lexy::_detail::ascii_set result; - if constexpr (LowC <= 0x7F && HighC <= 0x7F) - for (auto c = LowC; c <= HighC; c++) + if constexpr (LowC <= 0x7F && HighC <= 0x7F) { + for (auto c = LowC; c <= HighC; c++) { result.insert(c); + } + } return result; } static constexpr auto char_class_match_cp([[maybe_unused]] char32_t cp) { - if constexpr (LowC <= 0x7F && HighC <= 0x7F) + if constexpr (LowC <= 0x7F && HighC <= 0x7F) { return std::false_type {}; - else + } else { return LowC <= cp && cp <= HighC; + } } }; diff --git a/src/openvic-dataloader/v2script/AbstractSyntaxTree.cpp b/src/openvic-dataloader/v2script/AbstractSyntaxTree.cpp index 72ff627..7bee737 100644 --- a/src/openvic-dataloader/v2script/AbstractSyntaxTree.cpp +++ b/src/openvic-dataloader/v2script/AbstractSyntaxTree.cpp @@ -91,8 +91,9 @@ std::string FileAbstractSyntaxTree::make_list_visualizer() const { result.append(1, '\n'); - if (event == dryad::traverse_event::enter) + if (event == dryad::traverse_event::enter) { ++level; + } } return result; diff --git a/src/openvic-dataloader/v2script/EventGrammar.hpp b/src/openvic-dataloader/v2script/EventGrammar.hpp index 20168f8..af20ccf 100644 --- a/src/openvic-dataloader/v2script/EventGrammar.hpp +++ b/src/openvic-dataloader/v2script/EventGrammar.hpp @@ -32,7 +32,9 @@ namespace ovdl::v2script::grammar { bool is_number = true; for (auto* current = value->value().c_str(); *current; current++) { is_number = is_number && std::isdigit(*current); - if (!is_number) break; + if (!is_number) { + break; + } } if (!is_number) { state.logger().warning("month is not an integer") // diff --git a/src/openvic-dataloader/v2script/LuaDefinesGrammar.hpp b/src/openvic-dataloader/v2script/LuaDefinesGrammar.hpp index 885413c..8b4339a 100644 --- a/src/openvic-dataloader/v2script/LuaDefinesGrammar.hpp +++ b/src/openvic-dataloader/v2script/LuaDefinesGrammar.hpp @@ -66,8 +66,9 @@ namespace ovdl::v2script::lua::grammar { auto begin = scanner.position(); lexy::scan_result str_result; scanner.parse(str_result, rule); - if (!scanner || !str_result) + if (!scanner || !str_result) { return lexy::scan_failed; + } auto end = scanner.position(); auto str = str_result.value(); auto value = state.ast().intern(str.data(), str.size()); @@ -101,7 +102,9 @@ namespace ovdl::v2script::lua::grammar { static constexpr auto value = callback( [](detail::IsParseState auto& state, const char* pos, ast::IdentifierValue* name, ast::Value* initializer) -> ast::AssignStatement* { - if (initializer == nullptr) return nullptr; + if (initializer == nullptr) { + return nullptr; + } return state.ast().template create(pos, name, initializer); }, [](detail::IsParseState auto& state, ast::Value*) { diff --git a/src/openvic-dataloader/v2script/Parser.cpp b/src/openvic-dataloader/v2script/Parser.cpp index 9b36a95..f8506cb 100644 --- a/src/openvic-dataloader/v2script/Parser.cpp +++ b/src/openvic-dataloader/v2script/Parser.cpp @@ -348,7 +348,9 @@ const FilePosition Parser::get_error_position(const error::Error* error) const { void Parser::print_errors_to(std::basic_ostream& stream) const { auto errors = get_errors(); - if (errors.empty()) return; + if (errors.empty()) { + return; + } for (const auto error : errors) { dryad::visit_tree( error, diff --git a/src/openvic-dataloader/v2script/SimpleGrammar.hpp b/src/openvic-dataloader/v2script/SimpleGrammar.hpp index 06eeeb0..d2f87f5 100644 --- a/src/openvic-dataloader/v2script/SimpleGrammar.hpp +++ b/src/openvic-dataloader/v2script/SimpleGrammar.hpp @@ -215,8 +215,9 @@ namespace ovdl::v2script::grammar { auto begin = scanner.position(); lexy::scan_result str_result; scanner.parse(str_result, rule); - if (!scanner || !str_result) + if (!scanner || !str_result) { return lexy::scan_failed; + } auto end = scanner.position(); auto str = str_result.value(); auto value = state.ast().intern(str.data(), str.size()); @@ -297,13 +298,13 @@ namespace ovdl::v2script::grammar { return state.ast().template create(pos, left); }, [](detail::IsParseState auto& state, ast::Value* left) -> ast::ValueStatement* { - if (left == nullptr) { // May no longer be neccessary + if (left == nullptr) { // May no longer be necessary return nullptr; } return state.ast().template create(state.ast().location_of(left), left); }, [](detail::IsParseState auto& state, bool&, ast::Value* left) -> ast::ValueStatement* { - if (left == nullptr) { // May no longer be neccessary + if (left == nullptr) { // May no longer be necessary return nullptr; } return state.ast().template create(state.ast().location_of(left), left); diff --git a/tests/SCsub b/tests/SCsub index 49e2742..19e35dd 100644 --- a/tests/SCsub +++ b/tests/SCsub @@ -1,10 +1,7 @@ #!/usr/bin/env python import os import subprocess -import platform -import sys -import SCons from SCons.Script.SConscript import SConsEnvironment @@ -12,6 +9,7 @@ def UnitTestPostAction(target=None, source=None, env=None): print() return subprocess.run([target[0].path]).returncode + def UnitTest(env, **kwargs): test = env.Program(**kwargs) unit_test_action = env.Action(UnitTestPostAction, None) @@ -20,6 +18,7 @@ def UnitTest(env, **kwargs): env.AlwaysBuild(test_post_action) return test + SConsEnvironment.UnitTest = UnitTest Import("env") @@ -45,7 +44,7 @@ tests_env.Append(CPPDEFINES=["OPENVIC_DATALOADER_TESTS"]) tests_env.Append(CPPPATH=[tests_env.Dir(source_path)]) tests_env.tests_sources = env.GlobRecursive("*.cpp", [source_path]) -SConscript("deps/SCsub", {"env": tests_env }) +SConscript("deps/SCsub", {"env": tests_env}) # Blame Ubuntu 22's GCC-12 distribution for this crap # Compiler bug hangs if it can see if there is any reference to \x8F in a character @@ -53,8 +52,6 @@ if env["ubuntu_gcc_invalid_char_hang_bug"]: tests_env.Append(CPPDEFINES=["_OVDL_TEST_UBUNTU_GCC_12_BUG_"]) tests_program = tests_env.UnitTest( - source=tests_env.tests_sources, - target=os.path.join(BINDIR, tests_name), - PROGSUFFIX=".tests" + env["PROGSUFFIX"] + source=tests_env.tests_sources, target=os.path.join(BINDIR, tests_name), PROGSUFFIX=".tests" + env["PROGSUFFIX"] ) -Default(tests_program) \ No newline at end of file +Default(tests_program) diff --git a/tests/deps/SCsub b/tests/deps/SCsub index 7689a0d..e4e1d73 100644 --- a/tests/deps/SCsub +++ b/tests/deps/SCsub @@ -1,13 +1,12 @@ #!/usr/bin/env python -import os import subprocess from pathlib import Path Import("env") + def generate_snitch_config_header(target, source, env): header = [] - header_filename = "snitch_config.hpp" header.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.") header.append("") @@ -24,12 +23,14 @@ def generate_snitch_config_header(target, source, env): header.append("#include // for C++ feature check macros") for key, val in env.config_data.items(): - header +=(f''' + header += ( + f""" #if !defined({key}) # define {key} {val} -#endif''').split("\n") +#endif""" + ).split("\n") - header += (""" + header += """ #if defined(_MSC_VER) # if defined(_KERNEL_MODE) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS) # define SNITCH_EXCEPTIONS_NOT_AVAILABLE @@ -78,7 +79,7 @@ def generate_snitch_config_header(target, source, env): #else # define SNITCH_EXPORT #endif - """.split("\n")) + """.split("\n") header.append("") header.append(f"#endif // {header_guard}") @@ -87,6 +88,7 @@ def generate_snitch_config_header(target, source, env): with header_file_path.open("w+", encoding="utf-8") as header_file: header_file.write("\n".join(header)) + def build_snitch(env): major_version = 1 minor_version = 2 @@ -106,43 +108,39 @@ def build_snitch(env): snitch_env = env.Clone() - snitch_env.Append( - BUILDERS={ - "GenerateSnitchConfig": snitch_env.Builder(action=generate_snitch_config_header) - } - ) + snitch_env.Append(BUILDERS={"GenerateSnitchConfig": snitch_env.Builder(action=generate_snitch_config_header)}) snitch_env.config_data = { - "SNITCH_MAX_TEST_CASES": 5000, #"Maximum number of test cases in a test application." - "SNITCH_MAX_NESTED_SECTIONS": 8,#"Maximum depth of nested sections in a test case." - "SNITCH_MAX_EXPR_LENGTH": 1024, #"Maximum length of a printed expression when reporting failure." - "SNITCH_MAX_MESSAGE_LENGTH": 1024, #"Maximum length of error or status messages." - "SNITCH_MAX_TEST_NAME_LENGTH": 1024, #"Maximum length of a test case name." - "SNITCH_MAX_TAG_LENGTH": 256, #"Maximum length of a test tag." - "SNITCH_MAX_CAPTURES": 8, #"Maximum number of captured expressions in a test case." - "SNITCH_MAX_CAPTURE_LENGTH": 256, #"Maximum length of a captured expression." - "SNITCH_MAX_UNIQUE_TAGS": 1024, #"Maximum number of unique tags in a test application." - "SNITCH_MAX_COMMAND_LINE_ARGS": 1024, #"Maximum number of command line arguments to a test application." - "SNITCH_MAX_REGISTERED_REPORTERS": 8, #"Maximum number of registered reporter that can be selected from the command line." - "SNITCH_MAX_PATH_LENGTH": 1024, #"Maximum length of a file path when writing output to file." - "SNITCH_MAX_REPORTER_SIZE_BYTES": 128, #"Maximum size (in bytes) of a reporter object." - - "SNITCH_DEFINE_MAIN": 1, #"Define main() in snitch -- disable to provide your own main() function." - "SNITCH_WITH_EXCEPTIONS": 0, #"Use exceptions in snitch implementation -- will be forced OFF if exceptions are not available." - "SNITCH_WITH_MULTITHREADING": 0, #"Make the testing framework thread-safe -- disable if multithreading is not needed." - "SNITCH_WITH_TIMINGS": 1, #"Measure the time taken by each test case -- disable to speed up tests." - "SNITCH_WITH_SHORTHAND_MACROS": 1, #"Use short names for test macros -- disable if this causes conflicts." - "SNITCH_CONSTEXPR_FLOAT_USE_BITCAST": 1, #"Use std::bit_cast if available to implement exact constexpr float-to-string conversion." - "SNITCH_APPEND_TO_CHARS": 1, #"Use std::to_chars for string conversions -- disable for greater compatability with a slight performance cost." - "SNITCH_DEFAULT_WITH_COLOR": 1, #"Enable terminal colors by default -- can also be controlled by command line interface." - "SNITCH_DECOMPOSE_SUCCESSFUL_ASSERTIONS": 0, #"Enable expression decomposition even for successful assertions -- more expensive." - "SNITCH_WITH_ALL_REPORTERS": 1, #"Allow all built-in reporters to be selected from the command line -- disable for faster compilation." - "SNITCH_WITH_TEAMCITY_REPORTER": 0, #"Allow the TeamCity reporter to be selected from the command line -- enable if needed." - "SNITCH_WITH_CATCH2_XML_REPORTER": 0, #"Allow the Catch2 XML reporter to be selected from the command line -- enable if needed." - - "SNITCH_HEADER_ONLY": 0, #"Create a single-header header-only version of snitch." - "SNITCH_UNITY_BUILD": ("1" if UNITY_BUILD else "0"), #"Build sources as single file instead of separate files (faster full build)." - "SNITCH_DO_TEST": 1, #"Build tests." + "SNITCH_MAX_TEST_CASES": 5000, # "Maximum number of test cases in a test application." + "SNITCH_MAX_NESTED_SECTIONS": 8, # "Maximum depth of nested sections in a test case." + "SNITCH_MAX_EXPR_LENGTH": 1024, # "Maximum length of a printed expression when reporting failure." + "SNITCH_MAX_MESSAGE_LENGTH": 1024, # "Maximum length of error or status messages." + "SNITCH_MAX_TEST_NAME_LENGTH": 1024, # "Maximum length of a test case name." + "SNITCH_MAX_TAG_LENGTH": 256, # "Maximum length of a test tag." + "SNITCH_MAX_CAPTURES": 8, # "Maximum number of captured expressions in a test case." + "SNITCH_MAX_CAPTURE_LENGTH": 256, # "Maximum length of a captured expression." + "SNITCH_MAX_UNIQUE_TAGS": 1024, # "Maximum number of unique tags in a test application." + "SNITCH_MAX_COMMAND_LINE_ARGS": 1024, # "Maximum number of command line arguments to a test application." + "SNITCH_MAX_REGISTERED_REPORTERS": 8, # "Maximum number of registered reporter that can be selected from the command line." + "SNITCH_MAX_PATH_LENGTH": 1024, # "Maximum length of a file path when writing output to file." + "SNITCH_MAX_REPORTER_SIZE_BYTES": 128, # "Maximum size (in bytes) of a reporter object." + "SNITCH_DEFINE_MAIN": 1, # "Define main() in snitch -- disable to provide your own main() function." + "SNITCH_WITH_EXCEPTIONS": 0, # "Use exceptions in snitch implementation -- will be forced OFF if exceptions are not available." + "SNITCH_WITH_MULTITHREADING": 0, # "Make the testing framework thread-safe -- disable if multithreading is not needed." + "SNITCH_WITH_TIMINGS": 1, # "Measure the time taken by each test case -- disable to speed up tests." + "SNITCH_WITH_SHORTHAND_MACROS": 1, # "Use short names for test macros -- disable if this causes conflicts." + "SNITCH_CONSTEXPR_FLOAT_USE_BITCAST": 1, # "Use std::bit_cast if available to implement exact constexpr float-to-string conversion." + "SNITCH_APPEND_TO_CHARS": 1, # "Use std::to_chars for string conversions -- disable for greater compatibility with a slight performance cost." + "SNITCH_DEFAULT_WITH_COLOR": 1, # "Enable terminal colors by default -- can also be controlled by command line interface." + "SNITCH_DECOMPOSE_SUCCESSFUL_ASSERTIONS": 0, # "Enable expression decomposition even for successful assertions -- more expensive." + "SNITCH_WITH_ALL_REPORTERS": 1, # "Allow all built-in reporters to be selected from the command line -- disable for faster compilation." + "SNITCH_WITH_TEAMCITY_REPORTER": 0, # "Allow the TeamCity reporter to be selected from the command line -- enable if needed." + "SNITCH_WITH_CATCH2_XML_REPORTER": 0, # "Allow the Catch2 XML reporter to be selected from the command line -- enable if needed." + "SNITCH_HEADER_ONLY": 0, # "Create a single-header header-only version of snitch." + "SNITCH_UNITY_BUILD": ( + "1" if UNITY_BUILD else "0" + ), # "Build sources as single file instead of separate files (faster full build)." + "SNITCH_DO_TEST": 1, # "Build tests." } snitch_full_version = "" @@ -152,20 +150,24 @@ def build_snitch(env): snitch_full_version = SNITCH_VERSION + (".{}".format(snitch_full_version) if snitch_full_version else "") - snitch_env.Append(CPPDEFINES=[ - f'SNITCH_VERSION=\\"{SNITCH_VERSION}\\"', - f'SNITCH_FULL_VERSION=\\"{snitch_full_version}\\"', - f"SNITCH_VERSION_MAJOR={major_version}", - f"SNITCH_VERSION_MINOR={minor_version}", - f"SNITCH_VERSION_PATCH={patch_version}" - ]) + snitch_env.Append( + CPPDEFINES=[ + f'SNITCH_VERSION=\\"{SNITCH_VERSION}\\"', + f'SNITCH_FULL_VERSION=\\"{snitch_full_version}\\"', + f"SNITCH_VERSION_MAJOR={major_version}", + f"SNITCH_VERSION_MINOR={minor_version}", + f"SNITCH_VERSION_PATCH={patch_version}", + ] + ) snitch_env.Append(CPPDEFINES=["SNITCH_SHARED_LIBRARY=" + ("1" if not HEADER_ONLY and SHARED_BUILD else "0")]) include_path = "snitch/include" source_path = "snitch/src" unity_source = "snitch.cpp" - config = snitch_env.GenerateSnitchConfig(snitch_env.File(Path(include_path) / "snitch" / "snitch_config.hpp"), "SCsub") + config = snitch_env.GenerateSnitchConfig( + snitch_env.File(Path(include_path) / "snitch" / "snitch_config.hpp"), "SCsub" + ) snitch_env.Append(CPPPATH=[[snitch_env.Dir(p) for p in [source_path, include_path]]]) sources = snitch_env.GlobRecursive("*.cpp", [source_path], Path(source_path) / unity_source) @@ -198,4 +200,5 @@ def build_snitch(env): env.Append(CPPPATH=[[snitch_env.Dir(p) for p in [source_path, include_path]]]) Default(config) -build_snitch(env) \ No newline at end of file + +build_snitch(env) diff --git a/tests/src/v2script/AbstractSyntaxTree.cpp b/tests/src/v2script/AbstractSyntaxTree.cpp index ad9382f..45f2b5d 100644 --- a/tests/src/v2script/AbstractSyntaxTree.cpp +++ b/tests/src/v2script/AbstractSyntaxTree.cpp @@ -56,8 +56,9 @@ struct Ast : SymbolIntern { NodeLocation location_of(const Node* n) const { auto result = map.lookup(n); - if (result == nullptr) + if (result == nullptr) { return {}; + } return *result; } };