diff --git a/.github/workflows/formatter-config.yml b/.github/workflows/formatter-config.yml new file mode 100644 index 0000000000..6715a8b275 --- /dev/null +++ b/.github/workflows/formatter-config.yml @@ -0,0 +1,36 @@ +name: Formatter configuration +on: + pull_request: + paths: + - '.uncrustify.cfg' + - 'devtools/format/**' + - 'SerialPrograms/CMakeLists.txt' + - 'SerialPrograms/cmake/Formatting.cmake' + - 'SerialPrograms/cmake/RunFormatting.cmake' + - '.github/workflows/formatter-config.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + config-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - name: Build pinned Uncrustify + shell: bash + working-directory: ${{ runner.temp }} + run: | + curl --fail --location --silent --show-error \ + https://github.com/uncrustify/uncrustify/archive/refs/tags/uncrustify-0.83.0.tar.gz \ + --output uncrustify.tar.gz + printf '%s %s\n' \ + 1d4d3ab3a991c66eb24cb0a3e690573b4882fd98bc6ec64a01c283998c20dc87 \ + uncrustify.tar.gz | sha256sum --check --status + tar -xzf uncrustify.tar.gz + cmake -S uncrustify-uncrustify-0.83.0 -B uncrustify-build -DCMAKE_BUILD_TYPE=Release + cmake --build uncrustify-build --parallel 4 + echo "$RUNNER_TEMP/uncrustify-build" >> "$GITHUB_PATH" + - run: python -m unittest discover -s devtools/format -v diff --git a/.uncrustify.cfg b/.uncrustify.cfg new file mode 100644 index 0000000000..209088c299 --- /dev/null +++ b/.uncrustify.cfg @@ -0,0 +1,115 @@ +# Uncrustify 0.83.0. Usage and scope: devtools/format/README.md. +# Keep include order, comment text, existing LF/CRLF and unlimited line width. +newlines = auto +input_tab_size = 4 +output_tab_size = 4 +indent_columns = 4 +indent_continue = 4 +indent_with_tabs = 0 +indent_namespace = false +indent_access_spec = 1 +code_width = 0 +cmt_width = 0 +cmt_reflow_mode = 0 +cmt_indent_multi = false +mod_sort_include = false +mod_sort_using = false +mod_remove_duplicate_include = false + +# Compact braces, with a space before control parentheses: if (ready()){ +sp_before_sparen = force +sp_sparen_brace = remove +# Preserve alignment before short-function bodies (const/non-const overloads). +sp_fparen_brace = ignore +sp_cpp_lambda_paren_brace = remove +sp_cpp_lambda_square_brace = remove +sp_word_brace_ns = remove +sp_enum_brace = remove +sp_paren_brace = remove +sp_else_brace = remove +sp_brace_else = remove +sp_try_brace = remove +sp_catch_brace = remove +sp_brace_catch = remove +sp_do_brace_open = remove +sp_brace_close_while = remove +nl_if_brace = remove +nl_for_brace = remove +nl_while_brace = remove +nl_switch_brace = remove +nl_do_brace = remove +nl_try_brace = remove +nl_catch_brace = remove +nl_else_brace = remove +nl_brace_else = remove +nl_namespace_brace = remove +nl_class_brace = remove +nl_struct_brace = remove +nl_enum_brace = remove +# Preserve constructor brace/comment placement; attaching across a commented-out +# initializer moves the brace past the comment. Same-line gaps still collapse. +nl_fdef_brace = ignore + +# Type-attached pointers/references; conventional operator/comma spacing. +sp_before_ptr_star = remove +sp_after_ptr_star = force +sp_before_byref = remove +sp_after_byref = force +sp_assign = force +sp_arith = force +sp_compare = force +sp_bool = force +sp_after_comma = force +sp_before_comma = remove + +# Expand braced control bodies, but do not add/remove any braces or statements. +nl_split_if_one_liner = true +nl_split_for_one_liner = true +nl_split_while_one_liner = true +mod_full_brace_if = ignore +mod_full_brace_for = ignore +mod_full_brace_while = ignore +mod_full_brace_do = ignore +mod_full_brace_function = ignore +mod_paren_on_return = ignore +mod_paren_on_throw = ignore +mod_remove_extra_semicolon = false +mod_remove_empty_return = false +mod_enum_last_comma = ignore +mod_add_long_namespace_closebrace_comment = 0 +# Keep type spacing: `remove` can merge `operator const Type` into constType. +# This preserves existing standalone class-name/brace spacing as well. +sp_after_type = ignore +sp_angle_shift = ignore +sp_permit_cpp11_shift = true +indent_class = true + +sp_before_class_colon = force +sp_after_class_colon = force + +# Preserve compact functions/tables and extra spacing between tokens. +# Leading declaration alignment still needs explicit protection; see README. +nl_func_leave_one_liners = true +nl_getset_leave_one_liners = true +nl_class_leave_one_liners = true +nl_cpp_lambda_leave_one_liners = true +nl_assign_leave_one_liners = true +nl_enum_leave_one_liners = true +align_keep_extra_space = true + +# Keep closing-parenthesis columns and the repository's continuation layout. +# Keeping the first continuation verbatim makes some nested-lambda/table cases +# drift on every pass in 0.83.0. Use a stable four-space continuation instead. +indent_ignore_first_continue = false +indent_paren_close = -1 + +# The repository consistently spells parameter packs class... / typename.... +sp_type_ellipsis = remove +sp_before_ellipsis = remove +# Keep a braced argument indented relative to the enclosing call's parentheses. +indent_paren_open_brace = true +indent_func_call_param = true + +# Match existing lambda bodies inside calls; do not apply continuation twice. +indent_cpp_lambda_only_once = true +nl_brace_catch = remove diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index 7165a721cb..0600b6c971 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -40,6 +40,10 @@ add_custom_target(build-time-make-directory ALL # Internal repo or not, we're always building from the SerialPrograms folder set(REPO_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../") +# Optional development targets; do not build or link the application. +include(cmake/Formatting.cmake) +pa_add_format_targets("${REPO_ROOT_DIR}") + # Determine environment if(DEFINED ENV{GITHUB_ACTIONS}) message(STATUS "Detected CI environment, skipping qt deployment") diff --git a/SerialPrograms/cmake/Formatting.cmake b/SerialPrograms/cmake/Formatting.cmake new file mode 100644 index 0000000000..884bb02c4b --- /dev/null +++ b/SerialPrograms/cmake/Formatting.cmake @@ -0,0 +1,29 @@ +# Incremental C++ formatting, with no application build dependency. +# cmake --build /path/to/build --target format # apply eligible edited-line spacing +# cmake --build /path/to/build --target format-check # non-writing check +include_guard(GLOBAL) + +# Add explicit targets; defer Python/tool discovery until a formatting target is run. +function(pa_add_format_targets repo_root) + get_filename_component(format_repo "${repo_root}" ABSOLUTE) + set(PA_FORMAT_BASE "HEAD" CACHE STRING "Git parent ref for incremental formatting (merge base with HEAD)") + set(PA_FORMAT_PYTHON "" CACHE FILEPATH "Optional Python 3.8+ interpreter for formatting only") + foreach(format_target IN ITEMS format format-check) + if(format_target STREQUAL "format") + set(format_mode --write) + else() + set(format_mode --check) + endif() + add_custom_target(${format_target} + COMMAND "${CMAKE_COMMAND}" + "-DPA_FORMAT_REPO=${format_repo}" + "-DPA_FORMAT_BASE=${PA_FORMAT_BASE}" + "-DPA_FORMAT_MODE=${format_mode}" + "-DPA_FORMAT_PYTHON=${PA_FORMAT_PYTHON}" + -P "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/RunFormatting.cmake" + COMMENT "Incremental C++ ${format_target}: Git-edited lines only" + USES_TERMINAL + VERBATIM + ) + endforeach() +endfunction() diff --git a/SerialPrograms/cmake/RunFormatting.cmake b/SerialPrograms/cmake/RunFormatting.cmake new file mode 100644 index 0000000000..69cecfd115 --- /dev/null +++ b/SerialPrograms/cmake/RunFormatting.cmake @@ -0,0 +1,25 @@ +# Target-time adapter; invoked by Formatting.cmake, not during application configure. +# cmake --build /path/to/build --target format-check +cmake_minimum_required(VERSION 3.24) + +if(NOT PA_FORMAT_MODE STREQUAL "--write" AND NOT PA_FORMAT_MODE STREQUAL "--check") + message(FATAL_ERROR "Use the format or format-check build target.") +endif() +if(PA_FORMAT_PYTHON) + set(Python3_EXECUTABLE "${PA_FORMAT_PYTHON}") +endif() +find_package(Python3 3.8 QUIET COMPONENTS Interpreter) +if(NOT Python3_Interpreter_FOUND) + message(FATAL_ERROR "Formatting needs Python 3.8+. Install it or configure PA_FORMAT_PYTHON=/path/to/python3.") +endif() +execute_process( + COMMAND "${Python3_EXECUTABLE}" "${PA_FORMAT_REPO}/devtools/format/format_changed.py" + --repo "${PA_FORMAT_REPO}" --base "${PA_FORMAT_BASE}" "${PA_FORMAT_MODE}" + RESULT_VARIABLE format_result +) +if(NOT format_result STREQUAL "0") + if(PA_FORMAT_MODE STREQUAL "--check" AND format_result STREQUAL "1") + message(FATAL_ERROR "Edited-line formatting remains. Run the format target, then review and stage its changes.") + endif() + message(FATAL_ERROR "Incremental formatter failed (${format_result}); see its diagnostic above. Requires Uncrustify 0.83.0 and Clang; clang-format is not used.") +endif() diff --git a/devtools/format/CMAKE.md b/devtools/format/CMAKE.md new file mode 100644 index 0000000000..089b0320dd --- /dev/null +++ b/devtools/format/CMAKE.md @@ -0,0 +1,58 @@ +# CMake formatting targets + +After this integration is present in the configured source checkout: + +```sh +cmake --build /path/to/build --target format-check +cmake --build /path/to/build --target format +``` + +`format-check` previews eligible changes and fails if any remain. `format` +applies them. Neither target builds or links the app. They use the +[edited-line formatter](INCREMENTAL.md), not clang-format: tracked staged and +unstaged changes against HEAD, with all original leading columns/newlines kept. +They skip block reflows, preprocessor definitions and declaration lines. Review +the output and stage changes yourself; the index is never changed automatically. + +The target belongs to the build directory's **configured source checkout**. +Running a lab build's target formats that lab checkout, not a different feature +worktree in the terminal's current directory. Use a build configured from your +feature worktree, or invoke the Python command with `--repo` to choose another. +An old build does not gain targets until its source picks up this integration +and CMake reconfigures. + +Python 3.8+, Uncrustify 0.83.0 and Clang are needed when formatting eligible +changes. Python discovery happens only when a format target runs; it does not +add a Python/formatter requirement to normal app configuration. No dependency +is downloaded automatically and no clang-format installation is required. + +Optional settings: + +```sh +cmake -S SerialPrograms -B /path/to/build \ + -DPA_FORMAT_BASE=origin/main \ + -DPA_FORMAT_PYTHON=/path/to/python3 +``` + +`PA_FORMAT_BASE` defaults to HEAD; another ref selects its merge base with HEAD +for whole-branch formatting. Use the actual parent for a stacked branch. Leave +`PA_FORMAT_PYTHON` empty to discover Python at target time. `UNCRUSTIFY` and +`CLANG` environment variables select non-PATH executables as with the CLI. + +To configure a tools-only build without Qt/OpenCV or application dependencies: + +```sh +cmake -S SerialPrograms -B /path/to/tools-build \ + -DPA_CORE_ONLY=ON -DCOMMAND_LINE_EXE=OFF +cmake --build /path/to/tools-build --target format-check +``` + +This still performs normal CMake compiler/thread checks but compiles no app +when the explicit formatting target is requested. There is no `cmake --format` +flag; formatting is a project-defined build target. CTest registration for the +native application tests is a separate integration. + +Tests live in `test_cmake.py` beside the formatter tests and include the actual +CMake module. They check source/build paths with spaces, a committed parent ref, +index preservation, useful missing-Python diagnostics, and that explicit format +targets do not run an unrelated ALL/application target. diff --git a/devtools/format/INCREMENTAL.md b/devtools/format/INCREMENTAL.md new file mode 100644 index 0000000000..21d2e5bf0a --- /dev/null +++ b/devtools/format/INCREMENTAL.md @@ -0,0 +1,91 @@ +# Format edited lines only + +Use this mode for routine development. It avoids the broad reindentation and +known declaration-spacing changes in the full-file formatter preview. + +The tool needs Python 3, Uncrustify 0.83.0 and Clang (for a raw-token check). +It does not build or run SerialPrograms or connect a console. + +From your code worktree, preview first: + +```sh +python3 /path/to/tools/devtools/format/format_changed.py --repo . +``` + +While the tools PR is under review, the local checkout path is: + +```sh +python3 ~/Projects/wt/incremental-cpp-format/devtools/format/format_changed.py --repo . +``` + +Then apply the reviewed proposal: + +```sh +python3 ~/Projects/wt/incremental-cpp-format/devtools/format/format_changed.py --repo . --write +``` + +No directory change is necessary: `--repo ~/Projects/wt/bdsp-my-fix` selects +that checkout explicitly. The tool always uses the configuration beside its own +script, so the target branch need not merge the tools PR first. + +## Scope and behavior + +Default comparison is **HEAD against the working tree**, including staged and +unstaged edits. No commit is required. New files must first be tracked with +`git add`; untracked, deleted and renamed files are excluded. If a rename also +contains edits, commit the rename separately before using the default local mode. +Only `.h`, `.c`, `.cpp` and `.tpp` files in Common/SerialPrograms are considered. + +For a whole branch, compare with its merge base with a chosen parent: + +```sh +python3 /path/to/format_changed.py --repo . --base origin/main +``` + +Choose the actual parent for a stacked PR; do not compare a large story chain +with main when you only intend to format its top layer. The tool does not fetch. + +- Runs Uncrustify on each selected file to obtain context, then accepts only + same-line whitespace edits on lines Git marks added/modified. +- Keeps every original leading column, including manual declaration alignment, + and every original newline. Untouched lines remain byte-identical. +- Skips formatter hunks that change line count, preprocessor directives and + their continuations, and lines containing class/struct/union keywords. Those + skips keep block reflows and known declaration-brace changes out of the patch. +- Checks the candidate with Clang's raw lexer before writing: significant token + kind/spelling must match, including quoted/raw string contents. This does not + preprocess includes or prove every macro-invocation behavior equivalent; + review the displayed patch. Macro definitions are protected; invocations in + ordinary code are not universally identifiable without preprocessing. +- Verifies all candidates first and refuses a stale source snapshot. It never + stages files, commits, switches branches or changes the index. After --write, + review and stage the formatting yourself. + +This mode intentionally does **not** fix indentation, insert braces, expand +single-line control bodies, reflow blocks or assert complete style compliance. +Use existing lint/review for those. Skipped selected edits are reported on stderr; +stdout is the eligible patch. An unchanged result can mean the remaining +formatter suggestions were deliberately outside this mode's scope. + +`--check` performs the same preview without writing and returns 1 if eligible +formatting remains; 0 means no eligible changes, and 2 indicates a tool, lexer, +version or source-snapshot error. Preview alone returns 0 without writing. +There is no automatic hook or source-format CI gate in this PR. + +```sh +python3 /path/to/format_changed.py --repo . --check +``` + +Use `--uncrustify /path/to/uncrustify` / `--clang /path/to/clang` or environment +variables `UNCRUSTIFY` / `CLANG` for non-PATH installations. + +## Tests + +```sh +python3 -m unittest discover -s devtools/format -v +``` + +Tests call the real formatter and lexer, and use temporary Git repositories for +preview/check/write, staged-index preservation, explicit bases, unusual file +names, stale snapshots and refusal-before-write behavior. Application tests +remain native in their owning modules. diff --git a/devtools/format/README.md b/devtools/format/README.md new file mode 100644 index 0000000000..6abc5a27f0 --- /dev/null +++ b/devtools/format/README.md @@ -0,0 +1,114 @@ +# C++ formatting + +Use **Uncrustify 0.83.0** with the root `.uncrustify.cfg`. This replaces the +initial clang-format proposal: Uncrustify can produce the repository's compact +`if (condition){`, `}else{` and `namespace Name{` spelling directly. +No regex postprocessor or change to AGENTS.md's style rules is needed. + +## Install and preview + +On macOS: + +```sh +brew install uncrustify +uncrustify --version +``` + +Check for `Uncrustify-0.83.0` (Homebrew's release appends `_f`). CI builds that +release from a SHA-256-verified source archive. If your package manager supplies +a different version, install the pinned release before comparing formatter output. + +From the repo root, preview a specific file without changing it: + +```sh +uncrustify -q -c .uncrustify.cfg -l CPP \ + -f SerialPrograms/Source/CommonFramework/Main.cpp -o /tmp/Main.formatted.cpp +git diff --no-index -- SerialPrograms/Source/CommonFramework/Main.cpp /tmp/Main.formatted.cpp +``` + +A diff exits 1 when changes are present; that is expected. Apply to an explicit +file only after reviewing the preview: + +```sh +uncrustify -q -c .uncrustify.cfg -l CPP --replace --no-backup \ + SerialPrograms/Source/CommonFramework/Main.cpp +``` + +To check an explicit file without writing it: + +```sh +uncrustify -q -c .uncrustify.cfg -l CPP --check \ + SerialPrograms/Source/CommonFramework/Main.cpp +``` + +Format edited files in a separate commit from behavioral changes. Preserve +unrelated changes and do not format vendored or generated files. The repository +contains legacy formatting differences; adopting the configuration does not +require reformatting all existing sources. This PR's CI tests the configuration, +not source-wide compliance. Do not enable a broad format-on-save hook yet. + +## What this configuration covers + +- Four spaces, no indentation tabs, unindented namespaces/access labels and + type-attached pointers/references. +- Compact control/namespace braces and spaced control parentheses. Existing + standalone class brace spacing and nested-template `>>` spelling are preserved. + Braced single-line `if`/`for`/`while` bodies expand onto multiple lines; + ordinary short functions and empty constructors stay compact. +- Existing LF or CRLF style, include order (including own-header-last and + registration-order exceptions), comment text and unlimited line width. +- Existing spacing within aligned declarations/overloads, parameter-pack + spelling (`class... Args`), four-space continuation layout and existing + closing-parenthesis columns. Lambdas inside calls keep their ordinary body indentation. +- No brace insertion/removal, statement removal, include sorting or generated + namespace comments. Missing-brace and namespace/API documentation requirements + remain the responsibility of review and existing code-health checks. + +Formatting still changes indentation, spacing and some line breaks. C++ macros, +conditional compilation and newer syntax need review; a successful formatter +exit does not prove semantic equivalence or a successful native build. Main-tree +trials are performed in an isolated snapshot and reviewed before any formatting +commit is proposed. Known limitations are recorded in the fork PR/run record: + +- Class/struct brace spacing is not fully enforced: standalone declarations + retain their existing spacing, and inherited declarations can gain a space + before `{`, for example + `struct Derived : public Base {`. Uncrustify 0.83.0 does not expose a separate + configurable spacing rule for this case. Restore the repository's compact + spelling when reviewing output; this formatter is not a complete code-health + compliance check. +- Leading spaces used to align const/non-const overloads are still normalized + to the block indentation. `align_keep_extra_space` preserves spacing between + tokens, not arbitrary leading columns. Protect a deliberate table explicitly + with the tool's `// *INDENT-OFF*` / `// *INDENT-ON*` markers, or leave that + region unformatted. Tests expose this limitation and verify protected tables + remain byte-identical. No markers are added to application sources by this PR. +- Function-definition brace line breaks are preserved to avoid moving a + constructor's brace across comments or commented-out initializer entries. +- Missing braces stay missing. Formatting is not a substitute for the existing + multiline-control-flow/braces lint rules. + +## Configuration tests + +These are tooling tests, not application tests. They call the real formatter: + +```sh +python3 -m unittest discover -s devtools/format -v +``` + +For a non-PATH installation: + +```sh +UNCRUSTIFY=/path/to/uncrustify python3 -m unittest discover -s devtools/format -v +``` + +Coverage includes exact brace spelling, indentation, pointers, includes, +line-ending preservation, comment/long-line preservation, templates/designated +initializers, raw strings, macro continuations/token pasting, constructor-comment placement and idempotence. +Regressions also preserve conversion-operator tokens, short functions, empty +constructors, intra-line alignment, argument/closing-parenthesis layouts, lambdas, +attached catch chains, parameter packs and repeated-pass stability for nested +lambdas/initializer tables. Known inherited-class spacing and +leading-overload alignment gaps are tested explicitly rather than claimed fixed. + +Reference: [Uncrustify 0.83.0 options](https://github.com/uncrustify/uncrustify/blob/uncrustify-0.83.0/documentation/htdocs/default.cfg). diff --git a/devtools/format/format_changed.py b/devtools/format/format_changed.py new file mode 100644 index 0000000000..c39d90d6dd --- /dev/null +++ b/devtools/format/format_changed.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""Preview whitespace formatting of edited C/C++ lines, from any working directory. + + python3 /path/to/tools/devtools/format/format_changed.py --repo /path/to/code + python3 devtools/format/format_changed.py --write + python3 devtools/format/format_changed.py --base origin/main --check + +Uses the config beside this tool, Uncrustify 0.83.0 and Clang's raw lexer. +Default scope is staged + unstaged tracked edits against HEAD; --base selects +its merge base with HEAD. Never stages, commits, or reformats untouched lines. +See INCREMENTAL.md for the intentionally narrow formatting scope. +""" + +import argparse +from collections import Counter +from dataclasses import dataclass +import difflib +import os +from pathlib import Path +import re +import subprocess +import sys + + +CONFIG = Path(__file__).resolve().parents[2] / '.uncrustify.cfg' +SUFFIXES = {'.h', '.c', '.cpp', '.tpp'} + + +@dataclass +class Selection: + """Changed lines tied to the exact bytes read when their Git diff was measured.""" + lines: set + source: bytes + + +@dataclass +class Plan: + """A verified candidate plus the original bytes needed to detect stale plans.""" + path: Path + before: bytes + after: bytes + skipped: dict + + +def git(repo, *args): + """Read Git state; never invoke shell expansion, external diff or textconv.""" + return subprocess.check_output(['git', '-C', str(repo), *args]) + + +def hunk_lines(diff): + """Return one-based added/modified working-tree line numbers, not deletion anchors.""" + lines = set() + for match in re.finditer(rb'^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@', diff, re.M): + start = int(match[1]) + count = int(match[2]) if match[2] is not None else 1 + lines.update(range(start, start + count)) + return lines + + +def selected_lines(repo, base): + """Select tracked additions/modifications; ignore renamed and untracked files.""" + command = ['diff', '--no-ext-diff', '--no-textconv', '--find-renames', base] + names = git(repo, *command, '--name-only', '--diff-filter=AM', '-z', '--', 'Common', 'SerialPrograms') + selected = {} + for raw in filter(None, names.split(b'\0')): + name = os.fsdecode(raw) + if Path(name).suffix not in SUFFIXES: + continue + path = repo / name + if path.is_symlink(): + raise ValueError('Refusing to format a symbolic link: ' + name) + source = path.read_bytes() + diff = git(repo, *command, '--no-color', '--unified=0', '--', ':(literal)' + name) + if path.read_bytes() != source: + raise ValueError('Source changed while measuring the diff: ' + name) + if hunk_lines(diff): + selected[name] = Selection(hunk_lines(diff), source) + return selected + + +def protected_lines(lines): + """Protect preprocessor directives and their backslash continuation lines.""" + protected = set() + continuation = False + for index, line in enumerate(lines): + if continuation or line.lstrip().startswith(b'#'): + protected.add(index + 1) + continuation = line.rstrip(b'\r\n').rstrip(b' \t').endswith(b'\\') + return protected + + +def local_edits(source, formatted, selected): + """Keep same-line whitespace edits in scope; retain indentation and line endings.""" + original = source.splitlines(keepends=True) + output = formatted.splitlines(keepends=True) + result = original.copy() + protected = protected_lines(original) + skipped = Counter() + for tag, start, end, new_start, new_end in difflib.SequenceMatcher( + None, original, output, autojunk=False + ).get_opcodes(): + if tag == 'equal': + continue + if end - start != new_end - new_start: + skipped['reflow'] += len(selected.intersection(range(start + 1, end + 1))) + continue + for index, replacement in zip(range(start, end), output[new_start:new_end]): + if index + 1 not in selected: + continue + old = original[index] + if index + 1 in protected or re.search(rb'\b(class|struct|union)\b', old): + skipped['protected'] += 1 + continue + if b''.join(old.split()) != b''.join(replacement.split()): + raise ValueError('Formatter proposed a non-whitespace rewrite on an edited line.') + body = old.rstrip(b'\r\n') + prefix = body[:len(body) - len(body.lstrip(b' \t'))] + result[index] = prefix + replacement.rstrip(b'\r\n').lstrip(b' \t') + old[len(body):] + return b''.join(result), dict(skipped) + + +def raw_tokens(source, clang): + """Get significant token kinds/spellings without includes, preprocessing or execution.""" + result = subprocess.run( + [clang, '-x', 'c++', '-std=c++23', '-fsyntax-only', '-Xclang', '-dump-raw-tokens', '-'], + input=source, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ) + tokens = [] + for record in re.split(rb'\tLoc=<:\d+:\d+>\r?\n', result.stderr): + if not record: + continue + match = re.match(rb"^(\w+) '(.*)'\t", record, re.S) + if match is None: + raise ValueError('Could not parse Clang raw token output; no file was written.') + kind, spelling = match.groups() + if kind == b'comment' or (kind == b'unknown' and spelling.isspace()): + continue + tokens.append((kind, spelling)) + return tokens + + +def verify_tokens(source, candidate, clang): + """Reject whitespace changes that merge identifiers/operators or alter string literals.""" + if raw_tokens(source, clang) != raw_tokens(candidate, clang): + raise ValueError('C++ token kind/spelling changed; no file was written.') + + +def make_plans(repo, selection, uncrustify, clang): + """Verify every candidate before allowing the caller to write any source file.""" + version = subprocess.check_output([uncrustify, '--version'], text=True).strip() + if re.fullmatch(r'Uncrustify-0\.83\.0(?:_f)?', version) is None: + raise ValueError('Expected Uncrustify 0.83.0; found ' + version) + plans = [] + for name, selected in selection.items(): + path = repo / name + if path.is_symlink(): + raise ValueError('Refusing to format a symbolic link: ' + name) + source = selected.source + if path.read_bytes() != source: + raise ValueError('Source changed after measuring the diff: ' + name) + result = subprocess.run( + [uncrustify, '-q', '-c', str(CONFIG), '-l', 'CPP'], input=source, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + ) + if result.returncode or result.stderr: + raise ValueError(name + ': ' + result.stderr.decode(errors='replace')) + candidate, skipped = local_edits(source, result.stdout, selected.lines) + if candidate != source: + verify_tokens(source, candidate, clang) + plans.append(Plan(path, source, candidate, skipped)) + return plans + + +def write_plans(plans): + """Keep the index untouched; refuse plans invalidated by a concurrent source edit.""" + for plan in plans: + if plan.path.is_symlink() or plan.path.read_bytes() != plan.before: + raise ValueError('Source changed after planning: ' + str(plan.path)) + for plan in plans: + if plan.after != plan.before: + if plan.path.is_symlink() or plan.path.read_bytes() != plan.before: + raise ValueError('Source changed before writing: ' + str(plan.path)) + plan.path.write_bytes(plan.after) + + +def main(argv=None): + """Preview by default; --write applies, --check returns 1 for pending local edits.""" + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--repo', type=Path, default=Path.cwd()) + parser.add_argument('--base', default='HEAD', help='Compare the working tree with this revision\'s merge base with HEAD') + parser.add_argument('--uncrustify', default=os.environ.get('UNCRUSTIFY', 'uncrustify')) + parser.add_argument('--clang', default=os.environ.get('CLANG', 'clang')) + mode = parser.add_mutually_exclusive_group() + mode.add_argument('--write', action='store_true') + mode.add_argument('--check', action='store_true') + args = parser.parse_args(argv) + try: + repo = Path(os.fsdecode(git(args.repo, 'rev-parse', '--show-toplevel')).strip()) + base = os.fsdecode(git(repo, 'merge-base', args.base, 'HEAD')).strip() + selection = selected_lines(repo, base) + plans = make_plans(repo, selection, args.uncrustify, args.clang) if selection else [] + for plan in plans: + name = plan.path.relative_to(repo).as_posix() + sys.stdout.writelines(difflib.unified_diff( + plan.before.decode(errors='backslashreplace').splitlines(keepends=True), + plan.after.decode(errors='backslashreplace').splitlines(keepends=True), + fromfile='a/' + name, tofile='b/' + name, + )) + if plan.skipped: + print(name + ': skipped ' + str(plan.skipped), file=sys.stderr) + if args.write: + write_plans(plans) + count = sum(plan.before != plan.after for plan in plans) + print(f'{count} file(s) with eligible edited-line formatting; index untouched.', file=sys.stderr) + return int(args.check and count > 0) + except (OSError, ValueError, subprocess.CalledProcessError) as error: + print('Formatting refused: ' + str(error), file=sys.stderr) + return 2 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/devtools/format/test_changed.py b/devtools/format/test_changed.py new file mode 100644 index 0000000000..acf6beefa4 --- /dev/null +++ b/devtools/format/test_changed.py @@ -0,0 +1,149 @@ +"""Incremental formatting tests: python3 -m unittest discover -s devtools/format -v.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +import format_changed as changed + + +class LocalEditTests(unittest.TestCase): + def test_only_selected_line_changes_and_indent_is_preserved(self): + source = b' int before=1;\n int value=2;\n int after=3;\n' + formatted = b' int before = 1;\n int value = 2;\n int after = 3;\n' + candidate, _ = changed.local_edits(source, formatted, {2}) + self.assertEqual(b' int before=1;\n int value = 2;\n int after=3;\n', candidate) + + def test_reflows_and_declaration_braces_are_skipped(self): + source = b'class Derived : public Base{\n void f(){ if(x){run();} }\n};\n' + formatted = b'class Derived : public Base {\n void f(){\n if (x){\n run();\n }\n }\n};\n' + candidate, skips = changed.local_edits(source, formatted, {1, 2}) + self.assertEqual(source, candidate) + self.assertTrue(skips) + declaration = b'class Derived : public Base{\n' + candidate, skips = changed.local_edits( + declaration, b'class Derived : public Base {\n', {1} + ) + self.assertEqual(declaration, candidate) + self.assertEqual({'protected': 1}, skips) + + def test_preprocessor_and_continuation_lines_are_not_edited(self): + source = b'#define M(x) \\\n use(x)\nvoid f(){\n run();\n}\n' + formatted = b'#define M(x) \\\n use (x)\nvoid f(){\n run ();\n}\n' + candidate, skips = changed.local_edits(source, formatted, {1, 2, 4}) + self.assertEqual(b'#define M(x) \\\n use(x)\nvoid f(){\n run ();\n}\n', candidate) + self.assertTrue(skips) + + def test_crlf_and_deletion_only_ranges(self): + candidate, _ = changed.local_edits(b'int x=1;\r\n', b'int x = 1;\r\n', {1}) + self.assertEqual(b'int x = 1;\r\n', candidate) + self.assertEqual(set(), changed.hunk_lines(b'@@ -2 +1,0 @@\n-deleted\n')) + self.assertEqual({3, 4}, changed.hunk_lines(b'@@ -2 +3,2 @@\n+x\n+y\n')) + + def test_no_nonwhitespace_rewrite_is_accepted(self): + with self.assertRaisesRegex(ValueError, 'non-whitespace'): + changed.local_edits(b'int x=1;\n', b'int x = 2;\n', {1}) + + +class TokenGuardTests(unittest.TestCase): + def test_identifier_merge_and_literal_changes_are_rejected(self): + for before, after in [ + (b'operator const Type&();\n', b'operator constType&();\n'), + (b'const char* s = "a b";\n', b'const char* s = "ab";\n'), + (b'const char* s = R"x(a b)x";\n', b'const char* s = R"x(ab)x";\n'), + (b'int x = a + +b;\n', b'int x = a++b;\n'), + (b'const char* s = R"x(a\nb)x";\n', b'const char* s = R"x(ab)x";\n'), + ]: + with self.subTest(before=before): + with self.assertRaisesRegex(ValueError, 'token'): + changed.verify_tokens(before, after, 'clang') + + def test_whitespace_in_code_preserves_tokens(self): + changed.verify_tokens(b'if(x){run();}\n', b'if (x){run();}\n', 'clang') + + +class GitIntegrationTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + self.path = self.root / 'Common/example.cpp' + self.path.parent.mkdir() + self.path.write_bytes(b'void f(){\n int old=1;\n int value=2;\n}\n') + self.git('init', '-q') + self.git('add', '.') + self.git('-c', 'user.name=Formatter Test', '-c', 'user.email=test@example.invalid', + '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'base') + + def git(self, *args): + return subprocess.check_output(['git', '-C', str(self.root), *args]) + + def cli(self, args): + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + return changed.main(args) + + def test_default_preview_check_and_write_leave_index_untouched(self): + self.path.write_bytes(b'void f(){\n int old=1;\n int value=3;\n}\n') + self.git('add', '.') + staged = self.git('diff', '--cached', '--binary') + source = self.path.read_bytes() + common = ['--repo', str(self.root)] + self.assertEqual(0, self.cli(common)) + self.assertEqual(source, self.path.read_bytes()) + self.assertEqual(1, self.cli([*common, '--check'])) + self.assertEqual(0, self.cli([*common, '--write'])) + self.assertEqual(b'void f(){\n int old=1;\n int value = 3;\n}\n', self.path.read_bytes()) + self.assertEqual(staged, self.git('diff', '--cached', '--binary')) + self.assertEqual(0, self.cli([*common, '--check'])) + + def test_source_change_after_plan_is_refused(self): + plan = changed.Plan(self.path, self.path.read_bytes(), b'new text', {}) + self.path.write_bytes(b'user edit') + with self.assertRaisesRegex(ValueError, 'changed'): + changed.write_plans([plan]) + self.assertEqual(b'user edit', self.path.read_bytes()) + + def test_untracked_and_rename_only_files_are_not_formatted(self): + other = self.root / 'Common/new.cpp' + other.write_bytes(b'int untouched=0;\n') + self.assertEqual({}, changed.selected_lines(self.root, 'HEAD')) + self.git('mv', 'Common/example.cpp', 'Common/renamed.cpp') + self.assertEqual({}, changed.selected_lines(self.root, 'HEAD')) + + def test_filename_with_spaces_and_pathspec_characters(self): + path = self.root / 'Common/new [case].cpp' + path.write_bytes(b'int value=3;\n') + self.git('add', '.') + self.assertEqual(0, self.cli(['--repo', str(self.root), '--write'])) + self.assertEqual(b'int value = 3;\n', path.read_bytes()) + + def test_invalid_second_candidate_prevents_all_writes(self): + self.path.write_bytes(b'int first=1;\n') + other = self.root / 'Common/second.cpp' + other.write_bytes(b'int second=2;\n') + self.git('add', '.') + before = self.path.read_bytes(), other.read_bytes() + with patch.object(changed, 'verify_tokens', side_effect=[None, ValueError('token mismatch')]): + self.assertEqual(2, self.cli(['--repo', str(self.root), '--write'])) + self.assertEqual(before, (self.path.read_bytes(), other.read_bytes())) + + def test_snapshot_change_after_diff_selection_is_refused(self): + self.path.write_bytes(b'int value=3;\n') + selection = changed.selected_lines(self.root, 'HEAD') + self.path.write_bytes(b'user changed the file') + with self.assertRaisesRegex(ValueError, 'changed after measuring'): + changed.make_plans(self.root, selection, 'uncrustify', 'clang') + + def test_explicit_base_includes_committed_changes(self): + base = self.git('rev-parse', 'HEAD').decode().strip() + self.path.write_bytes(b'void f(){\n int old=1;\n int value=3;\n}\n') + self.git('add', '.') + self.git('-c', 'user.name=Formatter Test', '-c', 'user.email=test@example.invalid', + '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'edit') + self.assertEqual({}, changed.selected_lines(self.root, 'HEAD')) + self.assertEqual(0, self.cli(['--repo', str(self.root), '--base', base, '--write'])) + self.assertEqual(b'void f(){\n int old=1;\n int value = 3;\n}\n', self.path.read_bytes()) diff --git a/devtools/format/test_cmake.py b/devtools/format/test_cmake.py new file mode 100644 index 0000000000..c14193d220 --- /dev/null +++ b/devtools/format/test_cmake.py @@ -0,0 +1,78 @@ +"""CMake format targets: python3 -m unittest discover -s devtools/format -p test_cmake.py -v.""" + +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] + + +class CMakeFormattingTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory(prefix='format targets ') + self.addCleanup(self.directory.cleanup) + root = Path(self.directory.name) + self.repo, self.build, self.project = root / 'code tree', root / 'build tree', root / 'project' + self.project.mkdir() + (self.repo / 'Common').mkdir(parents=True) + (self.repo / 'devtools/format').mkdir(parents=True) + shutil.copy2(ROOT / '.uncrustify.cfg', self.repo / '.uncrustify.cfg') + shutil.copy2(ROOT / 'devtools/format/format_changed.py', self.repo / 'devtools/format/format_changed.py') + self.source = self.repo / 'Common/example.cpp' + self.source.write_bytes(b'void f(){\n int untouched=1;\n int changed=2;\n}\n') + self.git('init', '-q') + self.git('add', '.') + self.git('-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', + '-c', 'commit.gpgSign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'base') + self.marker = root / 'app-was-built' + self.project.joinpath('CMakeLists.txt').write_text( + 'cmake_minimum_required(VERSION 3.24)\nproject(FormatTargets NONE)\n' + f'include("{(ROOT / "SerialPrograms/cmake/Formatting.cmake").as_posix()}")\n' + f'pa_add_format_targets("{self.repo.as_posix()}")\n' + f'add_custom_target(app ALL COMMAND "${{CMAKE_COMMAND}}" -E touch "{self.marker.as_posix()}")\n' + ) + + def git(self, *args): + return subprocess.check_output(['git', '-C', str(self.repo), *args]) + + def configure(self, *args): + subprocess.run(['cmake', '-S', str(self.project), '-B', str(self.build), + '-DPA_FORMAT_PYTHON=' + sys.executable, *args], + capture_output=True, check=True) + + def target(self, name): + return subprocess.run(['cmake', '--build', str(self.build), '--target', name], capture_output=True) + + def test_check_write_and_no_application_dependency(self): + self.configure() + self.source.write_bytes(b'void f(){\n int untouched=1;\n int changed=3;\n}\n') + staged = self.git('diff', '--cached', '--binary') + self.assertNotEqual(0, self.target('format-check').returncode) + result = self.target('format') + self.assertEqual(0, result.returncode, result.stderr.decode()) + self.assertEqual(b'void f(){\n int untouched=1;\n int changed = 3;\n}\n', self.source.read_bytes()) + self.assertEqual(0, self.target('format-check').returncode) + self.assertEqual(staged, self.git('diff', '--cached', '--binary')) + self.assertFalse(self.marker.exists()) + + def test_missing_python_does_not_break_configure(self): + self.configure('-DPA_FORMAT_PYTHON=' + str(self.repo / 'missing-python')) + result = self.target('format') + self.assertNotEqual(0, result.returncode) + self.assertIn(b'Formatting needs Python 3.8+', result.stderr) + self.assertFalse(self.marker.exists()) + + def test_configured_parent_includes_committed_edits(self): + base = self.git('rev-parse', 'HEAD').decode().strip() + self.source.write_bytes(b'void f(){\n int untouched=1;\n int changed=3;\n}\n') + self.git('add', '.') + self.git('-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', + '-c', 'commit.gpgSign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'edit') + self.configure('-DPA_FORMAT_BASE=' + base) + self.assertEqual(0, self.target('format').returncode) + self.assertIn(b'int changed = 3;', self.source.read_bytes()) + self.assertIn(b'int untouched=1;', self.source.read_bytes()) diff --git a/devtools/format/test_config.py b/devtools/format/test_config.py new file mode 100644 index 0000000000..56c5a3b0e9 --- /dev/null +++ b/devtools/format/test_config.py @@ -0,0 +1,195 @@ +"""Check formatter behavior: python3 -m unittest discover -s devtools/format -v.""" + +import os +from pathlib import Path +import shlex +import subprocess +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +COMMAND = shlex.split(os.environ.get('UNCRUSTIFY', 'uncrustify')) + + +def format_cpp(source): + result = subprocess.run( + [*COMMAND, '-q', '-c', str(ROOT / '.uncrustify.cfg'), '-l', 'CPP'], + input=source, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ) + if result.stderr: + raise RuntimeError(result.stderr.decode(errors='replace')) + return result.stdout + + +class FormatterConfigTests(unittest.TestCase): + def test_pinned_version_and_valid_configuration(self): + version = subprocess.check_output([*COMMAND, '--version'], text=True) + self.assertRegex(version.strip(), r'^Uncrustify-0\.83\.0(?:_f)?$') + format_cpp(b'void f();\n') + + def test_exact_compact_braces_and_control_parentheses(self): + source = b'namespace Example {\nvoid f(){\nif(ready()) {\nrun();\n} else {\nstop();\n}\n}\n}\n' + expected = b'namespace Example{\nvoid f(){\n if (ready()){\n run();\n }else{\n stop();\n }\n}\n}\n' + self.assertEqual(expected, format_cpp(source)) + self.assertEqual(expected, format_cpp(expected)) + + def test_class_members_access_labels_and_type_attached_pointers(self): + source = b'class Thing{\npublic:\nvoid f(int *p){\n*p=1;\n}\n};\n' + expected = b'class Thing{\npublic:\n void f(int* p){\n *p = 1;\n }\n};\n' + self.assertEqual(expected, format_cpp(source)) + + def test_include_order_is_preserved_including_own_header_last(self): + source = b'#include \n#include "Common/Cpp/Exceptions.h"\n\n#include "Own.h"\n' + self.assertEqual(source, format_cpp(source)) + + def test_existing_lf_and_crlf_are_preserved(self): + for newline in (b'\n', b'\r\n'): + with self.subTest(newline=newline): + source = newline.join([b'void f(){', b' g();', b'}', b'']) + result = format_cpp(source) + if newline == b'\r\n': + self.assertNotIn(b'\n', result.replace(b'\r\n', b'')) + else: + self.assertNotIn(b'\r', result) + + def test_comments_and_long_lines_are_not_reflowed(self): + comment = b'// ' + b' '.join([b'keep this explanation intact'] * 8) + code = b' call(' + b', '.join(b'argument_' + str(i).encode() for i in range(25)) + b');' + result = format_cpp(b'void f(){\n' + comment + b'\n' + code + b'\n}\n') + self.assertIn(comment, result) + self.assertIn(code, result) + + def test_braced_single_line_control_bodies_are_expanded(self): + result = format_cpp(b'void f(){if (x){run();}else{stop();}}\n') + self.assertIn(b'if (x){\n', result) + self.assertIn(b'}else{\n', result) + self.assertNotIn(b'{run();}', result) + self.assertEqual(result, format_cpp(result)) + + def test_templates_designated_initializers_and_raw_strings(self): + source = ( + b'template \nstruct Case{\n T input;\n T expectation;\n};\n' + b'constexpr Case cases[] = {\n {.input = 1, .expectation = 2},\n};\n' + b'const char* text = R"tag(if(x) { } else { /* keep */ })tag";\n' + ) + result = format_cpp(source) + self.assertIn(b'R"tag(if(x) { } else { /* keep */ })tag"', result) + self.assertIn(b'.input = 1', result) + self.assertIn(b'.expectation = 2', result) + self.assertEqual(result, format_cpp(result)) + + def test_macro_continuations_and_token_pasting(self): + source = ( + b'#define JOIN(a, b) a ## b\n' + b'#define TRACE(x) do { \\\n' + b' trace(#x, x); \\\n' + b'} while (false)\n' + ) + result = format_cpp(source) + self.assertIn(b'a ## b', result) + self.assertIn(b'trace(#x, x);', result) + self.assertEqual(source.count(b'\\\n'), result.count(b'\\\n')) + self.assertEqual(result, format_cpp(result)) + + def test_constructor_comment_stays_before_body_brace(self): + source = ( + b'Thing::Thing()\n : m_value(0)\n' + b'// , m_other(1)\n{\n run();\n}\n' + ) + result = format_cpp(source) + self.assertIn(b'// , m_other(1)\n{', result) + self.assertEqual(result, format_cpp(result)) + + def test_known_inherited_class_spacing_gap(self): + # Unlike control/namespace braces, this case is not fully configurable. + source = b'struct Derived : public Base{\n int value;\n};\n' + self.assertIn(b'struct Derived : public Base {', format_cpp(source)) + + def test_conversion_operators_and_nested_templates_preserve_tokens(self): + source = ( + b'template \nstruct Holder{\n' + b' operator const Type&() const{ return value; }\n' + b' Type value;\n};\n' + b'std::vector>> values;\n' + ) + result = format_cpp(source) + self.assertIn(b'operator const Type&()', result) + self.assertNotIn(b'constType', result) + self.assertIn(b'Holder>>', result) + self.assertEqual(result, format_cpp(result)) + + def test_preserves_short_functions_and_empty_constructor(self): + source = ( + b'class Value{\npublic:\n' + b' Value()\n : m_value(0)\n {}\n' + b' int get() const{ return m_value; }\n' + b' void clear(){ m_value = 0; }\n' + b'private:\n int m_value;\n};\n' + ) + self.assertEqual(source, format_cpp(source)) + + def test_preserves_manual_spacing_within_overloads(self): + source = ( + b'class Value{\npublic:\n' + b' const Type& get() const{ return m_value; }\n' + b' Type& get() { return m_value; }\n' + b' const Type* data() const;\n' + b' Type* data();\n};\n' + ) + self.assertEqual(source, format_cpp(source)) + + def test_preserves_multiline_argument_and_closing_parenthesis_layout(self): + source = ( + b'void f(){\n call(\n first,\n second\n );\n' + b' auto value = build(\n Params{\n .count = 2,\n }\n );\n}\n' + ) + self.assertEqual(source, format_cpp(source)) + + def test_preserves_template_parameter_pack_spelling(self): + source = b'template \nvoid f(Args&&... args);\n' + self.assertEqual(source, format_cpp(source)) + + def test_known_leading_overload_alignment_gap(self): + source = ( + b'class Value{\npublic:\n' + b' const Type* data() const;\n' + b' Type* data();\n};\n' + ) + result = format_cpp(source) + self.assertIn(b'\n Type* data();', result) + self.assertNotEqual(source, result) + + def test_explicitly_protected_alignment_table_is_unchanged(self): + source = ( + b'class Value{\npublic:\n' + b'// *INDENT-OFF*\n' + b' const Type& get() const{ return m_value; }\n' + b' Type& get() { return m_value; }\n' + b'// *INDENT-ON*\n};\n' + ) + self.assertEqual(source, format_cpp(source)) + + def test_preserves_lambda_body_inside_call(self): + source = ( + b'void f(){\n ScopeExit cleanup([]{\n stop();\n });\n}\n' + ) + self.assertEqual(source, format_cpp(source)) + + def test_preserves_attached_catch_chain(self): + source = ( + b'void f(){\n try{\n run();\n }catch (const First& error){\n' + b' log(error);\n }catch (const Second& error){\n' + b' log(error);\n }\n}\n' + ) + self.assertEqual(source, format_cpp(source)) + + def test_nested_lambda_and_initializer_table_are_stable(self): + sources = [ + b'void f(){\n dispatch(\n scope,\n [](Handle& h){\n run(h);\n }\n );\n done();\n}\n', + b'void f(){\n static const Database value({\n {A, "a"},\n {B, "b"},\n });\n}\n', + b'void f(){\n try{\n run();\n }catch (Error& e){\n report(\n "message");\n }\n}\n', + ] + for source in sources: + with self.subTest(source=source): + result = format_cpp(source) + self.assertEqual(result, format_cpp(result))